]> Git Repo - J-linux.git/blob - drivers/net/ethernet/intel/igc/igc_main.c
igc: Remove delay during TX ring configuration
[J-linux.git] / drivers / net / ethernet / intel / igc / igc_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c)  2018 Intel Corporation */
3
4 #include <linux/module.h>
5 #include <linux/types.h>
6 #include <linux/if_vlan.h>
7 #include <linux/tcp.h>
8 #include <linux/udp.h>
9 #include <linux/ip.h>
10 #include <linux/pm_runtime.h>
11 #include <net/pkt_sched.h>
12 #include <linux/bpf_trace.h>
13 #include <net/xdp_sock_drv.h>
14 #include <linux/pci.h>
15
16 #include <net/ipv6.h>
17
18 #include "igc.h"
19 #include "igc_hw.h"
20 #include "igc_tsn.h"
21 #include "igc_xdp.h"
22
23 #define DRV_SUMMARY     "Intel(R) 2.5G Ethernet Linux Driver"
24
25 #define DEFAULT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK)
26
27 #define IGC_XDP_PASS            0
28 #define IGC_XDP_CONSUMED        BIT(0)
29 #define IGC_XDP_TX              BIT(1)
30 #define IGC_XDP_REDIRECT        BIT(2)
31
32 static int debug = -1;
33
34 MODULE_AUTHOR("Intel Corporation, <[email protected]>");
35 MODULE_DESCRIPTION(DRV_SUMMARY);
36 MODULE_LICENSE("GPL v2");
37 module_param(debug, int, 0);
38 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
39
40 char igc_driver_name[] = "igc";
41 static const char igc_driver_string[] = DRV_SUMMARY;
42 static const char igc_copyright[] =
43         "Copyright(c) 2018 Intel Corporation.";
44
45 static const struct igc_info *igc_info_tbl[] = {
46         [board_base] = &igc_base_info,
47 };
48
49 static const struct pci_device_id igc_pci_tbl[] = {
50         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_LM), board_base },
51         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_V), board_base },
52         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_I), board_base },
53         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I220_V), board_base },
54         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_K), board_base },
55         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_K2), board_base },
56         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_K), board_base },
57         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_LMVP), board_base },
58         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_LMVP), board_base },
59         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_IT), board_base },
60         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_LM), board_base },
61         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_V), board_base },
62         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_IT), board_base },
63         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I221_V), board_base },
64         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I226_BLANK_NVM), board_base },
65         { PCI_VDEVICE(INTEL, IGC_DEV_ID_I225_BLANK_NVM), board_base },
66         /* required last entry */
67         {0, }
68 };
69
70 MODULE_DEVICE_TABLE(pci, igc_pci_tbl);
71
72 enum latency_range {
73         lowest_latency = 0,
74         low_latency = 1,
75         bulk_latency = 2,
76         latency_invalid = 255
77 };
78
79 void igc_reset(struct igc_adapter *adapter)
80 {
81         struct net_device *dev = adapter->netdev;
82         struct igc_hw *hw = &adapter->hw;
83         struct igc_fc_info *fc = &hw->fc;
84         u32 pba, hwm;
85
86         /* Repartition PBA for greater than 9k MTU if required */
87         pba = IGC_PBA_34K;
88
89         /* flow control settings
90          * The high water mark must be low enough to fit one full frame
91          * after transmitting the pause frame.  As such we must have enough
92          * space to allow for us to complete our current transmit and then
93          * receive the frame that is in progress from the link partner.
94          * Set it to:
95          * - the full Rx FIFO size minus one full Tx plus one full Rx frame
96          */
97         hwm = (pba << 10) - (adapter->max_frame_size + MAX_JUMBO_FRAME_SIZE);
98
99         fc->high_water = hwm & 0xFFFFFFF0;      /* 16-byte granularity */
100         fc->low_water = fc->high_water - 16;
101         fc->pause_time = 0xFFFF;
102         fc->send_xon = 1;
103         fc->current_mode = fc->requested_mode;
104
105         hw->mac.ops.reset_hw(hw);
106
107         if (hw->mac.ops.init_hw(hw))
108                 netdev_err(dev, "Error on hardware initialization\n");
109
110         /* Re-establish EEE setting */
111         igc_set_eee_i225(hw, true, true, true);
112
113         if (!netif_running(adapter->netdev))
114                 igc_power_down_phy_copper_base(&adapter->hw);
115
116         /* Enable HW to recognize an 802.1Q VLAN Ethernet packet */
117         wr32(IGC_VET, ETH_P_8021Q);
118
119         /* Re-enable PTP, where applicable. */
120         igc_ptp_reset(adapter);
121
122         /* Re-enable TSN offloading, where applicable. */
123         igc_tsn_reset(adapter);
124
125         igc_get_phy_info(hw);
126 }
127
128 /**
129  * igc_power_up_link - Power up the phy link
130  * @adapter: address of board private structure
131  */
132 static void igc_power_up_link(struct igc_adapter *adapter)
133 {
134         igc_reset_phy(&adapter->hw);
135
136         igc_power_up_phy_copper(&adapter->hw);
137
138         igc_setup_link(&adapter->hw);
139 }
140
141 /**
142  * igc_release_hw_control - release control of the h/w to f/w
143  * @adapter: address of board private structure
144  *
145  * igc_release_hw_control resets CTRL_EXT:DRV_LOAD bit.
146  * For ASF and Pass Through versions of f/w this means that the
147  * driver is no longer loaded.
148  */
149 static void igc_release_hw_control(struct igc_adapter *adapter)
150 {
151         struct igc_hw *hw = &adapter->hw;
152         u32 ctrl_ext;
153
154         if (!pci_device_is_present(adapter->pdev))
155                 return;
156
157         /* Let firmware take over control of h/w */
158         ctrl_ext = rd32(IGC_CTRL_EXT);
159         wr32(IGC_CTRL_EXT,
160              ctrl_ext & ~IGC_CTRL_EXT_DRV_LOAD);
161 }
162
163 /**
164  * igc_get_hw_control - get control of the h/w from f/w
165  * @adapter: address of board private structure
166  *
167  * igc_get_hw_control sets CTRL_EXT:DRV_LOAD bit.
168  * For ASF and Pass Through versions of f/w this means that
169  * the driver is loaded.
170  */
171 static void igc_get_hw_control(struct igc_adapter *adapter)
172 {
173         struct igc_hw *hw = &adapter->hw;
174         u32 ctrl_ext;
175
176         /* Let firmware know the driver has taken over */
177         ctrl_ext = rd32(IGC_CTRL_EXT);
178         wr32(IGC_CTRL_EXT,
179              ctrl_ext | IGC_CTRL_EXT_DRV_LOAD);
180 }
181
182 static void igc_unmap_tx_buffer(struct device *dev, struct igc_tx_buffer *buf)
183 {
184         dma_unmap_single(dev, dma_unmap_addr(buf, dma),
185                          dma_unmap_len(buf, len), DMA_TO_DEVICE);
186
187         dma_unmap_len_set(buf, len, 0);
188 }
189
190 /**
191  * igc_clean_tx_ring - Free Tx Buffers
192  * @tx_ring: ring to be cleaned
193  */
194 static void igc_clean_tx_ring(struct igc_ring *tx_ring)
195 {
196         u16 i = tx_ring->next_to_clean;
197         struct igc_tx_buffer *tx_buffer = &tx_ring->tx_buffer_info[i];
198         u32 xsk_frames = 0;
199
200         while (i != tx_ring->next_to_use) {
201                 union igc_adv_tx_desc *eop_desc, *tx_desc;
202
203                 switch (tx_buffer->type) {
204                 case IGC_TX_BUFFER_TYPE_XSK:
205                         xsk_frames++;
206                         break;
207                 case IGC_TX_BUFFER_TYPE_XDP:
208                         xdp_return_frame(tx_buffer->xdpf);
209                         igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
210                         break;
211                 case IGC_TX_BUFFER_TYPE_SKB:
212                         dev_kfree_skb_any(tx_buffer->skb);
213                         igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
214                         break;
215                 default:
216                         netdev_warn_once(tx_ring->netdev, "Unknown Tx buffer type\n");
217                         break;
218                 }
219
220                 /* check for eop_desc to determine the end of the packet */
221                 eop_desc = tx_buffer->next_to_watch;
222                 tx_desc = IGC_TX_DESC(tx_ring, i);
223
224                 /* unmap remaining buffers */
225                 while (tx_desc != eop_desc) {
226                         tx_buffer++;
227                         tx_desc++;
228                         i++;
229                         if (unlikely(i == tx_ring->count)) {
230                                 i = 0;
231                                 tx_buffer = tx_ring->tx_buffer_info;
232                                 tx_desc = IGC_TX_DESC(tx_ring, 0);
233                         }
234
235                         /* unmap any remaining paged data */
236                         if (dma_unmap_len(tx_buffer, len))
237                                 igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
238                 }
239
240                 tx_buffer->next_to_watch = NULL;
241
242                 /* move us one more past the eop_desc for start of next pkt */
243                 tx_buffer++;
244                 i++;
245                 if (unlikely(i == tx_ring->count)) {
246                         i = 0;
247                         tx_buffer = tx_ring->tx_buffer_info;
248                 }
249         }
250
251         if (tx_ring->xsk_pool && xsk_frames)
252                 xsk_tx_completed(tx_ring->xsk_pool, xsk_frames);
253
254         /* reset BQL for queue */
255         netdev_tx_reset_queue(txring_txq(tx_ring));
256
257         /* Zero out the buffer ring */
258         memset(tx_ring->tx_buffer_info, 0,
259                sizeof(*tx_ring->tx_buffer_info) * tx_ring->count);
260
261         /* Zero out the descriptor ring */
262         memset(tx_ring->desc, 0, tx_ring->size);
263
264         /* reset next_to_use and next_to_clean */
265         tx_ring->next_to_use = 0;
266         tx_ring->next_to_clean = 0;
267 }
268
269 /**
270  * igc_free_tx_resources - Free Tx Resources per Queue
271  * @tx_ring: Tx descriptor ring for a specific queue
272  *
273  * Free all transmit software resources
274  */
275 void igc_free_tx_resources(struct igc_ring *tx_ring)
276 {
277         igc_disable_tx_ring(tx_ring);
278
279         vfree(tx_ring->tx_buffer_info);
280         tx_ring->tx_buffer_info = NULL;
281
282         /* if not set, then don't free */
283         if (!tx_ring->desc)
284                 return;
285
286         dma_free_coherent(tx_ring->dev, tx_ring->size,
287                           tx_ring->desc, tx_ring->dma);
288
289         tx_ring->desc = NULL;
290 }
291
292 /**
293  * igc_free_all_tx_resources - Free Tx Resources for All Queues
294  * @adapter: board private structure
295  *
296  * Free all transmit software resources
297  */
298 static void igc_free_all_tx_resources(struct igc_adapter *adapter)
299 {
300         int i;
301
302         for (i = 0; i < adapter->num_tx_queues; i++)
303                 igc_free_tx_resources(adapter->tx_ring[i]);
304 }
305
306 /**
307  * igc_clean_all_tx_rings - Free Tx Buffers for all queues
308  * @adapter: board private structure
309  */
310 static void igc_clean_all_tx_rings(struct igc_adapter *adapter)
311 {
312         int i;
313
314         for (i = 0; i < adapter->num_tx_queues; i++)
315                 if (adapter->tx_ring[i])
316                         igc_clean_tx_ring(adapter->tx_ring[i]);
317 }
318
319 /**
320  * igc_setup_tx_resources - allocate Tx resources (Descriptors)
321  * @tx_ring: tx descriptor ring (for a specific queue) to setup
322  *
323  * Return 0 on success, negative on failure
324  */
325 int igc_setup_tx_resources(struct igc_ring *tx_ring)
326 {
327         struct net_device *ndev = tx_ring->netdev;
328         struct device *dev = tx_ring->dev;
329         int size = 0;
330
331         size = sizeof(struct igc_tx_buffer) * tx_ring->count;
332         tx_ring->tx_buffer_info = vzalloc(size);
333         if (!tx_ring->tx_buffer_info)
334                 goto err;
335
336         /* round up to nearest 4K */
337         tx_ring->size = tx_ring->count * sizeof(union igc_adv_tx_desc);
338         tx_ring->size = ALIGN(tx_ring->size, 4096);
339
340         tx_ring->desc = dma_alloc_coherent(dev, tx_ring->size,
341                                            &tx_ring->dma, GFP_KERNEL);
342
343         if (!tx_ring->desc)
344                 goto err;
345
346         tx_ring->next_to_use = 0;
347         tx_ring->next_to_clean = 0;
348
349         return 0;
350
351 err:
352         vfree(tx_ring->tx_buffer_info);
353         netdev_err(ndev, "Unable to allocate memory for Tx descriptor ring\n");
354         return -ENOMEM;
355 }
356
357 /**
358  * igc_setup_all_tx_resources - wrapper to allocate Tx resources for all queues
359  * @adapter: board private structure
360  *
361  * Return 0 on success, negative on failure
362  */
363 static int igc_setup_all_tx_resources(struct igc_adapter *adapter)
364 {
365         struct net_device *dev = adapter->netdev;
366         int i, err = 0;
367
368         for (i = 0; i < adapter->num_tx_queues; i++) {
369                 err = igc_setup_tx_resources(adapter->tx_ring[i]);
370                 if (err) {
371                         netdev_err(dev, "Error on Tx queue %u setup\n", i);
372                         for (i--; i >= 0; i--)
373                                 igc_free_tx_resources(adapter->tx_ring[i]);
374                         break;
375                 }
376         }
377
378         return err;
379 }
380
381 static void igc_clean_rx_ring_page_shared(struct igc_ring *rx_ring)
382 {
383         u16 i = rx_ring->next_to_clean;
384
385         dev_kfree_skb(rx_ring->skb);
386         rx_ring->skb = NULL;
387
388         /* Free all the Rx ring sk_buffs */
389         while (i != rx_ring->next_to_alloc) {
390                 struct igc_rx_buffer *buffer_info = &rx_ring->rx_buffer_info[i];
391
392                 /* Invalidate cache lines that may have been written to by
393                  * device so that we avoid corrupting memory.
394                  */
395                 dma_sync_single_range_for_cpu(rx_ring->dev,
396                                               buffer_info->dma,
397                                               buffer_info->page_offset,
398                                               igc_rx_bufsz(rx_ring),
399                                               DMA_FROM_DEVICE);
400
401                 /* free resources associated with mapping */
402                 dma_unmap_page_attrs(rx_ring->dev,
403                                      buffer_info->dma,
404                                      igc_rx_pg_size(rx_ring),
405                                      DMA_FROM_DEVICE,
406                                      IGC_RX_DMA_ATTR);
407                 __page_frag_cache_drain(buffer_info->page,
408                                         buffer_info->pagecnt_bias);
409
410                 i++;
411                 if (i == rx_ring->count)
412                         i = 0;
413         }
414 }
415
416 static void igc_clean_rx_ring_xsk_pool(struct igc_ring *ring)
417 {
418         struct igc_rx_buffer *bi;
419         u16 i;
420
421         for (i = 0; i < ring->count; i++) {
422                 bi = &ring->rx_buffer_info[i];
423                 if (!bi->xdp)
424                         continue;
425
426                 xsk_buff_free(bi->xdp);
427                 bi->xdp = NULL;
428         }
429 }
430
431 /**
432  * igc_clean_rx_ring - Free Rx Buffers per Queue
433  * @ring: ring to free buffers from
434  */
435 static void igc_clean_rx_ring(struct igc_ring *ring)
436 {
437         if (ring->xsk_pool)
438                 igc_clean_rx_ring_xsk_pool(ring);
439         else
440                 igc_clean_rx_ring_page_shared(ring);
441
442         clear_ring_uses_large_buffer(ring);
443
444         ring->next_to_alloc = 0;
445         ring->next_to_clean = 0;
446         ring->next_to_use = 0;
447 }
448
449 /**
450  * igc_clean_all_rx_rings - Free Rx Buffers for all queues
451  * @adapter: board private structure
452  */
453 static void igc_clean_all_rx_rings(struct igc_adapter *adapter)
454 {
455         int i;
456
457         for (i = 0; i < adapter->num_rx_queues; i++)
458                 if (adapter->rx_ring[i])
459                         igc_clean_rx_ring(adapter->rx_ring[i]);
460 }
461
462 /**
463  * igc_free_rx_resources - Free Rx Resources
464  * @rx_ring: ring to clean the resources from
465  *
466  * Free all receive software resources
467  */
468 void igc_free_rx_resources(struct igc_ring *rx_ring)
469 {
470         igc_clean_rx_ring(rx_ring);
471
472         xdp_rxq_info_unreg(&rx_ring->xdp_rxq);
473
474         vfree(rx_ring->rx_buffer_info);
475         rx_ring->rx_buffer_info = NULL;
476
477         /* if not set, then don't free */
478         if (!rx_ring->desc)
479                 return;
480
481         dma_free_coherent(rx_ring->dev, rx_ring->size,
482                           rx_ring->desc, rx_ring->dma);
483
484         rx_ring->desc = NULL;
485 }
486
487 /**
488  * igc_free_all_rx_resources - Free Rx Resources for All Queues
489  * @adapter: board private structure
490  *
491  * Free all receive software resources
492  */
493 static void igc_free_all_rx_resources(struct igc_adapter *adapter)
494 {
495         int i;
496
497         for (i = 0; i < adapter->num_rx_queues; i++)
498                 igc_free_rx_resources(adapter->rx_ring[i]);
499 }
500
501 /**
502  * igc_setup_rx_resources - allocate Rx resources (Descriptors)
503  * @rx_ring:    rx descriptor ring (for a specific queue) to setup
504  *
505  * Returns 0 on success, negative on failure
506  */
507 int igc_setup_rx_resources(struct igc_ring *rx_ring)
508 {
509         struct net_device *ndev = rx_ring->netdev;
510         struct device *dev = rx_ring->dev;
511         u8 index = rx_ring->queue_index;
512         int size, desc_len, res;
513
514         /* XDP RX-queue info */
515         if (xdp_rxq_info_is_reg(&rx_ring->xdp_rxq))
516                 xdp_rxq_info_unreg(&rx_ring->xdp_rxq);
517         res = xdp_rxq_info_reg(&rx_ring->xdp_rxq, ndev, index,
518                                rx_ring->q_vector->napi.napi_id);
519         if (res < 0) {
520                 netdev_err(ndev, "Failed to register xdp_rxq index %u\n",
521                            index);
522                 return res;
523         }
524
525         size = sizeof(struct igc_rx_buffer) * rx_ring->count;
526         rx_ring->rx_buffer_info = vzalloc(size);
527         if (!rx_ring->rx_buffer_info)
528                 goto err;
529
530         desc_len = sizeof(union igc_adv_rx_desc);
531
532         /* Round up to nearest 4K */
533         rx_ring->size = rx_ring->count * desc_len;
534         rx_ring->size = ALIGN(rx_ring->size, 4096);
535
536         rx_ring->desc = dma_alloc_coherent(dev, rx_ring->size,
537                                            &rx_ring->dma, GFP_KERNEL);
538
539         if (!rx_ring->desc)
540                 goto err;
541
542         rx_ring->next_to_alloc = 0;
543         rx_ring->next_to_clean = 0;
544         rx_ring->next_to_use = 0;
545
546         return 0;
547
548 err:
549         xdp_rxq_info_unreg(&rx_ring->xdp_rxq);
550         vfree(rx_ring->rx_buffer_info);
551         rx_ring->rx_buffer_info = NULL;
552         netdev_err(ndev, "Unable to allocate memory for Rx descriptor ring\n");
553         return -ENOMEM;
554 }
555
556 /**
557  * igc_setup_all_rx_resources - wrapper to allocate Rx resources
558  *                                (Descriptors) for all queues
559  * @adapter: board private structure
560  *
561  * Return 0 on success, negative on failure
562  */
563 static int igc_setup_all_rx_resources(struct igc_adapter *adapter)
564 {
565         struct net_device *dev = adapter->netdev;
566         int i, err = 0;
567
568         for (i = 0; i < adapter->num_rx_queues; i++) {
569                 err = igc_setup_rx_resources(adapter->rx_ring[i]);
570                 if (err) {
571                         netdev_err(dev, "Error on Rx queue %u setup\n", i);
572                         for (i--; i >= 0; i--)
573                                 igc_free_rx_resources(adapter->rx_ring[i]);
574                         break;
575                 }
576         }
577
578         return err;
579 }
580
581 static struct xsk_buff_pool *igc_get_xsk_pool(struct igc_adapter *adapter,
582                                               struct igc_ring *ring)
583 {
584         if (!igc_xdp_is_enabled(adapter) ||
585             !test_bit(IGC_RING_FLAG_AF_XDP_ZC, &ring->flags))
586                 return NULL;
587
588         return xsk_get_pool_from_qid(ring->netdev, ring->queue_index);
589 }
590
591 /**
592  * igc_configure_rx_ring - Configure a receive ring after Reset
593  * @adapter: board private structure
594  * @ring: receive ring to be configured
595  *
596  * Configure the Rx unit of the MAC after a reset.
597  */
598 static void igc_configure_rx_ring(struct igc_adapter *adapter,
599                                   struct igc_ring *ring)
600 {
601         struct igc_hw *hw = &adapter->hw;
602         union igc_adv_rx_desc *rx_desc;
603         int reg_idx = ring->reg_idx;
604         u32 srrctl = 0, rxdctl = 0;
605         u64 rdba = ring->dma;
606         u32 buf_size;
607
608         xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
609         ring->xsk_pool = igc_get_xsk_pool(adapter, ring);
610         if (ring->xsk_pool) {
611                 WARN_ON(xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
612                                                    MEM_TYPE_XSK_BUFF_POOL,
613                                                    NULL));
614                 xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
615         } else {
616                 WARN_ON(xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
617                                                    MEM_TYPE_PAGE_SHARED,
618                                                    NULL));
619         }
620
621         if (igc_xdp_is_enabled(adapter))
622                 set_ring_uses_large_buffer(ring);
623
624         /* disable the queue */
625         wr32(IGC_RXDCTL(reg_idx), 0);
626
627         /* Set DMA base address registers */
628         wr32(IGC_RDBAL(reg_idx),
629              rdba & 0x00000000ffffffffULL);
630         wr32(IGC_RDBAH(reg_idx), rdba >> 32);
631         wr32(IGC_RDLEN(reg_idx),
632              ring->count * sizeof(union igc_adv_rx_desc));
633
634         /* initialize head and tail */
635         ring->tail = adapter->io_addr + IGC_RDT(reg_idx);
636         wr32(IGC_RDH(reg_idx), 0);
637         writel(0, ring->tail);
638
639         /* reset next-to- use/clean to place SW in sync with hardware */
640         ring->next_to_clean = 0;
641         ring->next_to_use = 0;
642
643         if (ring->xsk_pool)
644                 buf_size = xsk_pool_get_rx_frame_size(ring->xsk_pool);
645         else if (ring_uses_large_buffer(ring))
646                 buf_size = IGC_RXBUFFER_3072;
647         else
648                 buf_size = IGC_RXBUFFER_2048;
649
650         srrctl = rd32(IGC_SRRCTL(reg_idx));
651         srrctl &= ~(IGC_SRRCTL_BSIZEPKT_MASK | IGC_SRRCTL_BSIZEHDR_MASK |
652                     IGC_SRRCTL_DESCTYPE_MASK);
653         srrctl |= IGC_SRRCTL_BSIZEHDR(IGC_RX_HDR_LEN);
654         srrctl |= IGC_SRRCTL_BSIZEPKT(buf_size);
655         srrctl |= IGC_SRRCTL_DESCTYPE_ADV_ONEBUF;
656
657         wr32(IGC_SRRCTL(reg_idx), srrctl);
658
659         rxdctl |= IGC_RX_PTHRESH;
660         rxdctl |= IGC_RX_HTHRESH << 8;
661         rxdctl |= IGC_RX_WTHRESH << 16;
662
663         /* initialize rx_buffer_info */
664         memset(ring->rx_buffer_info, 0,
665                sizeof(struct igc_rx_buffer) * ring->count);
666
667         /* initialize Rx descriptor 0 */
668         rx_desc = IGC_RX_DESC(ring, 0);
669         rx_desc->wb.upper.length = 0;
670
671         /* enable receive descriptor fetching */
672         rxdctl |= IGC_RXDCTL_QUEUE_ENABLE;
673
674         wr32(IGC_RXDCTL(reg_idx), rxdctl);
675 }
676
677 /**
678  * igc_configure_rx - Configure receive Unit after Reset
679  * @adapter: board private structure
680  *
681  * Configure the Rx unit of the MAC after a reset.
682  */
683 static void igc_configure_rx(struct igc_adapter *adapter)
684 {
685         int i;
686
687         /* Setup the HW Rx Head and Tail Descriptor Pointers and
688          * the Base and Length of the Rx Descriptor Ring
689          */
690         for (i = 0; i < adapter->num_rx_queues; i++)
691                 igc_configure_rx_ring(adapter, adapter->rx_ring[i]);
692 }
693
694 /**
695  * igc_configure_tx_ring - Configure transmit ring after Reset
696  * @adapter: board private structure
697  * @ring: tx ring to configure
698  *
699  * Configure a transmit ring after a reset.
700  */
701 static void igc_configure_tx_ring(struct igc_adapter *adapter,
702                                   struct igc_ring *ring)
703 {
704         struct igc_hw *hw = &adapter->hw;
705         int reg_idx = ring->reg_idx;
706         u64 tdba = ring->dma;
707         u32 txdctl = 0;
708
709         ring->xsk_pool = igc_get_xsk_pool(adapter, ring);
710
711         /* disable the queue */
712         wr32(IGC_TXDCTL(reg_idx), 0);
713         wrfl();
714
715         wr32(IGC_TDLEN(reg_idx),
716              ring->count * sizeof(union igc_adv_tx_desc));
717         wr32(IGC_TDBAL(reg_idx),
718              tdba & 0x00000000ffffffffULL);
719         wr32(IGC_TDBAH(reg_idx), tdba >> 32);
720
721         ring->tail = adapter->io_addr + IGC_TDT(reg_idx);
722         wr32(IGC_TDH(reg_idx), 0);
723         writel(0, ring->tail);
724
725         txdctl |= IGC_TX_PTHRESH;
726         txdctl |= IGC_TX_HTHRESH << 8;
727         txdctl |= IGC_TX_WTHRESH << 16;
728
729         txdctl |= IGC_TXDCTL_QUEUE_ENABLE;
730         wr32(IGC_TXDCTL(reg_idx), txdctl);
731 }
732
733 /**
734  * igc_configure_tx - Configure transmit Unit after Reset
735  * @adapter: board private structure
736  *
737  * Configure the Tx unit of the MAC after a reset.
738  */
739 static void igc_configure_tx(struct igc_adapter *adapter)
740 {
741         int i;
742
743         for (i = 0; i < adapter->num_tx_queues; i++)
744                 igc_configure_tx_ring(adapter, adapter->tx_ring[i]);
745 }
746
747 /**
748  * igc_setup_mrqc - configure the multiple receive queue control registers
749  * @adapter: Board private structure
750  */
751 static void igc_setup_mrqc(struct igc_adapter *adapter)
752 {
753         struct igc_hw *hw = &adapter->hw;
754         u32 j, num_rx_queues;
755         u32 mrqc, rxcsum;
756         u32 rss_key[10];
757
758         netdev_rss_key_fill(rss_key, sizeof(rss_key));
759         for (j = 0; j < 10; j++)
760                 wr32(IGC_RSSRK(j), rss_key[j]);
761
762         num_rx_queues = adapter->rss_queues;
763
764         if (adapter->rss_indir_tbl_init != num_rx_queues) {
765                 for (j = 0; j < IGC_RETA_SIZE; j++)
766                         adapter->rss_indir_tbl[j] =
767                         (j * num_rx_queues) / IGC_RETA_SIZE;
768                 adapter->rss_indir_tbl_init = num_rx_queues;
769         }
770         igc_write_rss_indir_tbl(adapter);
771
772         /* Disable raw packet checksumming so that RSS hash is placed in
773          * descriptor on writeback.  No need to enable TCP/UDP/IP checksum
774          * offloads as they are enabled by default
775          */
776         rxcsum = rd32(IGC_RXCSUM);
777         rxcsum |= IGC_RXCSUM_PCSD;
778
779         /* Enable Receive Checksum Offload for SCTP */
780         rxcsum |= IGC_RXCSUM_CRCOFL;
781
782         /* Don't need to set TUOFL or IPOFL, they default to 1 */
783         wr32(IGC_RXCSUM, rxcsum);
784
785         /* Generate RSS hash based on packet types, TCP/UDP
786          * port numbers and/or IPv4/v6 src and dst addresses
787          */
788         mrqc = IGC_MRQC_RSS_FIELD_IPV4 |
789                IGC_MRQC_RSS_FIELD_IPV4_TCP |
790                IGC_MRQC_RSS_FIELD_IPV6 |
791                IGC_MRQC_RSS_FIELD_IPV6_TCP |
792                IGC_MRQC_RSS_FIELD_IPV6_TCP_EX;
793
794         if (adapter->flags & IGC_FLAG_RSS_FIELD_IPV4_UDP)
795                 mrqc |= IGC_MRQC_RSS_FIELD_IPV4_UDP;
796         if (adapter->flags & IGC_FLAG_RSS_FIELD_IPV6_UDP)
797                 mrqc |= IGC_MRQC_RSS_FIELD_IPV6_UDP;
798
799         mrqc |= IGC_MRQC_ENABLE_RSS_MQ;
800
801         wr32(IGC_MRQC, mrqc);
802 }
803
804 /**
805  * igc_setup_rctl - configure the receive control registers
806  * @adapter: Board private structure
807  */
808 static void igc_setup_rctl(struct igc_adapter *adapter)
809 {
810         struct igc_hw *hw = &adapter->hw;
811         u32 rctl;
812
813         rctl = rd32(IGC_RCTL);
814
815         rctl &= ~(3 << IGC_RCTL_MO_SHIFT);
816         rctl &= ~(IGC_RCTL_LBM_TCVR | IGC_RCTL_LBM_MAC);
817
818         rctl |= IGC_RCTL_EN | IGC_RCTL_BAM | IGC_RCTL_RDMTS_HALF |
819                 (hw->mac.mc_filter_type << IGC_RCTL_MO_SHIFT);
820
821         /* enable stripping of CRC. Newer features require
822          * that the HW strips the CRC.
823          */
824         rctl |= IGC_RCTL_SECRC;
825
826         /* disable store bad packets and clear size bits. */
827         rctl &= ~(IGC_RCTL_SBP | IGC_RCTL_SZ_256);
828
829         /* enable LPE to allow for reception of jumbo frames */
830         rctl |= IGC_RCTL_LPE;
831
832         /* disable queue 0 to prevent tail write w/o re-config */
833         wr32(IGC_RXDCTL(0), 0);
834
835         /* This is useful for sniffing bad packets. */
836         if (adapter->netdev->features & NETIF_F_RXALL) {
837                 /* UPE and MPE will be handled by normal PROMISC logic
838                  * in set_rx_mode
839                  */
840                 rctl |= (IGC_RCTL_SBP | /* Receive bad packets */
841                          IGC_RCTL_BAM | /* RX All Bcast Pkts */
842                          IGC_RCTL_PMCF); /* RX All MAC Ctrl Pkts */
843
844                 rctl &= ~(IGC_RCTL_DPF | /* Allow filtered pause */
845                           IGC_RCTL_CFIEN); /* Disable VLAN CFIEN Filter */
846         }
847
848         wr32(IGC_RCTL, rctl);
849 }
850
851 /**
852  * igc_setup_tctl - configure the transmit control registers
853  * @adapter: Board private structure
854  */
855 static void igc_setup_tctl(struct igc_adapter *adapter)
856 {
857         struct igc_hw *hw = &adapter->hw;
858         u32 tctl;
859
860         /* disable queue 0 which icould be enabled by default */
861         wr32(IGC_TXDCTL(0), 0);
862
863         /* Program the Transmit Control Register */
864         tctl = rd32(IGC_TCTL);
865         tctl &= ~IGC_TCTL_CT;
866         tctl |= IGC_TCTL_PSP | IGC_TCTL_RTLC |
867                 (IGC_COLLISION_THRESHOLD << IGC_CT_SHIFT);
868
869         /* Enable transmits */
870         tctl |= IGC_TCTL_EN;
871
872         wr32(IGC_TCTL, tctl);
873 }
874
875 /**
876  * igc_set_mac_filter_hw() - Set MAC address filter in hardware
877  * @adapter: Pointer to adapter where the filter should be set
878  * @index: Filter index
879  * @type: MAC address filter type (source or destination)
880  * @addr: MAC address
881  * @queue: If non-negative, queue assignment feature is enabled and frames
882  *         matching the filter are enqueued onto 'queue'. Otherwise, queue
883  *         assignment is disabled.
884  */
885 static void igc_set_mac_filter_hw(struct igc_adapter *adapter, int index,
886                                   enum igc_mac_filter_type type,
887                                   const u8 *addr, int queue)
888 {
889         struct net_device *dev = adapter->netdev;
890         struct igc_hw *hw = &adapter->hw;
891         u32 ral, rah;
892
893         if (WARN_ON(index >= hw->mac.rar_entry_count))
894                 return;
895
896         ral = le32_to_cpup((__le32 *)(addr));
897         rah = le16_to_cpup((__le16 *)(addr + 4));
898
899         if (type == IGC_MAC_FILTER_TYPE_SRC) {
900                 rah &= ~IGC_RAH_ASEL_MASK;
901                 rah |= IGC_RAH_ASEL_SRC_ADDR;
902         }
903
904         if (queue >= 0) {
905                 rah &= ~IGC_RAH_QSEL_MASK;
906                 rah |= (queue << IGC_RAH_QSEL_SHIFT);
907                 rah |= IGC_RAH_QSEL_ENABLE;
908         }
909
910         rah |= IGC_RAH_AV;
911
912         wr32(IGC_RAL(index), ral);
913         wr32(IGC_RAH(index), rah);
914
915         netdev_dbg(dev, "MAC address filter set in HW: index %d", index);
916 }
917
918 /**
919  * igc_clear_mac_filter_hw() - Clear MAC address filter in hardware
920  * @adapter: Pointer to adapter where the filter should be cleared
921  * @index: Filter index
922  */
923 static void igc_clear_mac_filter_hw(struct igc_adapter *adapter, int index)
924 {
925         struct net_device *dev = adapter->netdev;
926         struct igc_hw *hw = &adapter->hw;
927
928         if (WARN_ON(index >= hw->mac.rar_entry_count))
929                 return;
930
931         wr32(IGC_RAL(index), 0);
932         wr32(IGC_RAH(index), 0);
933
934         netdev_dbg(dev, "MAC address filter cleared in HW: index %d", index);
935 }
936
937 /* Set default MAC address for the PF in the first RAR entry */
938 static void igc_set_default_mac_filter(struct igc_adapter *adapter)
939 {
940         struct net_device *dev = adapter->netdev;
941         u8 *addr = adapter->hw.mac.addr;
942
943         netdev_dbg(dev, "Set default MAC address filter: address %pM", addr);
944
945         igc_set_mac_filter_hw(adapter, 0, IGC_MAC_FILTER_TYPE_DST, addr, -1);
946 }
947
948 /**
949  * igc_set_mac - Change the Ethernet Address of the NIC
950  * @netdev: network interface device structure
951  * @p: pointer to an address structure
952  *
953  * Returns 0 on success, negative on failure
954  */
955 static int igc_set_mac(struct net_device *netdev, void *p)
956 {
957         struct igc_adapter *adapter = netdev_priv(netdev);
958         struct igc_hw *hw = &adapter->hw;
959         struct sockaddr *addr = p;
960
961         if (!is_valid_ether_addr(addr->sa_data))
962                 return -EADDRNOTAVAIL;
963
964         eth_hw_addr_set(netdev, addr->sa_data);
965         memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len);
966
967         /* set the correct pool for the new PF MAC address in entry 0 */
968         igc_set_default_mac_filter(adapter);
969
970         return 0;
971 }
972
973 /**
974  *  igc_write_mc_addr_list - write multicast addresses to MTA
975  *  @netdev: network interface device structure
976  *
977  *  Writes multicast address list to the MTA hash table.
978  *  Returns: -ENOMEM on failure
979  *           0 on no addresses written
980  *           X on writing X addresses to MTA
981  **/
982 static int igc_write_mc_addr_list(struct net_device *netdev)
983 {
984         struct igc_adapter *adapter = netdev_priv(netdev);
985         struct igc_hw *hw = &adapter->hw;
986         struct netdev_hw_addr *ha;
987         u8  *mta_list;
988         int i;
989
990         if (netdev_mc_empty(netdev)) {
991                 /* nothing to program, so clear mc list */
992                 igc_update_mc_addr_list(hw, NULL, 0);
993                 return 0;
994         }
995
996         mta_list = kcalloc(netdev_mc_count(netdev), 6, GFP_ATOMIC);
997         if (!mta_list)
998                 return -ENOMEM;
999
1000         /* The shared function expects a packed array of only addresses. */
1001         i = 0;
1002         netdev_for_each_mc_addr(ha, netdev)
1003                 memcpy(mta_list + (i++ * ETH_ALEN), ha->addr, ETH_ALEN);
1004
1005         igc_update_mc_addr_list(hw, mta_list, i);
1006         kfree(mta_list);
1007
1008         return netdev_mc_count(netdev);
1009 }
1010
1011 static __le32 igc_tx_launchtime(struct igc_ring *ring, ktime_t txtime,
1012                                 bool *first_flag, bool *insert_empty)
1013 {
1014         struct igc_adapter *adapter = netdev_priv(ring->netdev);
1015         ktime_t cycle_time = adapter->cycle_time;
1016         ktime_t base_time = adapter->base_time;
1017         ktime_t now = ktime_get_clocktai();
1018         ktime_t baset_est, end_of_cycle;
1019         u32 launchtime;
1020         s64 n;
1021
1022         n = div64_s64(ktime_sub_ns(now, base_time), cycle_time);
1023
1024         baset_est = ktime_add_ns(base_time, cycle_time * (n));
1025         end_of_cycle = ktime_add_ns(baset_est, cycle_time);
1026
1027         if (ktime_compare(txtime, end_of_cycle) >= 0) {
1028                 if (baset_est != ring->last_ff_cycle) {
1029                         *first_flag = true;
1030                         ring->last_ff_cycle = baset_est;
1031
1032                         if (ktime_compare(txtime, ring->last_tx_cycle) > 0)
1033                                 *insert_empty = true;
1034                 }
1035         }
1036
1037         /* Introducing a window at end of cycle on which packets
1038          * potentially not honor launchtime. Window of 5us chosen
1039          * considering software update the tail pointer and packets
1040          * are dma'ed to packet buffer.
1041          */
1042         if ((ktime_sub_ns(end_of_cycle, now) < 5 * NSEC_PER_USEC))
1043                 netdev_warn(ring->netdev, "Packet with txtime=%llu may not be honoured\n",
1044                             txtime);
1045
1046         ring->last_tx_cycle = end_of_cycle;
1047
1048         launchtime = ktime_sub_ns(txtime, baset_est);
1049         if (launchtime > 0)
1050                 div_s64_rem(launchtime, cycle_time, &launchtime);
1051         else
1052                 launchtime = 0;
1053
1054         return cpu_to_le32(launchtime);
1055 }
1056
1057 static int igc_init_empty_frame(struct igc_ring *ring,
1058                                 struct igc_tx_buffer *buffer,
1059                                 struct sk_buff *skb)
1060 {
1061         unsigned int size;
1062         dma_addr_t dma;
1063
1064         size = skb_headlen(skb);
1065
1066         dma = dma_map_single(ring->dev, skb->data, size, DMA_TO_DEVICE);
1067         if (dma_mapping_error(ring->dev, dma)) {
1068                 netdev_err_once(ring->netdev, "Failed to map DMA for TX\n");
1069                 return -ENOMEM;
1070         }
1071
1072         buffer->skb = skb;
1073         buffer->protocol = 0;
1074         buffer->bytecount = skb->len;
1075         buffer->gso_segs = 1;
1076         buffer->time_stamp = jiffies;
1077         dma_unmap_len_set(buffer, len, skb->len);
1078         dma_unmap_addr_set(buffer, dma, dma);
1079
1080         return 0;
1081 }
1082
1083 static int igc_init_tx_empty_descriptor(struct igc_ring *ring,
1084                                         struct sk_buff *skb,
1085                                         struct igc_tx_buffer *first)
1086 {
1087         union igc_adv_tx_desc *desc;
1088         u32 cmd_type, olinfo_status;
1089         int err;
1090
1091         if (!igc_desc_unused(ring))
1092                 return -EBUSY;
1093
1094         err = igc_init_empty_frame(ring, first, skb);
1095         if (err)
1096                 return err;
1097
1098         cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT |
1099                    IGC_ADVTXD_DCMD_IFCS | IGC_TXD_DCMD |
1100                    first->bytecount;
1101         olinfo_status = first->bytecount << IGC_ADVTXD_PAYLEN_SHIFT;
1102
1103         desc = IGC_TX_DESC(ring, ring->next_to_use);
1104         desc->read.cmd_type_len = cpu_to_le32(cmd_type);
1105         desc->read.olinfo_status = cpu_to_le32(olinfo_status);
1106         desc->read.buffer_addr = cpu_to_le64(dma_unmap_addr(first, dma));
1107
1108         netdev_tx_sent_queue(txring_txq(ring), skb->len);
1109
1110         first->next_to_watch = desc;
1111
1112         ring->next_to_use++;
1113         if (ring->next_to_use == ring->count)
1114                 ring->next_to_use = 0;
1115
1116         return 0;
1117 }
1118
1119 #define IGC_EMPTY_FRAME_SIZE 60
1120
1121 static void igc_tx_ctxtdesc(struct igc_ring *tx_ring,
1122                             __le32 launch_time, bool first_flag,
1123                             u32 vlan_macip_lens, u32 type_tucmd,
1124                             u32 mss_l4len_idx)
1125 {
1126         struct igc_adv_tx_context_desc *context_desc;
1127         u16 i = tx_ring->next_to_use;
1128
1129         context_desc = IGC_TX_CTXTDESC(tx_ring, i);
1130
1131         i++;
1132         tx_ring->next_to_use = (i < tx_ring->count) ? i : 0;
1133
1134         /* set bits to identify this as an advanced context descriptor */
1135         type_tucmd |= IGC_TXD_CMD_DEXT | IGC_ADVTXD_DTYP_CTXT;
1136
1137         /* For i225, context index must be unique per ring. */
1138         if (test_bit(IGC_RING_FLAG_TX_CTX_IDX, &tx_ring->flags))
1139                 mss_l4len_idx |= tx_ring->reg_idx << 4;
1140
1141         if (first_flag)
1142                 mss_l4len_idx |= IGC_ADVTXD_TSN_CNTX_FIRST;
1143
1144         context_desc->vlan_macip_lens   = cpu_to_le32(vlan_macip_lens);
1145         context_desc->type_tucmd_mlhl   = cpu_to_le32(type_tucmd);
1146         context_desc->mss_l4len_idx     = cpu_to_le32(mss_l4len_idx);
1147         context_desc->launch_time       = launch_time;
1148 }
1149
1150 static void igc_tx_csum(struct igc_ring *tx_ring, struct igc_tx_buffer *first,
1151                         __le32 launch_time, bool first_flag)
1152 {
1153         struct sk_buff *skb = first->skb;
1154         u32 vlan_macip_lens = 0;
1155         u32 type_tucmd = 0;
1156
1157         if (skb->ip_summed != CHECKSUM_PARTIAL) {
1158 csum_failed:
1159                 if (!(first->tx_flags & IGC_TX_FLAGS_VLAN) &&
1160                     !tx_ring->launchtime_enable)
1161                         return;
1162                 goto no_csum;
1163         }
1164
1165         switch (skb->csum_offset) {
1166         case offsetof(struct tcphdr, check):
1167                 type_tucmd = IGC_ADVTXD_TUCMD_L4T_TCP;
1168                 fallthrough;
1169         case offsetof(struct udphdr, check):
1170                 break;
1171         case offsetof(struct sctphdr, checksum):
1172                 /* validate that this is actually an SCTP request */
1173                 if (skb_csum_is_sctp(skb)) {
1174                         type_tucmd = IGC_ADVTXD_TUCMD_L4T_SCTP;
1175                         break;
1176                 }
1177                 fallthrough;
1178         default:
1179                 skb_checksum_help(skb);
1180                 goto csum_failed;
1181         }
1182
1183         /* update TX checksum flag */
1184         first->tx_flags |= IGC_TX_FLAGS_CSUM;
1185         vlan_macip_lens = skb_checksum_start_offset(skb) -
1186                           skb_network_offset(skb);
1187 no_csum:
1188         vlan_macip_lens |= skb_network_offset(skb) << IGC_ADVTXD_MACLEN_SHIFT;
1189         vlan_macip_lens |= first->tx_flags & IGC_TX_FLAGS_VLAN_MASK;
1190
1191         igc_tx_ctxtdesc(tx_ring, launch_time, first_flag,
1192                         vlan_macip_lens, type_tucmd, 0);
1193 }
1194
1195 static int __igc_maybe_stop_tx(struct igc_ring *tx_ring, const u16 size)
1196 {
1197         struct net_device *netdev = tx_ring->netdev;
1198
1199         netif_stop_subqueue(netdev, tx_ring->queue_index);
1200
1201         /* memory barriier comment */
1202         smp_mb();
1203
1204         /* We need to check again in a case another CPU has just
1205          * made room available.
1206          */
1207         if (igc_desc_unused(tx_ring) < size)
1208                 return -EBUSY;
1209
1210         /* A reprieve! */
1211         netif_wake_subqueue(netdev, tx_ring->queue_index);
1212
1213         u64_stats_update_begin(&tx_ring->tx_syncp2);
1214         tx_ring->tx_stats.restart_queue2++;
1215         u64_stats_update_end(&tx_ring->tx_syncp2);
1216
1217         return 0;
1218 }
1219
1220 static inline int igc_maybe_stop_tx(struct igc_ring *tx_ring, const u16 size)
1221 {
1222         if (igc_desc_unused(tx_ring) >= size)
1223                 return 0;
1224         return __igc_maybe_stop_tx(tx_ring, size);
1225 }
1226
1227 #define IGC_SET_FLAG(_input, _flag, _result) \
1228         (((_flag) <= (_result)) ?                               \
1229          ((u32)((_input) & (_flag)) * ((_result) / (_flag))) :  \
1230          ((u32)((_input) & (_flag)) / ((_flag) / (_result))))
1231
1232 static u32 igc_tx_cmd_type(struct sk_buff *skb, u32 tx_flags)
1233 {
1234         /* set type for advanced descriptor with frame checksum insertion */
1235         u32 cmd_type = IGC_ADVTXD_DTYP_DATA |
1236                        IGC_ADVTXD_DCMD_DEXT |
1237                        IGC_ADVTXD_DCMD_IFCS;
1238
1239         /* set HW vlan bit if vlan is present */
1240         cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_VLAN,
1241                                  IGC_ADVTXD_DCMD_VLE);
1242
1243         /* set segmentation bits for TSO */
1244         cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSO,
1245                                  (IGC_ADVTXD_DCMD_TSE));
1246
1247         /* set timestamp bit if present */
1248         cmd_type |= IGC_SET_FLAG(tx_flags, IGC_TX_FLAGS_TSTAMP,
1249                                  (IGC_ADVTXD_MAC_TSTAMP));
1250
1251         /* insert frame checksum */
1252         cmd_type ^= IGC_SET_FLAG(skb->no_fcs, 1, IGC_ADVTXD_DCMD_IFCS);
1253
1254         return cmd_type;
1255 }
1256
1257 static void igc_tx_olinfo_status(struct igc_ring *tx_ring,
1258                                  union igc_adv_tx_desc *tx_desc,
1259                                  u32 tx_flags, unsigned int paylen)
1260 {
1261         u32 olinfo_status = paylen << IGC_ADVTXD_PAYLEN_SHIFT;
1262
1263         /* insert L4 checksum */
1264         olinfo_status |= (tx_flags & IGC_TX_FLAGS_CSUM) *
1265                           ((IGC_TXD_POPTS_TXSM << 8) /
1266                           IGC_TX_FLAGS_CSUM);
1267
1268         /* insert IPv4 checksum */
1269         olinfo_status |= (tx_flags & IGC_TX_FLAGS_IPV4) *
1270                           (((IGC_TXD_POPTS_IXSM << 8)) /
1271                           IGC_TX_FLAGS_IPV4);
1272
1273         tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status);
1274 }
1275
1276 static int igc_tx_map(struct igc_ring *tx_ring,
1277                       struct igc_tx_buffer *first,
1278                       const u8 hdr_len)
1279 {
1280         struct sk_buff *skb = first->skb;
1281         struct igc_tx_buffer *tx_buffer;
1282         union igc_adv_tx_desc *tx_desc;
1283         u32 tx_flags = first->tx_flags;
1284         skb_frag_t *frag;
1285         u16 i = tx_ring->next_to_use;
1286         unsigned int data_len, size;
1287         dma_addr_t dma;
1288         u32 cmd_type;
1289
1290         cmd_type = igc_tx_cmd_type(skb, tx_flags);
1291         tx_desc = IGC_TX_DESC(tx_ring, i);
1292
1293         igc_tx_olinfo_status(tx_ring, tx_desc, tx_flags, skb->len - hdr_len);
1294
1295         size = skb_headlen(skb);
1296         data_len = skb->data_len;
1297
1298         dma = dma_map_single(tx_ring->dev, skb->data, size, DMA_TO_DEVICE);
1299
1300         tx_buffer = first;
1301
1302         for (frag = &skb_shinfo(skb)->frags[0];; frag++) {
1303                 if (dma_mapping_error(tx_ring->dev, dma))
1304                         goto dma_error;
1305
1306                 /* record length, and DMA address */
1307                 dma_unmap_len_set(tx_buffer, len, size);
1308                 dma_unmap_addr_set(tx_buffer, dma, dma);
1309
1310                 tx_desc->read.buffer_addr = cpu_to_le64(dma);
1311
1312                 while (unlikely(size > IGC_MAX_DATA_PER_TXD)) {
1313                         tx_desc->read.cmd_type_len =
1314                                 cpu_to_le32(cmd_type ^ IGC_MAX_DATA_PER_TXD);
1315
1316                         i++;
1317                         tx_desc++;
1318                         if (i == tx_ring->count) {
1319                                 tx_desc = IGC_TX_DESC(tx_ring, 0);
1320                                 i = 0;
1321                         }
1322                         tx_desc->read.olinfo_status = 0;
1323
1324                         dma += IGC_MAX_DATA_PER_TXD;
1325                         size -= IGC_MAX_DATA_PER_TXD;
1326
1327                         tx_desc->read.buffer_addr = cpu_to_le64(dma);
1328                 }
1329
1330                 if (likely(!data_len))
1331                         break;
1332
1333                 tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type ^ size);
1334
1335                 i++;
1336                 tx_desc++;
1337                 if (i == tx_ring->count) {
1338                         tx_desc = IGC_TX_DESC(tx_ring, 0);
1339                         i = 0;
1340                 }
1341                 tx_desc->read.olinfo_status = 0;
1342
1343                 size = skb_frag_size(frag);
1344                 data_len -= size;
1345
1346                 dma = skb_frag_dma_map(tx_ring->dev, frag, 0,
1347                                        size, DMA_TO_DEVICE);
1348
1349                 tx_buffer = &tx_ring->tx_buffer_info[i];
1350         }
1351
1352         /* write last descriptor with RS and EOP bits */
1353         cmd_type |= size | IGC_TXD_DCMD;
1354         tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type);
1355
1356         netdev_tx_sent_queue(txring_txq(tx_ring), first->bytecount);
1357
1358         /* set the timestamp */
1359         first->time_stamp = jiffies;
1360
1361         skb_tx_timestamp(skb);
1362
1363         /* Force memory writes to complete before letting h/w know there
1364          * are new descriptors to fetch.  (Only applicable for weak-ordered
1365          * memory model archs, such as IA-64).
1366          *
1367          * We also need this memory barrier to make certain all of the
1368          * status bits have been updated before next_to_watch is written.
1369          */
1370         wmb();
1371
1372         /* set next_to_watch value indicating a packet is present */
1373         first->next_to_watch = tx_desc;
1374
1375         i++;
1376         if (i == tx_ring->count)
1377                 i = 0;
1378
1379         tx_ring->next_to_use = i;
1380
1381         /* Make sure there is space in the ring for the next send. */
1382         igc_maybe_stop_tx(tx_ring, DESC_NEEDED);
1383
1384         if (netif_xmit_stopped(txring_txq(tx_ring)) || !netdev_xmit_more()) {
1385                 writel(i, tx_ring->tail);
1386         }
1387
1388         return 0;
1389 dma_error:
1390         netdev_err(tx_ring->netdev, "TX DMA map failed\n");
1391         tx_buffer = &tx_ring->tx_buffer_info[i];
1392
1393         /* clear dma mappings for failed tx_buffer_info map */
1394         while (tx_buffer != first) {
1395                 if (dma_unmap_len(tx_buffer, len))
1396                         igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
1397
1398                 if (i-- == 0)
1399                         i += tx_ring->count;
1400                 tx_buffer = &tx_ring->tx_buffer_info[i];
1401         }
1402
1403         if (dma_unmap_len(tx_buffer, len))
1404                 igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
1405
1406         dev_kfree_skb_any(tx_buffer->skb);
1407         tx_buffer->skb = NULL;
1408
1409         tx_ring->next_to_use = i;
1410
1411         return -1;
1412 }
1413
1414 static int igc_tso(struct igc_ring *tx_ring,
1415                    struct igc_tx_buffer *first,
1416                    __le32 launch_time, bool first_flag,
1417                    u8 *hdr_len)
1418 {
1419         u32 vlan_macip_lens, type_tucmd, mss_l4len_idx;
1420         struct sk_buff *skb = first->skb;
1421         union {
1422                 struct iphdr *v4;
1423                 struct ipv6hdr *v6;
1424                 unsigned char *hdr;
1425         } ip;
1426         union {
1427                 struct tcphdr *tcp;
1428                 struct udphdr *udp;
1429                 unsigned char *hdr;
1430         } l4;
1431         u32 paylen, l4_offset;
1432         int err;
1433
1434         if (skb->ip_summed != CHECKSUM_PARTIAL)
1435                 return 0;
1436
1437         if (!skb_is_gso(skb))
1438                 return 0;
1439
1440         err = skb_cow_head(skb, 0);
1441         if (err < 0)
1442                 return err;
1443
1444         ip.hdr = skb_network_header(skb);
1445         l4.hdr = skb_checksum_start(skb);
1446
1447         /* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */
1448         type_tucmd = IGC_ADVTXD_TUCMD_L4T_TCP;
1449
1450         /* initialize outer IP header fields */
1451         if (ip.v4->version == 4) {
1452                 unsigned char *csum_start = skb_checksum_start(skb);
1453                 unsigned char *trans_start = ip.hdr + (ip.v4->ihl * 4);
1454
1455                 /* IP header will have to cancel out any data that
1456                  * is not a part of the outer IP header
1457                  */
1458                 ip.v4->check = csum_fold(csum_partial(trans_start,
1459                                                       csum_start - trans_start,
1460                                                       0));
1461                 type_tucmd |= IGC_ADVTXD_TUCMD_IPV4;
1462
1463                 ip.v4->tot_len = 0;
1464                 first->tx_flags |= IGC_TX_FLAGS_TSO |
1465                                    IGC_TX_FLAGS_CSUM |
1466                                    IGC_TX_FLAGS_IPV4;
1467         } else {
1468                 ip.v6->payload_len = 0;
1469                 first->tx_flags |= IGC_TX_FLAGS_TSO |
1470                                    IGC_TX_FLAGS_CSUM;
1471         }
1472
1473         /* determine offset of inner transport header */
1474         l4_offset = l4.hdr - skb->data;
1475
1476         /* remove payload length from inner checksum */
1477         paylen = skb->len - l4_offset;
1478         if (type_tucmd & IGC_ADVTXD_TUCMD_L4T_TCP) {
1479                 /* compute length of segmentation header */
1480                 *hdr_len = (l4.tcp->doff * 4) + l4_offset;
1481                 csum_replace_by_diff(&l4.tcp->check,
1482                                      (__force __wsum)htonl(paylen));
1483         } else {
1484                 /* compute length of segmentation header */
1485                 *hdr_len = sizeof(*l4.udp) + l4_offset;
1486                 csum_replace_by_diff(&l4.udp->check,
1487                                      (__force __wsum)htonl(paylen));
1488         }
1489
1490         /* update gso size and bytecount with header size */
1491         first->gso_segs = skb_shinfo(skb)->gso_segs;
1492         first->bytecount += (first->gso_segs - 1) * *hdr_len;
1493
1494         /* MSS L4LEN IDX */
1495         mss_l4len_idx = (*hdr_len - l4_offset) << IGC_ADVTXD_L4LEN_SHIFT;
1496         mss_l4len_idx |= skb_shinfo(skb)->gso_size << IGC_ADVTXD_MSS_SHIFT;
1497
1498         /* VLAN MACLEN IPLEN */
1499         vlan_macip_lens = l4.hdr - ip.hdr;
1500         vlan_macip_lens |= (ip.hdr - skb->data) << IGC_ADVTXD_MACLEN_SHIFT;
1501         vlan_macip_lens |= first->tx_flags & IGC_TX_FLAGS_VLAN_MASK;
1502
1503         igc_tx_ctxtdesc(tx_ring, launch_time, first_flag,
1504                         vlan_macip_lens, type_tucmd, mss_l4len_idx);
1505
1506         return 1;
1507 }
1508
1509 static netdev_tx_t igc_xmit_frame_ring(struct sk_buff *skb,
1510                                        struct igc_ring *tx_ring)
1511 {
1512         struct igc_adapter *adapter = netdev_priv(tx_ring->netdev);
1513         bool first_flag = false, insert_empty = false;
1514         u16 count = TXD_USE_COUNT(skb_headlen(skb));
1515         __be16 protocol = vlan_get_protocol(skb);
1516         struct igc_tx_buffer *first;
1517         __le32 launch_time = 0;
1518         u32 tx_flags = 0;
1519         unsigned short f;
1520         ktime_t txtime;
1521         u8 hdr_len = 0;
1522         int tso = 0;
1523
1524         /* need: 1 descriptor per page * PAGE_SIZE/IGC_MAX_DATA_PER_TXD,
1525          *      + 1 desc for skb_headlen/IGC_MAX_DATA_PER_TXD,
1526          *      + 2 desc gap to keep tail from touching head,
1527          *      + 1 desc for context descriptor,
1528          * otherwise try next time
1529          */
1530         for (f = 0; f < skb_shinfo(skb)->nr_frags; f++)
1531                 count += TXD_USE_COUNT(skb_frag_size(
1532                                                 &skb_shinfo(skb)->frags[f]));
1533
1534         if (igc_maybe_stop_tx(tx_ring, count + 5)) {
1535                 /* this is a hard error */
1536                 return NETDEV_TX_BUSY;
1537         }
1538
1539         if (!tx_ring->launchtime_enable)
1540                 goto done;
1541
1542         txtime = skb->tstamp;
1543         skb->tstamp = ktime_set(0, 0);
1544         launch_time = igc_tx_launchtime(tx_ring, txtime, &first_flag, &insert_empty);
1545
1546         if (insert_empty) {
1547                 struct igc_tx_buffer *empty_info;
1548                 struct sk_buff *empty;
1549                 void *data;
1550
1551                 empty_info = &tx_ring->tx_buffer_info[tx_ring->next_to_use];
1552                 empty = alloc_skb(IGC_EMPTY_FRAME_SIZE, GFP_ATOMIC);
1553                 if (!empty)
1554                         goto done;
1555
1556                 data = skb_put(empty, IGC_EMPTY_FRAME_SIZE);
1557                 memset(data, 0, IGC_EMPTY_FRAME_SIZE);
1558
1559                 igc_tx_ctxtdesc(tx_ring, 0, false, 0, 0, 0);
1560
1561                 if (igc_init_tx_empty_descriptor(tx_ring,
1562                                                  empty,
1563                                                  empty_info) < 0)
1564                         dev_kfree_skb_any(empty);
1565         }
1566
1567 done:
1568         /* record the location of the first descriptor for this packet */
1569         first = &tx_ring->tx_buffer_info[tx_ring->next_to_use];
1570         first->type = IGC_TX_BUFFER_TYPE_SKB;
1571         first->skb = skb;
1572         first->bytecount = skb->len;
1573         first->gso_segs = 1;
1574
1575         if (tx_ring->max_sdu > 0) {
1576                 u32 max_sdu = 0;
1577
1578                 max_sdu = tx_ring->max_sdu +
1579                           (skb_vlan_tagged(first->skb) ? VLAN_HLEN : 0);
1580
1581                 if (first->bytecount > max_sdu) {
1582                         adapter->stats.txdrop++;
1583                         goto out_drop;
1584                 }
1585         }
1586
1587         if (unlikely(test_bit(IGC_RING_FLAG_TX_HWTSTAMP, &tx_ring->flags) &&
1588                      skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP)) {
1589                 /* FIXME: add support for retrieving timestamps from
1590                  * the other timer registers before skipping the
1591                  * timestamping request.
1592                  */
1593                 unsigned long flags;
1594
1595                 spin_lock_irqsave(&adapter->ptp_tx_lock, flags);
1596                 if (!adapter->ptp_tx_skb) {
1597                         skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
1598                         tx_flags |= IGC_TX_FLAGS_TSTAMP;
1599
1600                         adapter->ptp_tx_skb = skb_get(skb);
1601                         adapter->ptp_tx_start = jiffies;
1602                 } else {
1603                         adapter->tx_hwtstamp_skipped++;
1604                 }
1605
1606                 spin_unlock_irqrestore(&adapter->ptp_tx_lock, flags);
1607         }
1608
1609         if (skb_vlan_tag_present(skb)) {
1610                 tx_flags |= IGC_TX_FLAGS_VLAN;
1611                 tx_flags |= (skb_vlan_tag_get(skb) << IGC_TX_FLAGS_VLAN_SHIFT);
1612         }
1613
1614         /* record initial flags and protocol */
1615         first->tx_flags = tx_flags;
1616         first->protocol = protocol;
1617
1618         tso = igc_tso(tx_ring, first, launch_time, first_flag, &hdr_len);
1619         if (tso < 0)
1620                 goto out_drop;
1621         else if (!tso)
1622                 igc_tx_csum(tx_ring, first, launch_time, first_flag);
1623
1624         igc_tx_map(tx_ring, first, hdr_len);
1625
1626         return NETDEV_TX_OK;
1627
1628 out_drop:
1629         dev_kfree_skb_any(first->skb);
1630         first->skb = NULL;
1631
1632         return NETDEV_TX_OK;
1633 }
1634
1635 static inline struct igc_ring *igc_tx_queue_mapping(struct igc_adapter *adapter,
1636                                                     struct sk_buff *skb)
1637 {
1638         unsigned int r_idx = skb->queue_mapping;
1639
1640         if (r_idx >= adapter->num_tx_queues)
1641                 r_idx = r_idx % adapter->num_tx_queues;
1642
1643         return adapter->tx_ring[r_idx];
1644 }
1645
1646 static netdev_tx_t igc_xmit_frame(struct sk_buff *skb,
1647                                   struct net_device *netdev)
1648 {
1649         struct igc_adapter *adapter = netdev_priv(netdev);
1650
1651         /* The minimum packet size with TCTL.PSP set is 17 so pad the skb
1652          * in order to meet this minimum size requirement.
1653          */
1654         if (skb->len < 17) {
1655                 if (skb_padto(skb, 17))
1656                         return NETDEV_TX_OK;
1657                 skb->len = 17;
1658         }
1659
1660         return igc_xmit_frame_ring(skb, igc_tx_queue_mapping(adapter, skb));
1661 }
1662
1663 static void igc_rx_checksum(struct igc_ring *ring,
1664                             union igc_adv_rx_desc *rx_desc,
1665                             struct sk_buff *skb)
1666 {
1667         skb_checksum_none_assert(skb);
1668
1669         /* Ignore Checksum bit is set */
1670         if (igc_test_staterr(rx_desc, IGC_RXD_STAT_IXSM))
1671                 return;
1672
1673         /* Rx checksum disabled via ethtool */
1674         if (!(ring->netdev->features & NETIF_F_RXCSUM))
1675                 return;
1676
1677         /* TCP/UDP checksum error bit is set */
1678         if (igc_test_staterr(rx_desc,
1679                              IGC_RXDEXT_STATERR_L4E |
1680                              IGC_RXDEXT_STATERR_IPE)) {
1681                 /* work around errata with sctp packets where the TCPE aka
1682                  * L4E bit is set incorrectly on 64 byte (60 byte w/o crc)
1683                  * packets (aka let the stack check the crc32c)
1684                  */
1685                 if (!(skb->len == 60 &&
1686                       test_bit(IGC_RING_FLAG_RX_SCTP_CSUM, &ring->flags))) {
1687                         u64_stats_update_begin(&ring->rx_syncp);
1688                         ring->rx_stats.csum_err++;
1689                         u64_stats_update_end(&ring->rx_syncp);
1690                 }
1691                 /* let the stack verify checksum errors */
1692                 return;
1693         }
1694         /* It must be a TCP or UDP packet with a valid checksum */
1695         if (igc_test_staterr(rx_desc, IGC_RXD_STAT_TCPCS |
1696                                       IGC_RXD_STAT_UDPCS))
1697                 skb->ip_summed = CHECKSUM_UNNECESSARY;
1698
1699         netdev_dbg(ring->netdev, "cksum success: bits %08X\n",
1700                    le32_to_cpu(rx_desc->wb.upper.status_error));
1701 }
1702
1703 /* Mapping HW RSS Type to enum pkt_hash_types */
1704 static const enum pkt_hash_types igc_rss_type_table[IGC_RSS_TYPE_MAX_TABLE] = {
1705         [IGC_RSS_TYPE_NO_HASH]          = PKT_HASH_TYPE_L2,
1706         [IGC_RSS_TYPE_HASH_TCP_IPV4]    = PKT_HASH_TYPE_L4,
1707         [IGC_RSS_TYPE_HASH_IPV4]        = PKT_HASH_TYPE_L3,
1708         [IGC_RSS_TYPE_HASH_TCP_IPV6]    = PKT_HASH_TYPE_L4,
1709         [IGC_RSS_TYPE_HASH_IPV6_EX]     = PKT_HASH_TYPE_L3,
1710         [IGC_RSS_TYPE_HASH_IPV6]        = PKT_HASH_TYPE_L3,
1711         [IGC_RSS_TYPE_HASH_TCP_IPV6_EX] = PKT_HASH_TYPE_L4,
1712         [IGC_RSS_TYPE_HASH_UDP_IPV4]    = PKT_HASH_TYPE_L4,
1713         [IGC_RSS_TYPE_HASH_UDP_IPV6]    = PKT_HASH_TYPE_L4,
1714         [IGC_RSS_TYPE_HASH_UDP_IPV6_EX] = PKT_HASH_TYPE_L4,
1715         [10] = PKT_HASH_TYPE_NONE, /* RSS Type above 9 "Reserved" by HW  */
1716         [11] = PKT_HASH_TYPE_NONE, /* keep array sized for SW bit-mask   */
1717         [12] = PKT_HASH_TYPE_NONE, /* to handle future HW revisons       */
1718         [13] = PKT_HASH_TYPE_NONE,
1719         [14] = PKT_HASH_TYPE_NONE,
1720         [15] = PKT_HASH_TYPE_NONE,
1721 };
1722
1723 static inline void igc_rx_hash(struct igc_ring *ring,
1724                                union igc_adv_rx_desc *rx_desc,
1725                                struct sk_buff *skb)
1726 {
1727         if (ring->netdev->features & NETIF_F_RXHASH) {
1728                 u32 rss_hash = le32_to_cpu(rx_desc->wb.lower.hi_dword.rss);
1729                 u32 rss_type = igc_rss_type(rx_desc);
1730
1731                 skb_set_hash(skb, rss_hash, igc_rss_type_table[rss_type]);
1732         }
1733 }
1734
1735 static void igc_rx_vlan(struct igc_ring *rx_ring,
1736                         union igc_adv_rx_desc *rx_desc,
1737                         struct sk_buff *skb)
1738 {
1739         struct net_device *dev = rx_ring->netdev;
1740         u16 vid;
1741
1742         if ((dev->features & NETIF_F_HW_VLAN_CTAG_RX) &&
1743             igc_test_staterr(rx_desc, IGC_RXD_STAT_VP)) {
1744                 if (igc_test_staterr(rx_desc, IGC_RXDEXT_STATERR_LB) &&
1745                     test_bit(IGC_RING_FLAG_RX_LB_VLAN_BSWAP, &rx_ring->flags))
1746                         vid = be16_to_cpu((__force __be16)rx_desc->wb.upper.vlan);
1747                 else
1748                         vid = le16_to_cpu(rx_desc->wb.upper.vlan);
1749
1750                 __vlan_hwaccel_put_tag(skb, htons(ETH_P_8021Q), vid);
1751         }
1752 }
1753
1754 /**
1755  * igc_process_skb_fields - Populate skb header fields from Rx descriptor
1756  * @rx_ring: rx descriptor ring packet is being transacted on
1757  * @rx_desc: pointer to the EOP Rx descriptor
1758  * @skb: pointer to current skb being populated
1759  *
1760  * This function checks the ring, descriptor, and packet information in order
1761  * to populate the hash, checksum, VLAN, protocol, and other fields within the
1762  * skb.
1763  */
1764 static void igc_process_skb_fields(struct igc_ring *rx_ring,
1765                                    union igc_adv_rx_desc *rx_desc,
1766                                    struct sk_buff *skb)
1767 {
1768         igc_rx_hash(rx_ring, rx_desc, skb);
1769
1770         igc_rx_checksum(rx_ring, rx_desc, skb);
1771
1772         igc_rx_vlan(rx_ring, rx_desc, skb);
1773
1774         skb_record_rx_queue(skb, rx_ring->queue_index);
1775
1776         skb->protocol = eth_type_trans(skb, rx_ring->netdev);
1777 }
1778
1779 static void igc_vlan_mode(struct net_device *netdev, netdev_features_t features)
1780 {
1781         bool enable = !!(features & NETIF_F_HW_VLAN_CTAG_RX);
1782         struct igc_adapter *adapter = netdev_priv(netdev);
1783         struct igc_hw *hw = &adapter->hw;
1784         u32 ctrl;
1785
1786         ctrl = rd32(IGC_CTRL);
1787
1788         if (enable) {
1789                 /* enable VLAN tag insert/strip */
1790                 ctrl |= IGC_CTRL_VME;
1791         } else {
1792                 /* disable VLAN tag insert/strip */
1793                 ctrl &= ~IGC_CTRL_VME;
1794         }
1795         wr32(IGC_CTRL, ctrl);
1796 }
1797
1798 static void igc_restore_vlan(struct igc_adapter *adapter)
1799 {
1800         igc_vlan_mode(adapter->netdev, adapter->netdev->features);
1801 }
1802
1803 static struct igc_rx_buffer *igc_get_rx_buffer(struct igc_ring *rx_ring,
1804                                                const unsigned int size,
1805                                                int *rx_buffer_pgcnt)
1806 {
1807         struct igc_rx_buffer *rx_buffer;
1808
1809         rx_buffer = &rx_ring->rx_buffer_info[rx_ring->next_to_clean];
1810         *rx_buffer_pgcnt =
1811 #if (PAGE_SIZE < 8192)
1812                 page_count(rx_buffer->page);
1813 #else
1814                 0;
1815 #endif
1816         prefetchw(rx_buffer->page);
1817
1818         /* we are reusing so sync this buffer for CPU use */
1819         dma_sync_single_range_for_cpu(rx_ring->dev,
1820                                       rx_buffer->dma,
1821                                       rx_buffer->page_offset,
1822                                       size,
1823                                       DMA_FROM_DEVICE);
1824
1825         rx_buffer->pagecnt_bias--;
1826
1827         return rx_buffer;
1828 }
1829
1830 static void igc_rx_buffer_flip(struct igc_rx_buffer *buffer,
1831                                unsigned int truesize)
1832 {
1833 #if (PAGE_SIZE < 8192)
1834         buffer->page_offset ^= truesize;
1835 #else
1836         buffer->page_offset += truesize;
1837 #endif
1838 }
1839
1840 static unsigned int igc_get_rx_frame_truesize(struct igc_ring *ring,
1841                                               unsigned int size)
1842 {
1843         unsigned int truesize;
1844
1845 #if (PAGE_SIZE < 8192)
1846         truesize = igc_rx_pg_size(ring) / 2;
1847 #else
1848         truesize = ring_uses_build_skb(ring) ?
1849                    SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) +
1850                    SKB_DATA_ALIGN(IGC_SKB_PAD + size) :
1851                    SKB_DATA_ALIGN(size);
1852 #endif
1853         return truesize;
1854 }
1855
1856 /**
1857  * igc_add_rx_frag - Add contents of Rx buffer to sk_buff
1858  * @rx_ring: rx descriptor ring to transact packets on
1859  * @rx_buffer: buffer containing page to add
1860  * @skb: sk_buff to place the data into
1861  * @size: size of buffer to be added
1862  *
1863  * This function will add the data contained in rx_buffer->page to the skb.
1864  */
1865 static void igc_add_rx_frag(struct igc_ring *rx_ring,
1866                             struct igc_rx_buffer *rx_buffer,
1867                             struct sk_buff *skb,
1868                             unsigned int size)
1869 {
1870         unsigned int truesize;
1871
1872 #if (PAGE_SIZE < 8192)
1873         truesize = igc_rx_pg_size(rx_ring) / 2;
1874 #else
1875         truesize = ring_uses_build_skb(rx_ring) ?
1876                    SKB_DATA_ALIGN(IGC_SKB_PAD + size) :
1877                    SKB_DATA_ALIGN(size);
1878 #endif
1879         skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, rx_buffer->page,
1880                         rx_buffer->page_offset, size, truesize);
1881
1882         igc_rx_buffer_flip(rx_buffer, truesize);
1883 }
1884
1885 static struct sk_buff *igc_build_skb(struct igc_ring *rx_ring,
1886                                      struct igc_rx_buffer *rx_buffer,
1887                                      struct xdp_buff *xdp)
1888 {
1889         unsigned int size = xdp->data_end - xdp->data;
1890         unsigned int truesize = igc_get_rx_frame_truesize(rx_ring, size);
1891         unsigned int metasize = xdp->data - xdp->data_meta;
1892         struct sk_buff *skb;
1893
1894         /* prefetch first cache line of first page */
1895         net_prefetch(xdp->data_meta);
1896
1897         /* build an skb around the page buffer */
1898         skb = napi_build_skb(xdp->data_hard_start, truesize);
1899         if (unlikely(!skb))
1900                 return NULL;
1901
1902         /* update pointers within the skb to store the data */
1903         skb_reserve(skb, xdp->data - xdp->data_hard_start);
1904         __skb_put(skb, size);
1905         if (metasize)
1906                 skb_metadata_set(skb, metasize);
1907
1908         igc_rx_buffer_flip(rx_buffer, truesize);
1909         return skb;
1910 }
1911
1912 static struct sk_buff *igc_construct_skb(struct igc_ring *rx_ring,
1913                                          struct igc_rx_buffer *rx_buffer,
1914                                          struct xdp_buff *xdp,
1915                                          ktime_t timestamp)
1916 {
1917         unsigned int metasize = xdp->data - xdp->data_meta;
1918         unsigned int size = xdp->data_end - xdp->data;
1919         unsigned int truesize = igc_get_rx_frame_truesize(rx_ring, size);
1920         void *va = xdp->data;
1921         unsigned int headlen;
1922         struct sk_buff *skb;
1923
1924         /* prefetch first cache line of first page */
1925         net_prefetch(xdp->data_meta);
1926
1927         /* allocate a skb to store the frags */
1928         skb = napi_alloc_skb(&rx_ring->q_vector->napi,
1929                              IGC_RX_HDR_LEN + metasize);
1930         if (unlikely(!skb))
1931                 return NULL;
1932
1933         if (timestamp)
1934                 skb_hwtstamps(skb)->hwtstamp = timestamp;
1935
1936         /* Determine available headroom for copy */
1937         headlen = size;
1938         if (headlen > IGC_RX_HDR_LEN)
1939                 headlen = eth_get_headlen(skb->dev, va, IGC_RX_HDR_LEN);
1940
1941         /* align pull length to size of long to optimize memcpy performance */
1942         memcpy(__skb_put(skb, headlen + metasize), xdp->data_meta,
1943                ALIGN(headlen + metasize, sizeof(long)));
1944
1945         if (metasize) {
1946                 skb_metadata_set(skb, metasize);
1947                 __skb_pull(skb, metasize);
1948         }
1949
1950         /* update all of the pointers */
1951         size -= headlen;
1952         if (size) {
1953                 skb_add_rx_frag(skb, 0, rx_buffer->page,
1954                                 (va + headlen) - page_address(rx_buffer->page),
1955                                 size, truesize);
1956                 igc_rx_buffer_flip(rx_buffer, truesize);
1957         } else {
1958                 rx_buffer->pagecnt_bias++;
1959         }
1960
1961         return skb;
1962 }
1963
1964 /**
1965  * igc_reuse_rx_page - page flip buffer and store it back on the ring
1966  * @rx_ring: rx descriptor ring to store buffers on
1967  * @old_buff: donor buffer to have page reused
1968  *
1969  * Synchronizes page for reuse by the adapter
1970  */
1971 static void igc_reuse_rx_page(struct igc_ring *rx_ring,
1972                               struct igc_rx_buffer *old_buff)
1973 {
1974         u16 nta = rx_ring->next_to_alloc;
1975         struct igc_rx_buffer *new_buff;
1976
1977         new_buff = &rx_ring->rx_buffer_info[nta];
1978
1979         /* update, and store next to alloc */
1980         nta++;
1981         rx_ring->next_to_alloc = (nta < rx_ring->count) ? nta : 0;
1982
1983         /* Transfer page from old buffer to new buffer.
1984          * Move each member individually to avoid possible store
1985          * forwarding stalls.
1986          */
1987         new_buff->dma           = old_buff->dma;
1988         new_buff->page          = old_buff->page;
1989         new_buff->page_offset   = old_buff->page_offset;
1990         new_buff->pagecnt_bias  = old_buff->pagecnt_bias;
1991 }
1992
1993 static bool igc_can_reuse_rx_page(struct igc_rx_buffer *rx_buffer,
1994                                   int rx_buffer_pgcnt)
1995 {
1996         unsigned int pagecnt_bias = rx_buffer->pagecnt_bias;
1997         struct page *page = rx_buffer->page;
1998
1999         /* avoid re-using remote and pfmemalloc pages */
2000         if (!dev_page_is_reusable(page))
2001                 return false;
2002
2003 #if (PAGE_SIZE < 8192)
2004         /* if we are only owner of page we can reuse it */
2005         if (unlikely((rx_buffer_pgcnt - pagecnt_bias) > 1))
2006                 return false;
2007 #else
2008 #define IGC_LAST_OFFSET \
2009         (SKB_WITH_OVERHEAD(PAGE_SIZE) - IGC_RXBUFFER_2048)
2010
2011         if (rx_buffer->page_offset > IGC_LAST_OFFSET)
2012                 return false;
2013 #endif
2014
2015         /* If we have drained the page fragment pool we need to update
2016          * the pagecnt_bias and page count so that we fully restock the
2017          * number of references the driver holds.
2018          */
2019         if (unlikely(pagecnt_bias == 1)) {
2020                 page_ref_add(page, USHRT_MAX - 1);
2021                 rx_buffer->pagecnt_bias = USHRT_MAX;
2022         }
2023
2024         return true;
2025 }
2026
2027 /**
2028  * igc_is_non_eop - process handling of non-EOP buffers
2029  * @rx_ring: Rx ring being processed
2030  * @rx_desc: Rx descriptor for current buffer
2031  *
2032  * This function updates next to clean.  If the buffer is an EOP buffer
2033  * this function exits returning false, otherwise it will place the
2034  * sk_buff in the next buffer to be chained and return true indicating
2035  * that this is in fact a non-EOP buffer.
2036  */
2037 static bool igc_is_non_eop(struct igc_ring *rx_ring,
2038                            union igc_adv_rx_desc *rx_desc)
2039 {
2040         u32 ntc = rx_ring->next_to_clean + 1;
2041
2042         /* fetch, update, and store next to clean */
2043         ntc = (ntc < rx_ring->count) ? ntc : 0;
2044         rx_ring->next_to_clean = ntc;
2045
2046         prefetch(IGC_RX_DESC(rx_ring, ntc));
2047
2048         if (likely(igc_test_staterr(rx_desc, IGC_RXD_STAT_EOP)))
2049                 return false;
2050
2051         return true;
2052 }
2053
2054 /**
2055  * igc_cleanup_headers - Correct corrupted or empty headers
2056  * @rx_ring: rx descriptor ring packet is being transacted on
2057  * @rx_desc: pointer to the EOP Rx descriptor
2058  * @skb: pointer to current skb being fixed
2059  *
2060  * Address the case where we are pulling data in on pages only
2061  * and as such no data is present in the skb header.
2062  *
2063  * In addition if skb is not at least 60 bytes we need to pad it so that
2064  * it is large enough to qualify as a valid Ethernet frame.
2065  *
2066  * Returns true if an error was encountered and skb was freed.
2067  */
2068 static bool igc_cleanup_headers(struct igc_ring *rx_ring,
2069                                 union igc_adv_rx_desc *rx_desc,
2070                                 struct sk_buff *skb)
2071 {
2072         /* XDP packets use error pointer so abort at this point */
2073         if (IS_ERR(skb))
2074                 return true;
2075
2076         if (unlikely(igc_test_staterr(rx_desc, IGC_RXDEXT_STATERR_RXE))) {
2077                 struct net_device *netdev = rx_ring->netdev;
2078
2079                 if (!(netdev->features & NETIF_F_RXALL)) {
2080                         dev_kfree_skb_any(skb);
2081                         return true;
2082                 }
2083         }
2084
2085         /* if eth_skb_pad returns an error the skb was freed */
2086         if (eth_skb_pad(skb))
2087                 return true;
2088
2089         return false;
2090 }
2091
2092 static void igc_put_rx_buffer(struct igc_ring *rx_ring,
2093                               struct igc_rx_buffer *rx_buffer,
2094                               int rx_buffer_pgcnt)
2095 {
2096         if (igc_can_reuse_rx_page(rx_buffer, rx_buffer_pgcnt)) {
2097                 /* hand second half of page back to the ring */
2098                 igc_reuse_rx_page(rx_ring, rx_buffer);
2099         } else {
2100                 /* We are not reusing the buffer so unmap it and free
2101                  * any references we are holding to it
2102                  */
2103                 dma_unmap_page_attrs(rx_ring->dev, rx_buffer->dma,
2104                                      igc_rx_pg_size(rx_ring), DMA_FROM_DEVICE,
2105                                      IGC_RX_DMA_ATTR);
2106                 __page_frag_cache_drain(rx_buffer->page,
2107                                         rx_buffer->pagecnt_bias);
2108         }
2109
2110         /* clear contents of rx_buffer */
2111         rx_buffer->page = NULL;
2112 }
2113
2114 static inline unsigned int igc_rx_offset(struct igc_ring *rx_ring)
2115 {
2116         struct igc_adapter *adapter = rx_ring->q_vector->adapter;
2117
2118         if (ring_uses_build_skb(rx_ring))
2119                 return IGC_SKB_PAD;
2120         if (igc_xdp_is_enabled(adapter))
2121                 return XDP_PACKET_HEADROOM;
2122
2123         return 0;
2124 }
2125
2126 static bool igc_alloc_mapped_page(struct igc_ring *rx_ring,
2127                                   struct igc_rx_buffer *bi)
2128 {
2129         struct page *page = bi->page;
2130         dma_addr_t dma;
2131
2132         /* since we are recycling buffers we should seldom need to alloc */
2133         if (likely(page))
2134                 return true;
2135
2136         /* alloc new page for storage */
2137         page = dev_alloc_pages(igc_rx_pg_order(rx_ring));
2138         if (unlikely(!page)) {
2139                 rx_ring->rx_stats.alloc_failed++;
2140                 return false;
2141         }
2142
2143         /* map page for use */
2144         dma = dma_map_page_attrs(rx_ring->dev, page, 0,
2145                                  igc_rx_pg_size(rx_ring),
2146                                  DMA_FROM_DEVICE,
2147                                  IGC_RX_DMA_ATTR);
2148
2149         /* if mapping failed free memory back to system since
2150          * there isn't much point in holding memory we can't use
2151          */
2152         if (dma_mapping_error(rx_ring->dev, dma)) {
2153                 __free_page(page);
2154
2155                 rx_ring->rx_stats.alloc_failed++;
2156                 return false;
2157         }
2158
2159         bi->dma = dma;
2160         bi->page = page;
2161         bi->page_offset = igc_rx_offset(rx_ring);
2162         page_ref_add(page, USHRT_MAX - 1);
2163         bi->pagecnt_bias = USHRT_MAX;
2164
2165         return true;
2166 }
2167
2168 /**
2169  * igc_alloc_rx_buffers - Replace used receive buffers; packet split
2170  * @rx_ring: rx descriptor ring
2171  * @cleaned_count: number of buffers to clean
2172  */
2173 static void igc_alloc_rx_buffers(struct igc_ring *rx_ring, u16 cleaned_count)
2174 {
2175         union igc_adv_rx_desc *rx_desc;
2176         u16 i = rx_ring->next_to_use;
2177         struct igc_rx_buffer *bi;
2178         u16 bufsz;
2179
2180         /* nothing to do */
2181         if (!cleaned_count)
2182                 return;
2183
2184         rx_desc = IGC_RX_DESC(rx_ring, i);
2185         bi = &rx_ring->rx_buffer_info[i];
2186         i -= rx_ring->count;
2187
2188         bufsz = igc_rx_bufsz(rx_ring);
2189
2190         do {
2191                 if (!igc_alloc_mapped_page(rx_ring, bi))
2192                         break;
2193
2194                 /* sync the buffer for use by the device */
2195                 dma_sync_single_range_for_device(rx_ring->dev, bi->dma,
2196                                                  bi->page_offset, bufsz,
2197                                                  DMA_FROM_DEVICE);
2198
2199                 /* Refresh the desc even if buffer_addrs didn't change
2200                  * because each write-back erases this info.
2201                  */
2202                 rx_desc->read.pkt_addr = cpu_to_le64(bi->dma + bi->page_offset);
2203
2204                 rx_desc++;
2205                 bi++;
2206                 i++;
2207                 if (unlikely(!i)) {
2208                         rx_desc = IGC_RX_DESC(rx_ring, 0);
2209                         bi = rx_ring->rx_buffer_info;
2210                         i -= rx_ring->count;
2211                 }
2212
2213                 /* clear the length for the next_to_use descriptor */
2214                 rx_desc->wb.upper.length = 0;
2215
2216                 cleaned_count--;
2217         } while (cleaned_count);
2218
2219         i += rx_ring->count;
2220
2221         if (rx_ring->next_to_use != i) {
2222                 /* record the next descriptor to use */
2223                 rx_ring->next_to_use = i;
2224
2225                 /* update next to alloc since we have filled the ring */
2226                 rx_ring->next_to_alloc = i;
2227
2228                 /* Force memory writes to complete before letting h/w
2229                  * know there are new descriptors to fetch.  (Only
2230                  * applicable for weak-ordered memory model archs,
2231                  * such as IA-64).
2232                  */
2233                 wmb();
2234                 writel(i, rx_ring->tail);
2235         }
2236 }
2237
2238 static bool igc_alloc_rx_buffers_zc(struct igc_ring *ring, u16 count)
2239 {
2240         union igc_adv_rx_desc *desc;
2241         u16 i = ring->next_to_use;
2242         struct igc_rx_buffer *bi;
2243         dma_addr_t dma;
2244         bool ok = true;
2245
2246         if (!count)
2247                 return ok;
2248
2249         XSK_CHECK_PRIV_TYPE(struct igc_xdp_buff);
2250
2251         desc = IGC_RX_DESC(ring, i);
2252         bi = &ring->rx_buffer_info[i];
2253         i -= ring->count;
2254
2255         do {
2256                 bi->xdp = xsk_buff_alloc(ring->xsk_pool);
2257                 if (!bi->xdp) {
2258                         ok = false;
2259                         break;
2260                 }
2261
2262                 dma = xsk_buff_xdp_get_dma(bi->xdp);
2263                 desc->read.pkt_addr = cpu_to_le64(dma);
2264
2265                 desc++;
2266                 bi++;
2267                 i++;
2268                 if (unlikely(!i)) {
2269                         desc = IGC_RX_DESC(ring, 0);
2270                         bi = ring->rx_buffer_info;
2271                         i -= ring->count;
2272                 }
2273
2274                 /* Clear the length for the next_to_use descriptor. */
2275                 desc->wb.upper.length = 0;
2276
2277                 count--;
2278         } while (count);
2279
2280         i += ring->count;
2281
2282         if (ring->next_to_use != i) {
2283                 ring->next_to_use = i;
2284
2285                 /* Force memory writes to complete before letting h/w
2286                  * know there are new descriptors to fetch.  (Only
2287                  * applicable for weak-ordered memory model archs,
2288                  * such as IA-64).
2289                  */
2290                 wmb();
2291                 writel(i, ring->tail);
2292         }
2293
2294         return ok;
2295 }
2296
2297 /* This function requires __netif_tx_lock is held by the caller. */
2298 static int igc_xdp_init_tx_descriptor(struct igc_ring *ring,
2299                                       struct xdp_frame *xdpf)
2300 {
2301         struct skb_shared_info *sinfo = xdp_get_shared_info_from_frame(xdpf);
2302         u8 nr_frags = unlikely(xdp_frame_has_frags(xdpf)) ? sinfo->nr_frags : 0;
2303         u16 count, index = ring->next_to_use;
2304         struct igc_tx_buffer *head = &ring->tx_buffer_info[index];
2305         struct igc_tx_buffer *buffer = head;
2306         union igc_adv_tx_desc *desc = IGC_TX_DESC(ring, index);
2307         u32 olinfo_status, len = xdpf->len, cmd_type;
2308         void *data = xdpf->data;
2309         u16 i;
2310
2311         count = TXD_USE_COUNT(len);
2312         for (i = 0; i < nr_frags; i++)
2313                 count += TXD_USE_COUNT(skb_frag_size(&sinfo->frags[i]));
2314
2315         if (igc_maybe_stop_tx(ring, count + 3)) {
2316                 /* this is a hard error */
2317                 return -EBUSY;
2318         }
2319
2320         i = 0;
2321         head->bytecount = xdp_get_frame_len(xdpf);
2322         head->type = IGC_TX_BUFFER_TYPE_XDP;
2323         head->gso_segs = 1;
2324         head->xdpf = xdpf;
2325
2326         olinfo_status = head->bytecount << IGC_ADVTXD_PAYLEN_SHIFT;
2327         desc->read.olinfo_status = cpu_to_le32(olinfo_status);
2328
2329         for (;;) {
2330                 dma_addr_t dma;
2331
2332                 dma = dma_map_single(ring->dev, data, len, DMA_TO_DEVICE);
2333                 if (dma_mapping_error(ring->dev, dma)) {
2334                         netdev_err_once(ring->netdev,
2335                                         "Failed to map DMA for TX\n");
2336                         goto unmap;
2337                 }
2338
2339                 dma_unmap_len_set(buffer, len, len);
2340                 dma_unmap_addr_set(buffer, dma, dma);
2341
2342                 cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT |
2343                            IGC_ADVTXD_DCMD_IFCS | len;
2344
2345                 desc->read.cmd_type_len = cpu_to_le32(cmd_type);
2346                 desc->read.buffer_addr = cpu_to_le64(dma);
2347
2348                 buffer->protocol = 0;
2349
2350                 if (++index == ring->count)
2351                         index = 0;
2352
2353                 if (i == nr_frags)
2354                         break;
2355
2356                 buffer = &ring->tx_buffer_info[index];
2357                 desc = IGC_TX_DESC(ring, index);
2358                 desc->read.olinfo_status = 0;
2359
2360                 data = skb_frag_address(&sinfo->frags[i]);
2361                 len = skb_frag_size(&sinfo->frags[i]);
2362                 i++;
2363         }
2364         desc->read.cmd_type_len |= cpu_to_le32(IGC_TXD_DCMD);
2365
2366         netdev_tx_sent_queue(txring_txq(ring), head->bytecount);
2367         /* set the timestamp */
2368         head->time_stamp = jiffies;
2369         /* set next_to_watch value indicating a packet is present */
2370         head->next_to_watch = desc;
2371         ring->next_to_use = index;
2372
2373         return 0;
2374
2375 unmap:
2376         for (;;) {
2377                 buffer = &ring->tx_buffer_info[index];
2378                 if (dma_unmap_len(buffer, len))
2379                         dma_unmap_page(ring->dev,
2380                                        dma_unmap_addr(buffer, dma),
2381                                        dma_unmap_len(buffer, len),
2382                                        DMA_TO_DEVICE);
2383                 dma_unmap_len_set(buffer, len, 0);
2384                 if (buffer == head)
2385                         break;
2386
2387                 if (!index)
2388                         index += ring->count;
2389                 index--;
2390         }
2391
2392         return -ENOMEM;
2393 }
2394
2395 static struct igc_ring *igc_xdp_get_tx_ring(struct igc_adapter *adapter,
2396                                             int cpu)
2397 {
2398         int index = cpu;
2399
2400         if (unlikely(index < 0))
2401                 index = 0;
2402
2403         while (index >= adapter->num_tx_queues)
2404                 index -= adapter->num_tx_queues;
2405
2406         return adapter->tx_ring[index];
2407 }
2408
2409 static int igc_xdp_xmit_back(struct igc_adapter *adapter, struct xdp_buff *xdp)
2410 {
2411         struct xdp_frame *xdpf = xdp_convert_buff_to_frame(xdp);
2412         int cpu = smp_processor_id();
2413         struct netdev_queue *nq;
2414         struct igc_ring *ring;
2415         int res;
2416
2417         if (unlikely(!xdpf))
2418                 return -EFAULT;
2419
2420         ring = igc_xdp_get_tx_ring(adapter, cpu);
2421         nq = txring_txq(ring);
2422
2423         __netif_tx_lock(nq, cpu);
2424         /* Avoid transmit queue timeout since we share it with the slow path */
2425         txq_trans_cond_update(nq);
2426         res = igc_xdp_init_tx_descriptor(ring, xdpf);
2427         __netif_tx_unlock(nq);
2428         return res;
2429 }
2430
2431 /* This function assumes rcu_read_lock() is held by the caller. */
2432 static int __igc_xdp_run_prog(struct igc_adapter *adapter,
2433                               struct bpf_prog *prog,
2434                               struct xdp_buff *xdp)
2435 {
2436         u32 act = bpf_prog_run_xdp(prog, xdp);
2437
2438         switch (act) {
2439         case XDP_PASS:
2440                 return IGC_XDP_PASS;
2441         case XDP_TX:
2442                 if (igc_xdp_xmit_back(adapter, xdp) < 0)
2443                         goto out_failure;
2444                 return IGC_XDP_TX;
2445         case XDP_REDIRECT:
2446                 if (xdp_do_redirect(adapter->netdev, xdp, prog) < 0)
2447                         goto out_failure;
2448                 return IGC_XDP_REDIRECT;
2449                 break;
2450         default:
2451                 bpf_warn_invalid_xdp_action(adapter->netdev, prog, act);
2452                 fallthrough;
2453         case XDP_ABORTED:
2454 out_failure:
2455                 trace_xdp_exception(adapter->netdev, prog, act);
2456                 fallthrough;
2457         case XDP_DROP:
2458                 return IGC_XDP_CONSUMED;
2459         }
2460 }
2461
2462 static struct sk_buff *igc_xdp_run_prog(struct igc_adapter *adapter,
2463                                         struct xdp_buff *xdp)
2464 {
2465         struct bpf_prog *prog;
2466         int res;
2467
2468         prog = READ_ONCE(adapter->xdp_prog);
2469         if (!prog) {
2470                 res = IGC_XDP_PASS;
2471                 goto out;
2472         }
2473
2474         res = __igc_xdp_run_prog(adapter, prog, xdp);
2475
2476 out:
2477         return ERR_PTR(-res);
2478 }
2479
2480 /* This function assumes __netif_tx_lock is held by the caller. */
2481 static void igc_flush_tx_descriptors(struct igc_ring *ring)
2482 {
2483         /* Once tail pointer is updated, hardware can fetch the descriptors
2484          * any time so we issue a write membar here to ensure all memory
2485          * writes are complete before the tail pointer is updated.
2486          */
2487         wmb();
2488         writel(ring->next_to_use, ring->tail);
2489 }
2490
2491 static void igc_finalize_xdp(struct igc_adapter *adapter, int status)
2492 {
2493         int cpu = smp_processor_id();
2494         struct netdev_queue *nq;
2495         struct igc_ring *ring;
2496
2497         if (status & IGC_XDP_TX) {
2498                 ring = igc_xdp_get_tx_ring(adapter, cpu);
2499                 nq = txring_txq(ring);
2500
2501                 __netif_tx_lock(nq, cpu);
2502                 igc_flush_tx_descriptors(ring);
2503                 __netif_tx_unlock(nq);
2504         }
2505
2506         if (status & IGC_XDP_REDIRECT)
2507                 xdp_do_flush();
2508 }
2509
2510 static void igc_update_rx_stats(struct igc_q_vector *q_vector,
2511                                 unsigned int packets, unsigned int bytes)
2512 {
2513         struct igc_ring *ring = q_vector->rx.ring;
2514
2515         u64_stats_update_begin(&ring->rx_syncp);
2516         ring->rx_stats.packets += packets;
2517         ring->rx_stats.bytes += bytes;
2518         u64_stats_update_end(&ring->rx_syncp);
2519
2520         q_vector->rx.total_packets += packets;
2521         q_vector->rx.total_bytes += bytes;
2522 }
2523
2524 static int igc_clean_rx_irq(struct igc_q_vector *q_vector, const int budget)
2525 {
2526         unsigned int total_bytes = 0, total_packets = 0;
2527         struct igc_adapter *adapter = q_vector->adapter;
2528         struct igc_ring *rx_ring = q_vector->rx.ring;
2529         struct sk_buff *skb = rx_ring->skb;
2530         u16 cleaned_count = igc_desc_unused(rx_ring);
2531         int xdp_status = 0, rx_buffer_pgcnt;
2532
2533         while (likely(total_packets < budget)) {
2534                 union igc_adv_rx_desc *rx_desc;
2535                 struct igc_rx_buffer *rx_buffer;
2536                 unsigned int size, truesize;
2537                 struct igc_xdp_buff ctx;
2538                 ktime_t timestamp = 0;
2539                 int pkt_offset = 0;
2540                 void *pktbuf;
2541
2542                 /* return some buffers to hardware, one at a time is too slow */
2543                 if (cleaned_count >= IGC_RX_BUFFER_WRITE) {
2544                         igc_alloc_rx_buffers(rx_ring, cleaned_count);
2545                         cleaned_count = 0;
2546                 }
2547
2548                 rx_desc = IGC_RX_DESC(rx_ring, rx_ring->next_to_clean);
2549                 size = le16_to_cpu(rx_desc->wb.upper.length);
2550                 if (!size)
2551                         break;
2552
2553                 /* This memory barrier is needed to keep us from reading
2554                  * any other fields out of the rx_desc until we know the
2555                  * descriptor has been written back
2556                  */
2557                 dma_rmb();
2558
2559                 rx_buffer = igc_get_rx_buffer(rx_ring, size, &rx_buffer_pgcnt);
2560                 truesize = igc_get_rx_frame_truesize(rx_ring, size);
2561
2562                 pktbuf = page_address(rx_buffer->page) + rx_buffer->page_offset;
2563
2564                 if (igc_test_staterr(rx_desc, IGC_RXDADV_STAT_TSIP)) {
2565                         timestamp = igc_ptp_rx_pktstamp(q_vector->adapter,
2566                                                         pktbuf);
2567                         ctx.rx_ts = timestamp;
2568                         pkt_offset = IGC_TS_HDR_LEN;
2569                         size -= IGC_TS_HDR_LEN;
2570                 }
2571
2572                 if (!skb) {
2573                         xdp_init_buff(&ctx.xdp, truesize, &rx_ring->xdp_rxq);
2574                         xdp_prepare_buff(&ctx.xdp, pktbuf - igc_rx_offset(rx_ring),
2575                                          igc_rx_offset(rx_ring) + pkt_offset,
2576                                          size, true);
2577                         xdp_buff_clear_frags_flag(&ctx.xdp);
2578                         ctx.rx_desc = rx_desc;
2579
2580                         skb = igc_xdp_run_prog(adapter, &ctx.xdp);
2581                 }
2582
2583                 if (IS_ERR(skb)) {
2584                         unsigned int xdp_res = -PTR_ERR(skb);
2585
2586                         switch (xdp_res) {
2587                         case IGC_XDP_CONSUMED:
2588                                 rx_buffer->pagecnt_bias++;
2589                                 break;
2590                         case IGC_XDP_TX:
2591                         case IGC_XDP_REDIRECT:
2592                                 igc_rx_buffer_flip(rx_buffer, truesize);
2593                                 xdp_status |= xdp_res;
2594                                 break;
2595                         }
2596
2597                         total_packets++;
2598                         total_bytes += size;
2599                 } else if (skb)
2600                         igc_add_rx_frag(rx_ring, rx_buffer, skb, size);
2601                 else if (ring_uses_build_skb(rx_ring))
2602                         skb = igc_build_skb(rx_ring, rx_buffer, &ctx.xdp);
2603                 else
2604                         skb = igc_construct_skb(rx_ring, rx_buffer, &ctx.xdp,
2605                                                 timestamp);
2606
2607                 /* exit if we failed to retrieve a buffer */
2608                 if (!skb) {
2609                         rx_ring->rx_stats.alloc_failed++;
2610                         rx_buffer->pagecnt_bias++;
2611                         break;
2612                 }
2613
2614                 igc_put_rx_buffer(rx_ring, rx_buffer, rx_buffer_pgcnt);
2615                 cleaned_count++;
2616
2617                 /* fetch next buffer in frame if non-eop */
2618                 if (igc_is_non_eop(rx_ring, rx_desc))
2619                         continue;
2620
2621                 /* verify the packet layout is correct */
2622                 if (igc_cleanup_headers(rx_ring, rx_desc, skb)) {
2623                         skb = NULL;
2624                         continue;
2625                 }
2626
2627                 /* probably a little skewed due to removing CRC */
2628                 total_bytes += skb->len;
2629
2630                 /* populate checksum, VLAN, and protocol */
2631                 igc_process_skb_fields(rx_ring, rx_desc, skb);
2632
2633                 napi_gro_receive(&q_vector->napi, skb);
2634
2635                 /* reset skb pointer */
2636                 skb = NULL;
2637
2638                 /* update budget accounting */
2639                 total_packets++;
2640         }
2641
2642         if (xdp_status)
2643                 igc_finalize_xdp(adapter, xdp_status);
2644
2645         /* place incomplete frames back on ring for completion */
2646         rx_ring->skb = skb;
2647
2648         igc_update_rx_stats(q_vector, total_packets, total_bytes);
2649
2650         if (cleaned_count)
2651                 igc_alloc_rx_buffers(rx_ring, cleaned_count);
2652
2653         return total_packets;
2654 }
2655
2656 static struct sk_buff *igc_construct_skb_zc(struct igc_ring *ring,
2657                                             struct xdp_buff *xdp)
2658 {
2659         unsigned int totalsize = xdp->data_end - xdp->data_meta;
2660         unsigned int metasize = xdp->data - xdp->data_meta;
2661         struct sk_buff *skb;
2662
2663         net_prefetch(xdp->data_meta);
2664
2665         skb = __napi_alloc_skb(&ring->q_vector->napi, totalsize,
2666                                GFP_ATOMIC | __GFP_NOWARN);
2667         if (unlikely(!skb))
2668                 return NULL;
2669
2670         memcpy(__skb_put(skb, totalsize), xdp->data_meta,
2671                ALIGN(totalsize, sizeof(long)));
2672
2673         if (metasize) {
2674                 skb_metadata_set(skb, metasize);
2675                 __skb_pull(skb, metasize);
2676         }
2677
2678         return skb;
2679 }
2680
2681 static void igc_dispatch_skb_zc(struct igc_q_vector *q_vector,
2682                                 union igc_adv_rx_desc *desc,
2683                                 struct xdp_buff *xdp,
2684                                 ktime_t timestamp)
2685 {
2686         struct igc_ring *ring = q_vector->rx.ring;
2687         struct sk_buff *skb;
2688
2689         skb = igc_construct_skb_zc(ring, xdp);
2690         if (!skb) {
2691                 ring->rx_stats.alloc_failed++;
2692                 return;
2693         }
2694
2695         if (timestamp)
2696                 skb_hwtstamps(skb)->hwtstamp = timestamp;
2697
2698         if (igc_cleanup_headers(ring, desc, skb))
2699                 return;
2700
2701         igc_process_skb_fields(ring, desc, skb);
2702         napi_gro_receive(&q_vector->napi, skb);
2703 }
2704
2705 static struct igc_xdp_buff *xsk_buff_to_igc_ctx(struct xdp_buff *xdp)
2706 {
2707         /* xdp_buff pointer used by ZC code path is alloc as xdp_buff_xsk. The
2708          * igc_xdp_buff shares its layout with xdp_buff_xsk and private
2709          * igc_xdp_buff fields fall into xdp_buff_xsk->cb
2710          */
2711        return (struct igc_xdp_buff *)xdp;
2712 }
2713
2714 static int igc_clean_rx_irq_zc(struct igc_q_vector *q_vector, const int budget)
2715 {
2716         struct igc_adapter *adapter = q_vector->adapter;
2717         struct igc_ring *ring = q_vector->rx.ring;
2718         u16 cleaned_count = igc_desc_unused(ring);
2719         int total_bytes = 0, total_packets = 0;
2720         u16 ntc = ring->next_to_clean;
2721         struct bpf_prog *prog;
2722         bool failure = false;
2723         int xdp_status = 0;
2724
2725         rcu_read_lock();
2726
2727         prog = READ_ONCE(adapter->xdp_prog);
2728
2729         while (likely(total_packets < budget)) {
2730                 union igc_adv_rx_desc *desc;
2731                 struct igc_rx_buffer *bi;
2732                 struct igc_xdp_buff *ctx;
2733                 ktime_t timestamp = 0;
2734                 unsigned int size;
2735                 int res;
2736
2737                 desc = IGC_RX_DESC(ring, ntc);
2738                 size = le16_to_cpu(desc->wb.upper.length);
2739                 if (!size)
2740                         break;
2741
2742                 /* This memory barrier is needed to keep us from reading
2743                  * any other fields out of the rx_desc until we know the
2744                  * descriptor has been written back
2745                  */
2746                 dma_rmb();
2747
2748                 bi = &ring->rx_buffer_info[ntc];
2749
2750                 ctx = xsk_buff_to_igc_ctx(bi->xdp);
2751                 ctx->rx_desc = desc;
2752
2753                 if (igc_test_staterr(desc, IGC_RXDADV_STAT_TSIP)) {
2754                         timestamp = igc_ptp_rx_pktstamp(q_vector->adapter,
2755                                                         bi->xdp->data);
2756                         ctx->rx_ts = timestamp;
2757
2758                         bi->xdp->data += IGC_TS_HDR_LEN;
2759
2760                         /* HW timestamp has been copied into local variable. Metadata
2761                          * length when XDP program is called should be 0.
2762                          */
2763                         bi->xdp->data_meta += IGC_TS_HDR_LEN;
2764                         size -= IGC_TS_HDR_LEN;
2765                 }
2766
2767                 bi->xdp->data_end = bi->xdp->data + size;
2768                 xsk_buff_dma_sync_for_cpu(bi->xdp, ring->xsk_pool);
2769
2770                 res = __igc_xdp_run_prog(adapter, prog, bi->xdp);
2771                 switch (res) {
2772                 case IGC_XDP_PASS:
2773                         igc_dispatch_skb_zc(q_vector, desc, bi->xdp, timestamp);
2774                         fallthrough;
2775                 case IGC_XDP_CONSUMED:
2776                         xsk_buff_free(bi->xdp);
2777                         break;
2778                 case IGC_XDP_TX:
2779                 case IGC_XDP_REDIRECT:
2780                         xdp_status |= res;
2781                         break;
2782                 }
2783
2784                 bi->xdp = NULL;
2785                 total_bytes += size;
2786                 total_packets++;
2787                 cleaned_count++;
2788                 ntc++;
2789                 if (ntc == ring->count)
2790                         ntc = 0;
2791         }
2792
2793         ring->next_to_clean = ntc;
2794         rcu_read_unlock();
2795
2796         if (cleaned_count >= IGC_RX_BUFFER_WRITE)
2797                 failure = !igc_alloc_rx_buffers_zc(ring, cleaned_count);
2798
2799         if (xdp_status)
2800                 igc_finalize_xdp(adapter, xdp_status);
2801
2802         igc_update_rx_stats(q_vector, total_packets, total_bytes);
2803
2804         if (xsk_uses_need_wakeup(ring->xsk_pool)) {
2805                 if (failure || ring->next_to_clean == ring->next_to_use)
2806                         xsk_set_rx_need_wakeup(ring->xsk_pool);
2807                 else
2808                         xsk_clear_rx_need_wakeup(ring->xsk_pool);
2809                 return total_packets;
2810         }
2811
2812         return failure ? budget : total_packets;
2813 }
2814
2815 static void igc_update_tx_stats(struct igc_q_vector *q_vector,
2816                                 unsigned int packets, unsigned int bytes)
2817 {
2818         struct igc_ring *ring = q_vector->tx.ring;
2819
2820         u64_stats_update_begin(&ring->tx_syncp);
2821         ring->tx_stats.bytes += bytes;
2822         ring->tx_stats.packets += packets;
2823         u64_stats_update_end(&ring->tx_syncp);
2824
2825         q_vector->tx.total_bytes += bytes;
2826         q_vector->tx.total_packets += packets;
2827 }
2828
2829 static void igc_xdp_xmit_zc(struct igc_ring *ring)
2830 {
2831         struct xsk_buff_pool *pool = ring->xsk_pool;
2832         struct netdev_queue *nq = txring_txq(ring);
2833         union igc_adv_tx_desc *tx_desc = NULL;
2834         int cpu = smp_processor_id();
2835         u16 ntu = ring->next_to_use;
2836         struct xdp_desc xdp_desc;
2837         u16 budget;
2838
2839         if (!netif_carrier_ok(ring->netdev))
2840                 return;
2841
2842         __netif_tx_lock(nq, cpu);
2843
2844         /* Avoid transmit queue timeout since we share it with the slow path */
2845         txq_trans_cond_update(nq);
2846
2847         budget = igc_desc_unused(ring);
2848
2849         while (xsk_tx_peek_desc(pool, &xdp_desc) && budget--) {
2850                 u32 cmd_type, olinfo_status;
2851                 struct igc_tx_buffer *bi;
2852                 dma_addr_t dma;
2853
2854                 cmd_type = IGC_ADVTXD_DTYP_DATA | IGC_ADVTXD_DCMD_DEXT |
2855                            IGC_ADVTXD_DCMD_IFCS | IGC_TXD_DCMD |
2856                            xdp_desc.len;
2857                 olinfo_status = xdp_desc.len << IGC_ADVTXD_PAYLEN_SHIFT;
2858
2859                 dma = xsk_buff_raw_get_dma(pool, xdp_desc.addr);
2860                 xsk_buff_raw_dma_sync_for_device(pool, dma, xdp_desc.len);
2861
2862                 tx_desc = IGC_TX_DESC(ring, ntu);
2863                 tx_desc->read.cmd_type_len = cpu_to_le32(cmd_type);
2864                 tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status);
2865                 tx_desc->read.buffer_addr = cpu_to_le64(dma);
2866
2867                 bi = &ring->tx_buffer_info[ntu];
2868                 bi->type = IGC_TX_BUFFER_TYPE_XSK;
2869                 bi->protocol = 0;
2870                 bi->bytecount = xdp_desc.len;
2871                 bi->gso_segs = 1;
2872                 bi->time_stamp = jiffies;
2873                 bi->next_to_watch = tx_desc;
2874
2875                 netdev_tx_sent_queue(txring_txq(ring), xdp_desc.len);
2876
2877                 ntu++;
2878                 if (ntu == ring->count)
2879                         ntu = 0;
2880         }
2881
2882         ring->next_to_use = ntu;
2883         if (tx_desc) {
2884                 igc_flush_tx_descriptors(ring);
2885                 xsk_tx_release(pool);
2886         }
2887
2888         __netif_tx_unlock(nq);
2889 }
2890
2891 /**
2892  * igc_clean_tx_irq - Reclaim resources after transmit completes
2893  * @q_vector: pointer to q_vector containing needed info
2894  * @napi_budget: Used to determine if we are in netpoll
2895  *
2896  * returns true if ring is completely cleaned
2897  */
2898 static bool igc_clean_tx_irq(struct igc_q_vector *q_vector, int napi_budget)
2899 {
2900         struct igc_adapter *adapter = q_vector->adapter;
2901         unsigned int total_bytes = 0, total_packets = 0;
2902         unsigned int budget = q_vector->tx.work_limit;
2903         struct igc_ring *tx_ring = q_vector->tx.ring;
2904         unsigned int i = tx_ring->next_to_clean;
2905         struct igc_tx_buffer *tx_buffer;
2906         union igc_adv_tx_desc *tx_desc;
2907         u32 xsk_frames = 0;
2908
2909         if (test_bit(__IGC_DOWN, &adapter->state))
2910                 return true;
2911
2912         tx_buffer = &tx_ring->tx_buffer_info[i];
2913         tx_desc = IGC_TX_DESC(tx_ring, i);
2914         i -= tx_ring->count;
2915
2916         do {
2917                 union igc_adv_tx_desc *eop_desc = tx_buffer->next_to_watch;
2918
2919                 /* if next_to_watch is not set then there is no work pending */
2920                 if (!eop_desc)
2921                         break;
2922
2923                 /* prevent any other reads prior to eop_desc */
2924                 smp_rmb();
2925
2926                 /* if DD is not set pending work has not been completed */
2927                 if (!(eop_desc->wb.status & cpu_to_le32(IGC_TXD_STAT_DD)))
2928                         break;
2929
2930                 /* clear next_to_watch to prevent false hangs */
2931                 tx_buffer->next_to_watch = NULL;
2932
2933                 /* update the statistics for this packet */
2934                 total_bytes += tx_buffer->bytecount;
2935                 total_packets += tx_buffer->gso_segs;
2936
2937                 switch (tx_buffer->type) {
2938                 case IGC_TX_BUFFER_TYPE_XSK:
2939                         xsk_frames++;
2940                         break;
2941                 case IGC_TX_BUFFER_TYPE_XDP:
2942                         xdp_return_frame(tx_buffer->xdpf);
2943                         igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
2944                         break;
2945                 case IGC_TX_BUFFER_TYPE_SKB:
2946                         napi_consume_skb(tx_buffer->skb, napi_budget);
2947                         igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
2948                         break;
2949                 default:
2950                         netdev_warn_once(tx_ring->netdev, "Unknown Tx buffer type\n");
2951                         break;
2952                 }
2953
2954                 /* clear last DMA location and unmap remaining buffers */
2955                 while (tx_desc != eop_desc) {
2956                         tx_buffer++;
2957                         tx_desc++;
2958                         i++;
2959                         if (unlikely(!i)) {
2960                                 i -= tx_ring->count;
2961                                 tx_buffer = tx_ring->tx_buffer_info;
2962                                 tx_desc = IGC_TX_DESC(tx_ring, 0);
2963                         }
2964
2965                         /* unmap any remaining paged data */
2966                         if (dma_unmap_len(tx_buffer, len))
2967                                 igc_unmap_tx_buffer(tx_ring->dev, tx_buffer);
2968                 }
2969
2970                 /* move us one more past the eop_desc for start of next pkt */
2971                 tx_buffer++;
2972                 tx_desc++;
2973                 i++;
2974                 if (unlikely(!i)) {
2975                         i -= tx_ring->count;
2976                         tx_buffer = tx_ring->tx_buffer_info;
2977                         tx_desc = IGC_TX_DESC(tx_ring, 0);
2978                 }
2979
2980                 /* issue prefetch for next Tx descriptor */
2981                 prefetch(tx_desc);
2982
2983                 /* update budget accounting */
2984                 budget--;
2985         } while (likely(budget));
2986
2987         netdev_tx_completed_queue(txring_txq(tx_ring),
2988                                   total_packets, total_bytes);
2989
2990         i += tx_ring->count;
2991         tx_ring->next_to_clean = i;
2992
2993         igc_update_tx_stats(q_vector, total_packets, total_bytes);
2994
2995         if (tx_ring->xsk_pool) {
2996                 if (xsk_frames)
2997                         xsk_tx_completed(tx_ring->xsk_pool, xsk_frames);
2998                 if (xsk_uses_need_wakeup(tx_ring->xsk_pool))
2999                         xsk_set_tx_need_wakeup(tx_ring->xsk_pool);
3000                 igc_xdp_xmit_zc(tx_ring);
3001         }
3002
3003         if (test_bit(IGC_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags)) {
3004                 struct igc_hw *hw = &adapter->hw;
3005
3006                 /* Detect a transmit hang in hardware, this serializes the
3007                  * check with the clearing of time_stamp and movement of i
3008                  */
3009                 clear_bit(IGC_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags);
3010                 if (tx_buffer->next_to_watch &&
3011                     time_after(jiffies, tx_buffer->time_stamp +
3012                     (adapter->tx_timeout_factor * HZ)) &&
3013                     !(rd32(IGC_STATUS) & IGC_STATUS_TXOFF) &&
3014                     (rd32(IGC_TDH(tx_ring->reg_idx)) !=
3015                      readl(tx_ring->tail))) {
3016                         /* detected Tx unit hang */
3017                         netdev_err(tx_ring->netdev,
3018                                    "Detected Tx Unit Hang\n"
3019                                    "  Tx Queue             <%d>\n"
3020                                    "  TDH                  <%x>\n"
3021                                    "  TDT                  <%x>\n"
3022                                    "  next_to_use          <%x>\n"
3023                                    "  next_to_clean        <%x>\n"
3024                                    "buffer_info[next_to_clean]\n"
3025                                    "  time_stamp           <%lx>\n"
3026                                    "  next_to_watch        <%p>\n"
3027                                    "  jiffies              <%lx>\n"
3028                                    "  desc.status          <%x>\n",
3029                                    tx_ring->queue_index,
3030                                    rd32(IGC_TDH(tx_ring->reg_idx)),
3031                                    readl(tx_ring->tail),
3032                                    tx_ring->next_to_use,
3033                                    tx_ring->next_to_clean,
3034                                    tx_buffer->time_stamp,
3035                                    tx_buffer->next_to_watch,
3036                                    jiffies,
3037                                    tx_buffer->next_to_watch->wb.status);
3038                         netif_stop_subqueue(tx_ring->netdev,
3039                                             tx_ring->queue_index);
3040
3041                         /* we are about to reset, no point in enabling stuff */
3042                         return true;
3043                 }
3044         }
3045
3046 #define TX_WAKE_THRESHOLD (DESC_NEEDED * 2)
3047         if (unlikely(total_packets &&
3048                      netif_carrier_ok(tx_ring->netdev) &&
3049                      igc_desc_unused(tx_ring) >= TX_WAKE_THRESHOLD)) {
3050                 /* Make sure that anybody stopping the queue after this
3051                  * sees the new next_to_clean.
3052                  */
3053                 smp_mb();
3054                 if (__netif_subqueue_stopped(tx_ring->netdev,
3055                                              tx_ring->queue_index) &&
3056                     !(test_bit(__IGC_DOWN, &adapter->state))) {
3057                         netif_wake_subqueue(tx_ring->netdev,
3058                                             tx_ring->queue_index);
3059
3060                         u64_stats_update_begin(&tx_ring->tx_syncp);
3061                         tx_ring->tx_stats.restart_queue++;
3062                         u64_stats_update_end(&tx_ring->tx_syncp);
3063                 }
3064         }
3065
3066         return !!budget;
3067 }
3068
3069 static int igc_find_mac_filter(struct igc_adapter *adapter,
3070                                enum igc_mac_filter_type type, const u8 *addr)
3071 {
3072         struct igc_hw *hw = &adapter->hw;
3073         int max_entries = hw->mac.rar_entry_count;
3074         u32 ral, rah;
3075         int i;
3076
3077         for (i = 0; i < max_entries; i++) {
3078                 ral = rd32(IGC_RAL(i));
3079                 rah = rd32(IGC_RAH(i));
3080
3081                 if (!(rah & IGC_RAH_AV))
3082                         continue;
3083                 if (!!(rah & IGC_RAH_ASEL_SRC_ADDR) != type)
3084                         continue;
3085                 if ((rah & IGC_RAH_RAH_MASK) !=
3086                     le16_to_cpup((__le16 *)(addr + 4)))
3087                         continue;
3088                 if (ral != le32_to_cpup((__le32 *)(addr)))
3089                         continue;
3090
3091                 return i;
3092         }
3093
3094         return -1;
3095 }
3096
3097 static int igc_get_avail_mac_filter_slot(struct igc_adapter *adapter)
3098 {
3099         struct igc_hw *hw = &adapter->hw;
3100         int max_entries = hw->mac.rar_entry_count;
3101         u32 rah;
3102         int i;
3103
3104         for (i = 0; i < max_entries; i++) {
3105                 rah = rd32(IGC_RAH(i));
3106
3107                 if (!(rah & IGC_RAH_AV))
3108                         return i;
3109         }
3110
3111         return -1;
3112 }
3113
3114 /**
3115  * igc_add_mac_filter() - Add MAC address filter
3116  * @adapter: Pointer to adapter where the filter should be added
3117  * @type: MAC address filter type (source or destination)
3118  * @addr: MAC address
3119  * @queue: If non-negative, queue assignment feature is enabled and frames
3120  *         matching the filter are enqueued onto 'queue'. Otherwise, queue
3121  *         assignment is disabled.
3122  *
3123  * Return: 0 in case of success, negative errno code otherwise.
3124  */
3125 static int igc_add_mac_filter(struct igc_adapter *adapter,
3126                               enum igc_mac_filter_type type, const u8 *addr,
3127                               int queue)
3128 {
3129         struct net_device *dev = adapter->netdev;
3130         int index;
3131
3132         index = igc_find_mac_filter(adapter, type, addr);
3133         if (index >= 0)
3134                 goto update_filter;
3135
3136         index = igc_get_avail_mac_filter_slot(adapter);
3137         if (index < 0)
3138                 return -ENOSPC;
3139
3140         netdev_dbg(dev, "Add MAC address filter: index %d type %s address %pM queue %d\n",
3141                    index, type == IGC_MAC_FILTER_TYPE_DST ? "dst" : "src",
3142                    addr, queue);
3143
3144 update_filter:
3145         igc_set_mac_filter_hw(adapter, index, type, addr, queue);
3146         return 0;
3147 }
3148
3149 /**
3150  * igc_del_mac_filter() - Delete MAC address filter
3151  * @adapter: Pointer to adapter where the filter should be deleted from
3152  * @type: MAC address filter type (source or destination)
3153  * @addr: MAC address
3154  */
3155 static void igc_del_mac_filter(struct igc_adapter *adapter,
3156                                enum igc_mac_filter_type type, const u8 *addr)
3157 {
3158         struct net_device *dev = adapter->netdev;
3159         int index;
3160
3161         index = igc_find_mac_filter(adapter, type, addr);
3162         if (index < 0)
3163                 return;
3164
3165         if (index == 0) {
3166                 /* If this is the default filter, we don't actually delete it.
3167                  * We just reset to its default value i.e. disable queue
3168                  * assignment.
3169                  */
3170                 netdev_dbg(dev, "Disable default MAC filter queue assignment");
3171
3172                 igc_set_mac_filter_hw(adapter, 0, type, addr, -1);
3173         } else {
3174                 netdev_dbg(dev, "Delete MAC address filter: index %d type %s address %pM\n",
3175                            index,
3176                            type == IGC_MAC_FILTER_TYPE_DST ? "dst" : "src",
3177                            addr);
3178
3179                 igc_clear_mac_filter_hw(adapter, index);
3180         }
3181 }
3182
3183 /**
3184  * igc_add_vlan_prio_filter() - Add VLAN priority filter
3185  * @adapter: Pointer to adapter where the filter should be added
3186  * @prio: VLAN priority value
3187  * @queue: Queue number which matching frames are assigned to
3188  *
3189  * Return: 0 in case of success, negative errno code otherwise.
3190  */
3191 static int igc_add_vlan_prio_filter(struct igc_adapter *adapter, int prio,
3192                                     int queue)
3193 {
3194         struct net_device *dev = adapter->netdev;
3195         struct igc_hw *hw = &adapter->hw;
3196         u32 vlanpqf;
3197
3198         vlanpqf = rd32(IGC_VLANPQF);
3199
3200         if (vlanpqf & IGC_VLANPQF_VALID(prio)) {
3201                 netdev_dbg(dev, "VLAN priority filter already in use\n");
3202                 return -EEXIST;
3203         }
3204
3205         vlanpqf |= IGC_VLANPQF_QSEL(prio, queue);
3206         vlanpqf |= IGC_VLANPQF_VALID(prio);
3207
3208         wr32(IGC_VLANPQF, vlanpqf);
3209
3210         netdev_dbg(dev, "Add VLAN priority filter: prio %d queue %d\n",
3211                    prio, queue);
3212         return 0;
3213 }
3214
3215 /**
3216  * igc_del_vlan_prio_filter() - Delete VLAN priority filter
3217  * @adapter: Pointer to adapter where the filter should be deleted from
3218  * @prio: VLAN priority value
3219  */
3220 static void igc_del_vlan_prio_filter(struct igc_adapter *adapter, int prio)
3221 {
3222         struct igc_hw *hw = &adapter->hw;
3223         u32 vlanpqf;
3224
3225         vlanpqf = rd32(IGC_VLANPQF);
3226
3227         vlanpqf &= ~IGC_VLANPQF_VALID(prio);
3228         vlanpqf &= ~IGC_VLANPQF_QSEL(prio, IGC_VLANPQF_QUEUE_MASK);
3229
3230         wr32(IGC_VLANPQF, vlanpqf);
3231
3232         netdev_dbg(adapter->netdev, "Delete VLAN priority filter: prio %d\n",
3233                    prio);
3234 }
3235
3236 static int igc_get_avail_etype_filter_slot(struct igc_adapter *adapter)
3237 {
3238         struct igc_hw *hw = &adapter->hw;
3239         int i;
3240
3241         for (i = 0; i < MAX_ETYPE_FILTER; i++) {
3242                 u32 etqf = rd32(IGC_ETQF(i));
3243
3244                 if (!(etqf & IGC_ETQF_FILTER_ENABLE))
3245                         return i;
3246         }
3247
3248         return -1;
3249 }
3250
3251 /**
3252  * igc_add_etype_filter() - Add ethertype filter
3253  * @adapter: Pointer to adapter where the filter should be added
3254  * @etype: Ethertype value
3255  * @queue: If non-negative, queue assignment feature is enabled and frames
3256  *         matching the filter are enqueued onto 'queue'. Otherwise, queue
3257  *         assignment is disabled.
3258  *
3259  * Return: 0 in case of success, negative errno code otherwise.
3260  */
3261 static int igc_add_etype_filter(struct igc_adapter *adapter, u16 etype,
3262                                 int queue)
3263 {
3264         struct igc_hw *hw = &adapter->hw;
3265         int index;
3266         u32 etqf;
3267
3268         index = igc_get_avail_etype_filter_slot(adapter);
3269         if (index < 0)
3270                 return -ENOSPC;
3271
3272         etqf = rd32(IGC_ETQF(index));
3273
3274         etqf &= ~IGC_ETQF_ETYPE_MASK;
3275         etqf |= etype;
3276
3277         if (queue >= 0) {
3278                 etqf &= ~IGC_ETQF_QUEUE_MASK;
3279                 etqf |= (queue << IGC_ETQF_QUEUE_SHIFT);
3280                 etqf |= IGC_ETQF_QUEUE_ENABLE;
3281         }
3282
3283         etqf |= IGC_ETQF_FILTER_ENABLE;
3284
3285         wr32(IGC_ETQF(index), etqf);
3286
3287         netdev_dbg(adapter->netdev, "Add ethertype filter: etype %04x queue %d\n",
3288                    etype, queue);
3289         return 0;
3290 }
3291
3292 static int igc_find_etype_filter(struct igc_adapter *adapter, u16 etype)
3293 {
3294         struct igc_hw *hw = &adapter->hw;
3295         int i;
3296
3297         for (i = 0; i < MAX_ETYPE_FILTER; i++) {
3298                 u32 etqf = rd32(IGC_ETQF(i));
3299
3300                 if ((etqf & IGC_ETQF_ETYPE_MASK) == etype)
3301                         return i;
3302         }
3303
3304         return -1;
3305 }
3306
3307 /**
3308  * igc_del_etype_filter() - Delete ethertype filter
3309  * @adapter: Pointer to adapter where the filter should be deleted from
3310  * @etype: Ethertype value
3311  */
3312 static void igc_del_etype_filter(struct igc_adapter *adapter, u16 etype)
3313 {
3314         struct igc_hw *hw = &adapter->hw;
3315         int index;
3316
3317         index = igc_find_etype_filter(adapter, etype);
3318         if (index < 0)
3319                 return;
3320
3321         wr32(IGC_ETQF(index), 0);
3322
3323         netdev_dbg(adapter->netdev, "Delete ethertype filter: etype %04x\n",
3324                    etype);
3325 }
3326
3327 static int igc_flex_filter_select(struct igc_adapter *adapter,
3328                                   struct igc_flex_filter *input,
3329                                   u32 *fhft)
3330 {
3331         struct igc_hw *hw = &adapter->hw;
3332         u8 fhft_index;
3333         u32 fhftsl;
3334
3335         if (input->index >= MAX_FLEX_FILTER) {
3336                 dev_err(&adapter->pdev->dev, "Wrong Flex Filter index selected!\n");
3337                 return -EINVAL;
3338         }
3339
3340         /* Indirect table select register */
3341         fhftsl = rd32(IGC_FHFTSL);
3342         fhftsl &= ~IGC_FHFTSL_FTSL_MASK;
3343         switch (input->index) {
3344         case 0 ... 7:
3345                 fhftsl |= 0x00;
3346                 break;
3347         case 8 ... 15:
3348                 fhftsl |= 0x01;
3349                 break;
3350         case 16 ... 23:
3351                 fhftsl |= 0x02;
3352                 break;
3353         case 24 ... 31:
3354                 fhftsl |= 0x03;
3355                 break;
3356         }
3357         wr32(IGC_FHFTSL, fhftsl);
3358
3359         /* Normalize index down to host table register */
3360         fhft_index = input->index % 8;
3361
3362         *fhft = (fhft_index < 4) ? IGC_FHFT(fhft_index) :
3363                 IGC_FHFT_EXT(fhft_index - 4);
3364
3365         return 0;
3366 }
3367
3368 static int igc_write_flex_filter_ll(struct igc_adapter *adapter,
3369                                     struct igc_flex_filter *input)
3370 {
3371         struct device *dev = &adapter->pdev->dev;
3372         struct igc_hw *hw = &adapter->hw;
3373         u8 *data = input->data;
3374         u8 *mask = input->mask;
3375         u32 queuing;
3376         u32 fhft;
3377         u32 wufc;
3378         int ret;
3379         int i;
3380
3381         /* Length has to be aligned to 8. Otherwise the filter will fail. Bail
3382          * out early to avoid surprises later.
3383          */
3384         if (input->length % 8 != 0) {
3385                 dev_err(dev, "The length of a flex filter has to be 8 byte aligned!\n");
3386                 return -EINVAL;
3387         }
3388
3389         /* Select corresponding flex filter register and get base for host table. */
3390         ret = igc_flex_filter_select(adapter, input, &fhft);
3391         if (ret)
3392                 return ret;
3393
3394         /* When adding a filter globally disable flex filter feature. That is
3395          * recommended within the datasheet.
3396          */
3397         wufc = rd32(IGC_WUFC);
3398         wufc &= ~IGC_WUFC_FLEX_HQ;
3399         wr32(IGC_WUFC, wufc);
3400
3401         /* Configure filter */
3402         queuing = input->length & IGC_FHFT_LENGTH_MASK;
3403         queuing |= (input->rx_queue << IGC_FHFT_QUEUE_SHIFT) & IGC_FHFT_QUEUE_MASK;
3404         queuing |= (input->prio << IGC_FHFT_PRIO_SHIFT) & IGC_FHFT_PRIO_MASK;
3405
3406         if (input->immediate_irq)
3407                 queuing |= IGC_FHFT_IMM_INT;
3408
3409         if (input->drop)
3410                 queuing |= IGC_FHFT_DROP;
3411
3412         wr32(fhft + 0xFC, queuing);
3413
3414         /* Write data (128 byte) and mask (128 bit) */
3415         for (i = 0; i < 16; ++i) {
3416                 const size_t data_idx = i * 8;
3417                 const size_t row_idx = i * 16;
3418                 u32 dw0 =
3419                         (data[data_idx + 0] << 0) |
3420                         (data[data_idx + 1] << 8) |
3421                         (data[data_idx + 2] << 16) |
3422                         (data[data_idx + 3] << 24);
3423                 u32 dw1 =
3424                         (data[data_idx + 4] << 0) |
3425                         (data[data_idx + 5] << 8) |
3426                         (data[data_idx + 6] << 16) |
3427                         (data[data_idx + 7] << 24);
3428                 u32 tmp;
3429
3430                 /* Write row: dw0, dw1 and mask */
3431                 wr32(fhft + row_idx, dw0);
3432                 wr32(fhft + row_idx + 4, dw1);
3433
3434                 /* mask is only valid for MASK(7, 0) */
3435                 tmp = rd32(fhft + row_idx + 8);
3436                 tmp &= ~GENMASK(7, 0);
3437                 tmp |= mask[i];
3438                 wr32(fhft + row_idx + 8, tmp);
3439         }
3440
3441         /* Enable filter. */
3442         wufc |= IGC_WUFC_FLEX_HQ;
3443         if (input->index > 8) {
3444                 /* Filter 0-7 are enabled via WUFC. The other 24 filters are not. */
3445                 u32 wufc_ext = rd32(IGC_WUFC_EXT);
3446
3447                 wufc_ext |= (IGC_WUFC_EXT_FLX8 << (input->index - 8));
3448
3449                 wr32(IGC_WUFC_EXT, wufc_ext);
3450         } else {
3451                 wufc |= (IGC_WUFC_FLX0 << input->index);
3452         }
3453         wr32(IGC_WUFC, wufc);
3454
3455         dev_dbg(&adapter->pdev->dev, "Added flex filter %u to HW.\n",
3456                 input->index);
3457
3458         return 0;
3459 }
3460
3461 static void igc_flex_filter_add_field(struct igc_flex_filter *flex,
3462                                       const void *src, unsigned int offset,
3463                                       size_t len, const void *mask)
3464 {
3465         int i;
3466
3467         /* data */
3468         memcpy(&flex->data[offset], src, len);
3469
3470         /* mask */
3471         for (i = 0; i < len; ++i) {
3472                 const unsigned int idx = i + offset;
3473                 const u8 *ptr = mask;
3474
3475                 if (mask) {
3476                         if (ptr[i] & 0xff)
3477                                 flex->mask[idx / 8] |= BIT(idx % 8);
3478
3479                         continue;
3480                 }
3481
3482                 flex->mask[idx / 8] |= BIT(idx % 8);
3483         }
3484 }
3485
3486 static int igc_find_avail_flex_filter_slot(struct igc_adapter *adapter)
3487 {
3488         struct igc_hw *hw = &adapter->hw;
3489         u32 wufc, wufc_ext;
3490         int i;
3491
3492         wufc = rd32(IGC_WUFC);
3493         wufc_ext = rd32(IGC_WUFC_EXT);
3494
3495         for (i = 0; i < MAX_FLEX_FILTER; i++) {
3496                 if (i < 8) {
3497                         if (!(wufc & (IGC_WUFC_FLX0 << i)))
3498                                 return i;
3499                 } else {
3500                         if (!(wufc_ext & (IGC_WUFC_EXT_FLX8 << (i - 8))))
3501                                 return i;
3502                 }
3503         }
3504
3505         return -ENOSPC;
3506 }
3507
3508 static bool igc_flex_filter_in_use(struct igc_adapter *adapter)
3509 {
3510         struct igc_hw *hw = &adapter->hw;
3511         u32 wufc, wufc_ext;
3512
3513         wufc = rd32(IGC_WUFC);
3514         wufc_ext = rd32(IGC_WUFC_EXT);
3515
3516         if (wufc & IGC_WUFC_FILTER_MASK)
3517                 return true;
3518
3519         if (wufc_ext & IGC_WUFC_EXT_FILTER_MASK)
3520                 return true;
3521
3522         return false;
3523 }
3524
3525 static int igc_add_flex_filter(struct igc_adapter *adapter,
3526                                struct igc_nfc_rule *rule)
3527 {
3528         struct igc_flex_filter flex = { };
3529         struct igc_nfc_filter *filter = &rule->filter;
3530         unsigned int eth_offset, user_offset;
3531         int ret, index;
3532         bool vlan;
3533
3534         index = igc_find_avail_flex_filter_slot(adapter);
3535         if (index < 0)
3536                 return -ENOSPC;
3537
3538         /* Construct the flex filter:
3539          *  -> dest_mac [6]
3540          *  -> src_mac [6]
3541          *  -> tpid [2]
3542          *  -> vlan tci [2]
3543          *  -> ether type [2]
3544          *  -> user data [8]
3545          *  -> = 26 bytes => 32 length
3546          */
3547         flex.index    = index;
3548         flex.length   = 32;
3549         flex.rx_queue = rule->action;
3550
3551         vlan = rule->filter.vlan_tci || rule->filter.vlan_etype;
3552         eth_offset = vlan ? 16 : 12;
3553         user_offset = vlan ? 18 : 14;
3554
3555         /* Add destination MAC  */
3556         if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR)
3557                 igc_flex_filter_add_field(&flex, &filter->dst_addr, 0,
3558                                           ETH_ALEN, NULL);
3559
3560         /* Add source MAC */
3561         if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR)
3562                 igc_flex_filter_add_field(&flex, &filter->src_addr, 6,
3563                                           ETH_ALEN, NULL);
3564
3565         /* Add VLAN etype */
3566         if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_ETYPE)
3567                 igc_flex_filter_add_field(&flex, &filter->vlan_etype, 12,
3568                                           sizeof(filter->vlan_etype),
3569                                           NULL);
3570
3571         /* Add VLAN TCI */
3572         if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI)
3573                 igc_flex_filter_add_field(&flex, &filter->vlan_tci, 14,
3574                                           sizeof(filter->vlan_tci), NULL);
3575
3576         /* Add Ether type */
3577         if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE) {
3578                 __be16 etype = cpu_to_be16(filter->etype);
3579
3580                 igc_flex_filter_add_field(&flex, &etype, eth_offset,
3581                                           sizeof(etype), NULL);
3582         }
3583
3584         /* Add user data */
3585         if (rule->filter.match_flags & IGC_FILTER_FLAG_USER_DATA)
3586                 igc_flex_filter_add_field(&flex, &filter->user_data,
3587                                           user_offset,
3588                                           sizeof(filter->user_data),
3589                                           filter->user_mask);
3590
3591         /* Add it down to the hardware and enable it. */
3592         ret = igc_write_flex_filter_ll(adapter, &flex);
3593         if (ret)
3594                 return ret;
3595
3596         filter->flex_index = index;
3597
3598         return 0;
3599 }
3600
3601 static void igc_del_flex_filter(struct igc_adapter *adapter,
3602                                 u16 reg_index)
3603 {
3604         struct igc_hw *hw = &adapter->hw;
3605         u32 wufc;
3606
3607         /* Just disable the filter. The filter table itself is kept
3608          * intact. Another flex_filter_add() should override the "old" data
3609          * then.
3610          */
3611         if (reg_index > 8) {
3612                 u32 wufc_ext = rd32(IGC_WUFC_EXT);
3613
3614                 wufc_ext &= ~(IGC_WUFC_EXT_FLX8 << (reg_index - 8));
3615                 wr32(IGC_WUFC_EXT, wufc_ext);
3616         } else {
3617                 wufc = rd32(IGC_WUFC);
3618
3619                 wufc &= ~(IGC_WUFC_FLX0 << reg_index);
3620                 wr32(IGC_WUFC, wufc);
3621         }
3622
3623         if (igc_flex_filter_in_use(adapter))
3624                 return;
3625
3626         /* No filters are in use, we may disable flex filters */
3627         wufc = rd32(IGC_WUFC);
3628         wufc &= ~IGC_WUFC_FLEX_HQ;
3629         wr32(IGC_WUFC, wufc);
3630 }
3631
3632 static int igc_enable_nfc_rule(struct igc_adapter *adapter,
3633                                struct igc_nfc_rule *rule)
3634 {
3635         int err;
3636
3637         if (rule->flex) {
3638                 return igc_add_flex_filter(adapter, rule);
3639         }
3640
3641         if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE) {
3642                 err = igc_add_etype_filter(adapter, rule->filter.etype,
3643                                            rule->action);
3644                 if (err)
3645                         return err;
3646         }
3647
3648         if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR) {
3649                 err = igc_add_mac_filter(adapter, IGC_MAC_FILTER_TYPE_SRC,
3650                                          rule->filter.src_addr, rule->action);
3651                 if (err)
3652                         return err;
3653         }
3654
3655         if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR) {
3656                 err = igc_add_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST,
3657                                          rule->filter.dst_addr, rule->action);
3658                 if (err)
3659                         return err;
3660         }
3661
3662         if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI) {
3663                 int prio = (rule->filter.vlan_tci & VLAN_PRIO_MASK) >>
3664                            VLAN_PRIO_SHIFT;
3665
3666                 err = igc_add_vlan_prio_filter(adapter, prio, rule->action);
3667                 if (err)
3668                         return err;
3669         }
3670
3671         return 0;
3672 }
3673
3674 static void igc_disable_nfc_rule(struct igc_adapter *adapter,
3675                                  const struct igc_nfc_rule *rule)
3676 {
3677         if (rule->flex) {
3678                 igc_del_flex_filter(adapter, rule->filter.flex_index);
3679                 return;
3680         }
3681
3682         if (rule->filter.match_flags & IGC_FILTER_FLAG_ETHER_TYPE)
3683                 igc_del_etype_filter(adapter, rule->filter.etype);
3684
3685         if (rule->filter.match_flags & IGC_FILTER_FLAG_VLAN_TCI) {
3686                 int prio = (rule->filter.vlan_tci & VLAN_PRIO_MASK) >>
3687                            VLAN_PRIO_SHIFT;
3688
3689                 igc_del_vlan_prio_filter(adapter, prio);
3690         }
3691
3692         if (rule->filter.match_flags & IGC_FILTER_FLAG_SRC_MAC_ADDR)
3693                 igc_del_mac_filter(adapter, IGC_MAC_FILTER_TYPE_SRC,
3694                                    rule->filter.src_addr);
3695
3696         if (rule->filter.match_flags & IGC_FILTER_FLAG_DST_MAC_ADDR)
3697                 igc_del_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST,
3698                                    rule->filter.dst_addr);
3699 }
3700
3701 /**
3702  * igc_get_nfc_rule() - Get NFC rule
3703  * @adapter: Pointer to adapter
3704  * @location: Rule location
3705  *
3706  * Context: Expects adapter->nfc_rule_lock to be held by caller.
3707  *
3708  * Return: Pointer to NFC rule at @location. If not found, NULL.
3709  */
3710 struct igc_nfc_rule *igc_get_nfc_rule(struct igc_adapter *adapter,
3711                                       u32 location)
3712 {
3713         struct igc_nfc_rule *rule;
3714
3715         list_for_each_entry(rule, &adapter->nfc_rule_list, list) {
3716                 if (rule->location == location)
3717                         return rule;
3718                 if (rule->location > location)
3719                         break;
3720         }
3721
3722         return NULL;
3723 }
3724
3725 /**
3726  * igc_del_nfc_rule() - Delete NFC rule
3727  * @adapter: Pointer to adapter
3728  * @rule: Pointer to rule to be deleted
3729  *
3730  * Disable NFC rule in hardware and delete it from adapter.
3731  *
3732  * Context: Expects adapter->nfc_rule_lock to be held by caller.
3733  */
3734 void igc_del_nfc_rule(struct igc_adapter *adapter, struct igc_nfc_rule *rule)
3735 {
3736         igc_disable_nfc_rule(adapter, rule);
3737
3738         list_del(&rule->list);
3739         adapter->nfc_rule_count--;
3740
3741         kfree(rule);
3742 }
3743
3744 static void igc_flush_nfc_rules(struct igc_adapter *adapter)
3745 {
3746         struct igc_nfc_rule *rule, *tmp;
3747
3748         mutex_lock(&adapter->nfc_rule_lock);
3749
3750         list_for_each_entry_safe(rule, tmp, &adapter->nfc_rule_list, list)
3751                 igc_del_nfc_rule(adapter, rule);
3752
3753         mutex_unlock(&adapter->nfc_rule_lock);
3754 }
3755
3756 /**
3757  * igc_add_nfc_rule() - Add NFC rule
3758  * @adapter: Pointer to adapter
3759  * @rule: Pointer to rule to be added
3760  *
3761  * Enable NFC rule in hardware and add it to adapter.
3762  *
3763  * Context: Expects adapter->nfc_rule_lock to be held by caller.
3764  *
3765  * Return: 0 on success, negative errno on failure.
3766  */
3767 int igc_add_nfc_rule(struct igc_adapter *adapter, struct igc_nfc_rule *rule)
3768 {
3769         struct igc_nfc_rule *pred, *cur;
3770         int err;
3771
3772         err = igc_enable_nfc_rule(adapter, rule);
3773         if (err)
3774                 return err;
3775
3776         pred = NULL;
3777         list_for_each_entry(cur, &adapter->nfc_rule_list, list) {
3778                 if (cur->location >= rule->location)
3779                         break;
3780                 pred = cur;
3781         }
3782
3783         list_add(&rule->list, pred ? &pred->list : &adapter->nfc_rule_list);
3784         adapter->nfc_rule_count++;
3785         return 0;
3786 }
3787
3788 static void igc_restore_nfc_rules(struct igc_adapter *adapter)
3789 {
3790         struct igc_nfc_rule *rule;
3791
3792         mutex_lock(&adapter->nfc_rule_lock);
3793
3794         list_for_each_entry_reverse(rule, &adapter->nfc_rule_list, list)
3795                 igc_enable_nfc_rule(adapter, rule);
3796
3797         mutex_unlock(&adapter->nfc_rule_lock);
3798 }
3799
3800 static int igc_uc_sync(struct net_device *netdev, const unsigned char *addr)
3801 {
3802         struct igc_adapter *adapter = netdev_priv(netdev);
3803
3804         return igc_add_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST, addr, -1);
3805 }
3806
3807 static int igc_uc_unsync(struct net_device *netdev, const unsigned char *addr)
3808 {
3809         struct igc_adapter *adapter = netdev_priv(netdev);
3810
3811         igc_del_mac_filter(adapter, IGC_MAC_FILTER_TYPE_DST, addr);
3812         return 0;
3813 }
3814
3815 /**
3816  * igc_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set
3817  * @netdev: network interface device structure
3818  *
3819  * The set_rx_mode entry point is called whenever the unicast or multicast
3820  * address lists or the network interface flags are updated.  This routine is
3821  * responsible for configuring the hardware for proper unicast, multicast,
3822  * promiscuous mode, and all-multi behavior.
3823  */
3824 static void igc_set_rx_mode(struct net_device *netdev)
3825 {
3826         struct igc_adapter *adapter = netdev_priv(netdev);
3827         struct igc_hw *hw = &adapter->hw;
3828         u32 rctl = 0, rlpml = MAX_JUMBO_FRAME_SIZE;
3829         int count;
3830
3831         /* Check for Promiscuous and All Multicast modes */
3832         if (netdev->flags & IFF_PROMISC) {
3833                 rctl |= IGC_RCTL_UPE | IGC_RCTL_MPE;
3834         } else {
3835                 if (netdev->flags & IFF_ALLMULTI) {
3836                         rctl |= IGC_RCTL_MPE;
3837                 } else {
3838                         /* Write addresses to the MTA, if the attempt fails
3839                          * then we should just turn on promiscuous mode so
3840                          * that we can at least receive multicast traffic
3841                          */
3842                         count = igc_write_mc_addr_list(netdev);
3843                         if (count < 0)
3844                                 rctl |= IGC_RCTL_MPE;
3845                 }
3846         }
3847
3848         /* Write addresses to available RAR registers, if there is not
3849          * sufficient space to store all the addresses then enable
3850          * unicast promiscuous mode
3851          */
3852         if (__dev_uc_sync(netdev, igc_uc_sync, igc_uc_unsync))
3853                 rctl |= IGC_RCTL_UPE;
3854
3855         /* update state of unicast and multicast */
3856         rctl |= rd32(IGC_RCTL) & ~(IGC_RCTL_UPE | IGC_RCTL_MPE);
3857         wr32(IGC_RCTL, rctl);
3858
3859 #if (PAGE_SIZE < 8192)
3860         if (adapter->max_frame_size <= IGC_MAX_FRAME_BUILD_SKB)
3861                 rlpml = IGC_MAX_FRAME_BUILD_SKB;
3862 #endif
3863         wr32(IGC_RLPML, rlpml);
3864 }
3865
3866 /**
3867  * igc_configure - configure the hardware for RX and TX
3868  * @adapter: private board structure
3869  */
3870 static void igc_configure(struct igc_adapter *adapter)
3871 {
3872         struct net_device *netdev = adapter->netdev;
3873         int i = 0;
3874
3875         igc_get_hw_control(adapter);
3876         igc_set_rx_mode(netdev);
3877
3878         igc_restore_vlan(adapter);
3879
3880         igc_setup_tctl(adapter);
3881         igc_setup_mrqc(adapter);
3882         igc_setup_rctl(adapter);
3883
3884         igc_set_default_mac_filter(adapter);
3885         igc_restore_nfc_rules(adapter);
3886
3887         igc_configure_tx(adapter);
3888         igc_configure_rx(adapter);
3889
3890         igc_rx_fifo_flush_base(&adapter->hw);
3891
3892         /* call igc_desc_unused which always leaves
3893          * at least 1 descriptor unused to make sure
3894          * next_to_use != next_to_clean
3895          */
3896         for (i = 0; i < adapter->num_rx_queues; i++) {
3897                 struct igc_ring *ring = adapter->rx_ring[i];
3898
3899                 if (ring->xsk_pool)
3900                         igc_alloc_rx_buffers_zc(ring, igc_desc_unused(ring));
3901                 else
3902                         igc_alloc_rx_buffers(ring, igc_desc_unused(ring));
3903         }
3904 }
3905
3906 /**
3907  * igc_write_ivar - configure ivar for given MSI-X vector
3908  * @hw: pointer to the HW structure
3909  * @msix_vector: vector number we are allocating to a given ring
3910  * @index: row index of IVAR register to write within IVAR table
3911  * @offset: column offset of in IVAR, should be multiple of 8
3912  *
3913  * The IVAR table consists of 2 columns,
3914  * each containing an cause allocation for an Rx and Tx ring, and a
3915  * variable number of rows depending on the number of queues supported.
3916  */
3917 static void igc_write_ivar(struct igc_hw *hw, int msix_vector,
3918                            int index, int offset)
3919 {
3920         u32 ivar = array_rd32(IGC_IVAR0, index);
3921
3922         /* clear any bits that are currently set */
3923         ivar &= ~((u32)0xFF << offset);
3924
3925         /* write vector and valid bit */
3926         ivar |= (msix_vector | IGC_IVAR_VALID) << offset;
3927
3928         array_wr32(IGC_IVAR0, index, ivar);
3929 }
3930
3931 static void igc_assign_vector(struct igc_q_vector *q_vector, int msix_vector)
3932 {
3933         struct igc_adapter *adapter = q_vector->adapter;
3934         struct igc_hw *hw = &adapter->hw;
3935         int rx_queue = IGC_N0_QUEUE;
3936         int tx_queue = IGC_N0_QUEUE;
3937
3938         if (q_vector->rx.ring)
3939                 rx_queue = q_vector->rx.ring->reg_idx;
3940         if (q_vector->tx.ring)
3941                 tx_queue = q_vector->tx.ring->reg_idx;
3942
3943         switch (hw->mac.type) {
3944         case igc_i225:
3945                 if (rx_queue > IGC_N0_QUEUE)
3946                         igc_write_ivar(hw, msix_vector,
3947                                        rx_queue >> 1,
3948                                        (rx_queue & 0x1) << 4);
3949                 if (tx_queue > IGC_N0_QUEUE)
3950                         igc_write_ivar(hw, msix_vector,
3951                                        tx_queue >> 1,
3952                                        ((tx_queue & 0x1) << 4) + 8);
3953                 q_vector->eims_value = BIT(msix_vector);
3954                 break;
3955         default:
3956                 WARN_ONCE(hw->mac.type != igc_i225, "Wrong MAC type\n");
3957                 break;
3958         }
3959
3960         /* add q_vector eims value to global eims_enable_mask */
3961         adapter->eims_enable_mask |= q_vector->eims_value;
3962
3963         /* configure q_vector to set itr on first interrupt */
3964         q_vector->set_itr = 1;
3965 }
3966
3967 /**
3968  * igc_configure_msix - Configure MSI-X hardware
3969  * @adapter: Pointer to adapter structure
3970  *
3971  * igc_configure_msix sets up the hardware to properly
3972  * generate MSI-X interrupts.
3973  */
3974 static void igc_configure_msix(struct igc_adapter *adapter)
3975 {
3976         struct igc_hw *hw = &adapter->hw;
3977         int i, vector = 0;
3978         u32 tmp;
3979
3980         adapter->eims_enable_mask = 0;
3981
3982         /* set vector for other causes, i.e. link changes */
3983         switch (hw->mac.type) {
3984         case igc_i225:
3985                 /* Turn on MSI-X capability first, or our settings
3986                  * won't stick.  And it will take days to debug.
3987                  */
3988                 wr32(IGC_GPIE, IGC_GPIE_MSIX_MODE |
3989                      IGC_GPIE_PBA | IGC_GPIE_EIAME |
3990                      IGC_GPIE_NSICR);
3991
3992                 /* enable msix_other interrupt */
3993                 adapter->eims_other = BIT(vector);
3994                 tmp = (vector++ | IGC_IVAR_VALID) << 8;
3995
3996                 wr32(IGC_IVAR_MISC, tmp);
3997                 break;
3998         default:
3999                 /* do nothing, since nothing else supports MSI-X */
4000                 break;
4001         } /* switch (hw->mac.type) */
4002
4003         adapter->eims_enable_mask |= adapter->eims_other;
4004
4005         for (i = 0; i < adapter->num_q_vectors; i++)
4006                 igc_assign_vector(adapter->q_vector[i], vector++);
4007
4008         wrfl();
4009 }
4010
4011 /**
4012  * igc_irq_enable - Enable default interrupt generation settings
4013  * @adapter: board private structure
4014  */
4015 static void igc_irq_enable(struct igc_adapter *adapter)
4016 {
4017         struct igc_hw *hw = &adapter->hw;
4018
4019         if (adapter->msix_entries) {
4020                 u32 ims = IGC_IMS_LSC | IGC_IMS_DOUTSYNC | IGC_IMS_DRSTA;
4021                 u32 regval = rd32(IGC_EIAC);
4022
4023                 wr32(IGC_EIAC, regval | adapter->eims_enable_mask);
4024                 regval = rd32(IGC_EIAM);
4025                 wr32(IGC_EIAM, regval | adapter->eims_enable_mask);
4026                 wr32(IGC_EIMS, adapter->eims_enable_mask);
4027                 wr32(IGC_IMS, ims);
4028         } else {
4029                 wr32(IGC_IMS, IMS_ENABLE_MASK | IGC_IMS_DRSTA);
4030                 wr32(IGC_IAM, IMS_ENABLE_MASK | IGC_IMS_DRSTA);
4031         }
4032 }
4033
4034 /**
4035  * igc_irq_disable - Mask off interrupt generation on the NIC
4036  * @adapter: board private structure
4037  */
4038 static void igc_irq_disable(struct igc_adapter *adapter)
4039 {
4040         struct igc_hw *hw = &adapter->hw;
4041
4042         if (adapter->msix_entries) {
4043                 u32 regval = rd32(IGC_EIAM);
4044
4045                 wr32(IGC_EIAM, regval & ~adapter->eims_enable_mask);
4046                 wr32(IGC_EIMC, adapter->eims_enable_mask);
4047                 regval = rd32(IGC_EIAC);
4048                 wr32(IGC_EIAC, regval & ~adapter->eims_enable_mask);
4049         }
4050
4051         wr32(IGC_IAM, 0);
4052         wr32(IGC_IMC, ~0);
4053         wrfl();
4054
4055         if (adapter->msix_entries) {
4056                 int vector = 0, i;
4057
4058                 synchronize_irq(adapter->msix_entries[vector++].vector);
4059
4060                 for (i = 0; i < adapter->num_q_vectors; i++)
4061                         synchronize_irq(adapter->msix_entries[vector++].vector);
4062         } else {
4063                 synchronize_irq(adapter->pdev->irq);
4064         }
4065 }
4066
4067 void igc_set_flag_queue_pairs(struct igc_adapter *adapter,
4068                               const u32 max_rss_queues)
4069 {
4070         /* Determine if we need to pair queues. */
4071         /* If rss_queues > half of max_rss_queues, pair the queues in
4072          * order to conserve interrupts due to limited supply.
4073          */
4074         if (adapter->rss_queues > (max_rss_queues / 2))
4075                 adapter->flags |= IGC_FLAG_QUEUE_PAIRS;
4076         else
4077                 adapter->flags &= ~IGC_FLAG_QUEUE_PAIRS;
4078 }
4079
4080 unsigned int igc_get_max_rss_queues(struct igc_adapter *adapter)
4081 {
4082         return IGC_MAX_RX_QUEUES;
4083 }
4084
4085 static void igc_init_queue_configuration(struct igc_adapter *adapter)
4086 {
4087         u32 max_rss_queues;
4088
4089         max_rss_queues = igc_get_max_rss_queues(adapter);
4090         adapter->rss_queues = min_t(u32, max_rss_queues, num_online_cpus());
4091
4092         igc_set_flag_queue_pairs(adapter, max_rss_queues);
4093 }
4094
4095 /**
4096  * igc_reset_q_vector - Reset config for interrupt vector
4097  * @adapter: board private structure to initialize
4098  * @v_idx: Index of vector to be reset
4099  *
4100  * If NAPI is enabled it will delete any references to the
4101  * NAPI struct. This is preparation for igc_free_q_vector.
4102  */
4103 static void igc_reset_q_vector(struct igc_adapter *adapter, int v_idx)
4104 {
4105         struct igc_q_vector *q_vector = adapter->q_vector[v_idx];
4106
4107         /* if we're coming from igc_set_interrupt_capability, the vectors are
4108          * not yet allocated
4109          */
4110         if (!q_vector)
4111                 return;
4112
4113         if (q_vector->tx.ring)
4114                 adapter->tx_ring[q_vector->tx.ring->queue_index] = NULL;
4115
4116         if (q_vector->rx.ring)
4117                 adapter->rx_ring[q_vector->rx.ring->queue_index] = NULL;
4118
4119         netif_napi_del(&q_vector->napi);
4120 }
4121
4122 /**
4123  * igc_free_q_vector - Free memory allocated for specific interrupt vector
4124  * @adapter: board private structure to initialize
4125  * @v_idx: Index of vector to be freed
4126  *
4127  * This function frees the memory allocated to the q_vector.
4128  */
4129 static void igc_free_q_vector(struct igc_adapter *adapter, int v_idx)
4130 {
4131         struct igc_q_vector *q_vector = adapter->q_vector[v_idx];
4132
4133         adapter->q_vector[v_idx] = NULL;
4134
4135         /* igc_get_stats64() might access the rings on this vector,
4136          * we must wait a grace period before freeing it.
4137          */
4138         if (q_vector)
4139                 kfree_rcu(q_vector, rcu);
4140 }
4141
4142 /**
4143  * igc_free_q_vectors - Free memory allocated for interrupt vectors
4144  * @adapter: board private structure to initialize
4145  *
4146  * This function frees the memory allocated to the q_vectors.  In addition if
4147  * NAPI is enabled it will delete any references to the NAPI struct prior
4148  * to freeing the q_vector.
4149  */
4150 static void igc_free_q_vectors(struct igc_adapter *adapter)
4151 {
4152         int v_idx = adapter->num_q_vectors;
4153
4154         adapter->num_tx_queues = 0;
4155         adapter->num_rx_queues = 0;
4156         adapter->num_q_vectors = 0;
4157
4158         while (v_idx--) {
4159                 igc_reset_q_vector(adapter, v_idx);
4160                 igc_free_q_vector(adapter, v_idx);
4161         }
4162 }
4163
4164 /**
4165  * igc_update_itr - update the dynamic ITR value based on statistics
4166  * @q_vector: pointer to q_vector
4167  * @ring_container: ring info to update the itr for
4168  *
4169  * Stores a new ITR value based on packets and byte
4170  * counts during the last interrupt.  The advantage of per interrupt
4171  * computation is faster updates and more accurate ITR for the current
4172  * traffic pattern.  Constants in this function were computed
4173  * based on theoretical maximum wire speed and thresholds were set based
4174  * on testing data as well as attempting to minimize response time
4175  * while increasing bulk throughput.
4176  * NOTE: These calculations are only valid when operating in a single-
4177  * queue environment.
4178  */
4179 static void igc_update_itr(struct igc_q_vector *q_vector,
4180                            struct igc_ring_container *ring_container)
4181 {
4182         unsigned int packets = ring_container->total_packets;
4183         unsigned int bytes = ring_container->total_bytes;
4184         u8 itrval = ring_container->itr;
4185
4186         /* no packets, exit with status unchanged */
4187         if (packets == 0)
4188                 return;
4189
4190         switch (itrval) {
4191         case lowest_latency:
4192                 /* handle TSO and jumbo frames */
4193                 if (bytes / packets > 8000)
4194                         itrval = bulk_latency;
4195                 else if ((packets < 5) && (bytes > 512))
4196                         itrval = low_latency;
4197                 break;
4198         case low_latency:  /* 50 usec aka 20000 ints/s */
4199                 if (bytes > 10000) {
4200                         /* this if handles the TSO accounting */
4201                         if (bytes / packets > 8000)
4202                                 itrval = bulk_latency;
4203                         else if ((packets < 10) || ((bytes / packets) > 1200))
4204                                 itrval = bulk_latency;
4205                         else if ((packets > 35))
4206                                 itrval = lowest_latency;
4207                 } else if (bytes / packets > 2000) {
4208                         itrval = bulk_latency;
4209                 } else if (packets <= 2 && bytes < 512) {
4210                         itrval = lowest_latency;
4211                 }
4212                 break;
4213         case bulk_latency: /* 250 usec aka 4000 ints/s */
4214                 if (bytes > 25000) {
4215                         if (packets > 35)
4216                                 itrval = low_latency;
4217                 } else if (bytes < 1500) {
4218                         itrval = low_latency;
4219                 }
4220                 break;
4221         }
4222
4223         /* clear work counters since we have the values we need */
4224         ring_container->total_bytes = 0;
4225         ring_container->total_packets = 0;
4226
4227         /* write updated itr to ring container */
4228         ring_container->itr = itrval;
4229 }
4230
4231 static void igc_set_itr(struct igc_q_vector *q_vector)
4232 {
4233         struct igc_adapter *adapter = q_vector->adapter;
4234         u32 new_itr = q_vector->itr_val;
4235         u8 current_itr = 0;
4236
4237         /* for non-gigabit speeds, just fix the interrupt rate at 4000 */
4238         switch (adapter->link_speed) {
4239         case SPEED_10:
4240         case SPEED_100:
4241                 current_itr = 0;
4242                 new_itr = IGC_4K_ITR;
4243                 goto set_itr_now;
4244         default:
4245                 break;
4246         }
4247
4248         igc_update_itr(q_vector, &q_vector->tx);
4249         igc_update_itr(q_vector, &q_vector->rx);
4250
4251         current_itr = max(q_vector->rx.itr, q_vector->tx.itr);
4252
4253         /* conservative mode (itr 3) eliminates the lowest_latency setting */
4254         if (current_itr == lowest_latency &&
4255             ((q_vector->rx.ring && adapter->rx_itr_setting == 3) ||
4256             (!q_vector->rx.ring && adapter->tx_itr_setting == 3)))
4257                 current_itr = low_latency;
4258
4259         switch (current_itr) {
4260         /* counts and packets in update_itr are dependent on these numbers */
4261         case lowest_latency:
4262                 new_itr = IGC_70K_ITR; /* 70,000 ints/sec */
4263                 break;
4264         case low_latency:
4265                 new_itr = IGC_20K_ITR; /* 20,000 ints/sec */
4266                 break;
4267         case bulk_latency:
4268                 new_itr = IGC_4K_ITR;  /* 4,000 ints/sec */
4269                 break;
4270         default:
4271                 break;
4272         }
4273
4274 set_itr_now:
4275         if (new_itr != q_vector->itr_val) {
4276                 /* this attempts to bias the interrupt rate towards Bulk
4277                  * by adding intermediate steps when interrupt rate is
4278                  * increasing
4279                  */
4280                 new_itr = new_itr > q_vector->itr_val ?
4281                           max((new_itr * q_vector->itr_val) /
4282                           (new_itr + (q_vector->itr_val >> 2)),
4283                           new_itr) : new_itr;
4284                 /* Don't write the value here; it resets the adapter's
4285                  * internal timer, and causes us to delay far longer than
4286                  * we should between interrupts.  Instead, we write the ITR
4287                  * value at the beginning of the next interrupt so the timing
4288                  * ends up being correct.
4289                  */
4290                 q_vector->itr_val = new_itr;
4291                 q_vector->set_itr = 1;
4292         }
4293 }
4294
4295 static void igc_reset_interrupt_capability(struct igc_adapter *adapter)
4296 {
4297         int v_idx = adapter->num_q_vectors;
4298
4299         if (adapter->msix_entries) {
4300                 pci_disable_msix(adapter->pdev);
4301                 kfree(adapter->msix_entries);
4302                 adapter->msix_entries = NULL;
4303         } else if (adapter->flags & IGC_FLAG_HAS_MSI) {
4304                 pci_disable_msi(adapter->pdev);
4305         }
4306
4307         while (v_idx--)
4308                 igc_reset_q_vector(adapter, v_idx);
4309 }
4310
4311 /**
4312  * igc_set_interrupt_capability - set MSI or MSI-X if supported
4313  * @adapter: Pointer to adapter structure
4314  * @msix: boolean value for MSI-X capability
4315  *
4316  * Attempt to configure interrupts using the best available
4317  * capabilities of the hardware and kernel.
4318  */
4319 static void igc_set_interrupt_capability(struct igc_adapter *adapter,
4320                                          bool msix)
4321 {
4322         int numvecs, i;
4323         int err;
4324
4325         if (!msix)
4326                 goto msi_only;
4327         adapter->flags |= IGC_FLAG_HAS_MSIX;
4328
4329         /* Number of supported queues. */
4330         adapter->num_rx_queues = adapter->rss_queues;
4331
4332         adapter->num_tx_queues = adapter->rss_queues;
4333
4334         /* start with one vector for every Rx queue */
4335         numvecs = adapter->num_rx_queues;
4336
4337         /* if Tx handler is separate add 1 for every Tx queue */
4338         if (!(adapter->flags & IGC_FLAG_QUEUE_PAIRS))
4339                 numvecs += adapter->num_tx_queues;
4340
4341         /* store the number of vectors reserved for queues */
4342         adapter->num_q_vectors = numvecs;
4343
4344         /* add 1 vector for link status interrupts */
4345         numvecs++;
4346
4347         adapter->msix_entries = kcalloc(numvecs, sizeof(struct msix_entry),
4348                                         GFP_KERNEL);
4349
4350         if (!adapter->msix_entries)
4351                 return;
4352
4353         /* populate entry values */
4354         for (i = 0; i < numvecs; i++)
4355                 adapter->msix_entries[i].entry = i;
4356
4357         err = pci_enable_msix_range(adapter->pdev,
4358                                     adapter->msix_entries,
4359                                     numvecs,
4360                                     numvecs);
4361         if (err > 0)
4362                 return;
4363
4364         kfree(adapter->msix_entries);
4365         adapter->msix_entries = NULL;
4366
4367         igc_reset_interrupt_capability(adapter);
4368
4369 msi_only:
4370         adapter->flags &= ~IGC_FLAG_HAS_MSIX;
4371
4372         adapter->rss_queues = 1;
4373         adapter->flags |= IGC_FLAG_QUEUE_PAIRS;
4374         adapter->num_rx_queues = 1;
4375         adapter->num_tx_queues = 1;
4376         adapter->num_q_vectors = 1;
4377         if (!pci_enable_msi(adapter->pdev))
4378                 adapter->flags |= IGC_FLAG_HAS_MSI;
4379 }
4380
4381 /**
4382  * igc_update_ring_itr - update the dynamic ITR value based on packet size
4383  * @q_vector: pointer to q_vector
4384  *
4385  * Stores a new ITR value based on strictly on packet size.  This
4386  * algorithm is less sophisticated than that used in igc_update_itr,
4387  * due to the difficulty of synchronizing statistics across multiple
4388  * receive rings.  The divisors and thresholds used by this function
4389  * were determined based on theoretical maximum wire speed and testing
4390  * data, in order to minimize response time while increasing bulk
4391  * throughput.
4392  * NOTE: This function is called only when operating in a multiqueue
4393  * receive environment.
4394  */
4395 static void igc_update_ring_itr(struct igc_q_vector *q_vector)
4396 {
4397         struct igc_adapter *adapter = q_vector->adapter;
4398         int new_val = q_vector->itr_val;
4399         int avg_wire_size = 0;
4400         unsigned int packets;
4401
4402         /* For non-gigabit speeds, just fix the interrupt rate at 4000
4403          * ints/sec - ITR timer value of 120 ticks.
4404          */
4405         switch (adapter->link_speed) {
4406         case SPEED_10:
4407         case SPEED_100:
4408                 new_val = IGC_4K_ITR;
4409                 goto set_itr_val;
4410         default:
4411                 break;
4412         }
4413
4414         packets = q_vector->rx.total_packets;
4415         if (packets)
4416                 avg_wire_size = q_vector->rx.total_bytes / packets;
4417
4418         packets = q_vector->tx.total_packets;
4419         if (packets)
4420                 avg_wire_size = max_t(u32, avg_wire_size,
4421                                       q_vector->tx.total_bytes / packets);
4422
4423         /* if avg_wire_size isn't set no work was done */
4424         if (!avg_wire_size)
4425                 goto clear_counts;
4426
4427         /* Add 24 bytes to size to account for CRC, preamble, and gap */
4428         avg_wire_size += 24;
4429
4430         /* Don't starve jumbo frames */
4431         avg_wire_size = min(avg_wire_size, 3000);
4432
4433         /* Give a little boost to mid-size frames */
4434         if (avg_wire_size > 300 && avg_wire_size < 1200)
4435                 new_val = avg_wire_size / 3;
4436         else
4437                 new_val = avg_wire_size / 2;
4438
4439         /* conservative mode (itr 3) eliminates the lowest_latency setting */
4440         if (new_val < IGC_20K_ITR &&
4441             ((q_vector->rx.ring && adapter->rx_itr_setting == 3) ||
4442             (!q_vector->rx.ring && adapter->tx_itr_setting == 3)))
4443                 new_val = IGC_20K_ITR;
4444
4445 set_itr_val:
4446         if (new_val != q_vector->itr_val) {
4447                 q_vector->itr_val = new_val;
4448                 q_vector->set_itr = 1;
4449         }
4450 clear_counts:
4451         q_vector->rx.total_bytes = 0;
4452         q_vector->rx.total_packets = 0;
4453         q_vector->tx.total_bytes = 0;
4454         q_vector->tx.total_packets = 0;
4455 }
4456
4457 static void igc_ring_irq_enable(struct igc_q_vector *q_vector)
4458 {
4459         struct igc_adapter *adapter = q_vector->adapter;
4460         struct igc_hw *hw = &adapter->hw;
4461
4462         if ((q_vector->rx.ring && (adapter->rx_itr_setting & 3)) ||
4463             (!q_vector->rx.ring && (adapter->tx_itr_setting & 3))) {
4464                 if (adapter->num_q_vectors == 1)
4465                         igc_set_itr(q_vector);
4466                 else
4467                         igc_update_ring_itr(q_vector);
4468         }
4469
4470         if (!test_bit(__IGC_DOWN, &adapter->state)) {
4471                 if (adapter->msix_entries)
4472                         wr32(IGC_EIMS, q_vector->eims_value);
4473                 else
4474                         igc_irq_enable(adapter);
4475         }
4476 }
4477
4478 static void igc_add_ring(struct igc_ring *ring,
4479                          struct igc_ring_container *head)
4480 {
4481         head->ring = ring;
4482         head->count++;
4483 }
4484
4485 /**
4486  * igc_cache_ring_register - Descriptor ring to register mapping
4487  * @adapter: board private structure to initialize
4488  *
4489  * Once we know the feature-set enabled for the device, we'll cache
4490  * the register offset the descriptor ring is assigned to.
4491  */
4492 static void igc_cache_ring_register(struct igc_adapter *adapter)
4493 {
4494         int i = 0, j = 0;
4495
4496         switch (adapter->hw.mac.type) {
4497         case igc_i225:
4498         default:
4499                 for (; i < adapter->num_rx_queues; i++)
4500                         adapter->rx_ring[i]->reg_idx = i;
4501                 for (; j < adapter->num_tx_queues; j++)
4502                         adapter->tx_ring[j]->reg_idx = j;
4503                 break;
4504         }
4505 }
4506
4507 /**
4508  * igc_poll - NAPI Rx polling callback
4509  * @napi: napi polling structure
4510  * @budget: count of how many packets we should handle
4511  */
4512 static int igc_poll(struct napi_struct *napi, int budget)
4513 {
4514         struct igc_q_vector *q_vector = container_of(napi,
4515                                                      struct igc_q_vector,
4516                                                      napi);
4517         struct igc_ring *rx_ring = q_vector->rx.ring;
4518         bool clean_complete = true;
4519         int work_done = 0;
4520
4521         if (q_vector->tx.ring)
4522                 clean_complete = igc_clean_tx_irq(q_vector, budget);
4523
4524         if (rx_ring) {
4525                 int cleaned = rx_ring->xsk_pool ?
4526                               igc_clean_rx_irq_zc(q_vector, budget) :
4527                               igc_clean_rx_irq(q_vector, budget);
4528
4529                 work_done += cleaned;
4530                 if (cleaned >= budget)
4531                         clean_complete = false;
4532         }
4533
4534         /* If all work not completed, return budget and keep polling */
4535         if (!clean_complete)
4536                 return budget;
4537
4538         /* Exit the polling mode, but don't re-enable interrupts if stack might
4539          * poll us due to busy-polling
4540          */
4541         if (likely(napi_complete_done(napi, work_done)))
4542                 igc_ring_irq_enable(q_vector);
4543
4544         return min(work_done, budget - 1);
4545 }
4546
4547 /**
4548  * igc_alloc_q_vector - Allocate memory for a single interrupt vector
4549  * @adapter: board private structure to initialize
4550  * @v_count: q_vectors allocated on adapter, used for ring interleaving
4551  * @v_idx: index of vector in adapter struct
4552  * @txr_count: total number of Tx rings to allocate
4553  * @txr_idx: index of first Tx ring to allocate
4554  * @rxr_count: total number of Rx rings to allocate
4555  * @rxr_idx: index of first Rx ring to allocate
4556  *
4557  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
4558  */
4559 static int igc_alloc_q_vector(struct igc_adapter *adapter,
4560                               unsigned int v_count, unsigned int v_idx,
4561                               unsigned int txr_count, unsigned int txr_idx,
4562                               unsigned int rxr_count, unsigned int rxr_idx)
4563 {
4564         struct igc_q_vector *q_vector;
4565         struct igc_ring *ring;
4566         int ring_count;
4567
4568         /* igc only supports 1 Tx and/or 1 Rx queue per vector */
4569         if (txr_count > 1 || rxr_count > 1)
4570                 return -ENOMEM;
4571
4572         ring_count = txr_count + rxr_count;
4573
4574         /* allocate q_vector and rings */
4575         q_vector = adapter->q_vector[v_idx];
4576         if (!q_vector)
4577                 q_vector = kzalloc(struct_size(q_vector, ring, ring_count),
4578                                    GFP_KERNEL);
4579         else
4580                 memset(q_vector, 0, struct_size(q_vector, ring, ring_count));
4581         if (!q_vector)
4582                 return -ENOMEM;
4583
4584         /* initialize NAPI */
4585         netif_napi_add(adapter->netdev, &q_vector->napi, igc_poll);
4586
4587         /* tie q_vector and adapter together */
4588         adapter->q_vector[v_idx] = q_vector;
4589         q_vector->adapter = adapter;
4590
4591         /* initialize work limits */
4592         q_vector->tx.work_limit = adapter->tx_work_limit;
4593
4594         /* initialize ITR configuration */
4595         q_vector->itr_register = adapter->io_addr + IGC_EITR(0);
4596         q_vector->itr_val = IGC_START_ITR;
4597
4598         /* initialize pointer to rings */
4599         ring = q_vector->ring;
4600
4601         /* initialize ITR */
4602         if (rxr_count) {
4603                 /* rx or rx/tx vector */
4604                 if (!adapter->rx_itr_setting || adapter->rx_itr_setting > 3)
4605                         q_vector->itr_val = adapter->rx_itr_setting;
4606         } else {
4607                 /* tx only vector */
4608                 if (!adapter->tx_itr_setting || adapter->tx_itr_setting > 3)
4609                         q_vector->itr_val = adapter->tx_itr_setting;
4610         }
4611
4612         if (txr_count) {
4613                 /* assign generic ring traits */
4614                 ring->dev = &adapter->pdev->dev;
4615                 ring->netdev = adapter->netdev;
4616
4617                 /* configure backlink on ring */
4618                 ring->q_vector = q_vector;
4619
4620                 /* update q_vector Tx values */
4621                 igc_add_ring(ring, &q_vector->tx);
4622
4623                 /* apply Tx specific ring traits */
4624                 ring->count = adapter->tx_ring_count;
4625                 ring->queue_index = txr_idx;
4626
4627                 /* assign ring to adapter */
4628                 adapter->tx_ring[txr_idx] = ring;
4629
4630                 /* push pointer to next ring */
4631                 ring++;
4632         }
4633
4634         if (rxr_count) {
4635                 /* assign generic ring traits */
4636                 ring->dev = &adapter->pdev->dev;
4637                 ring->netdev = adapter->netdev;
4638
4639                 /* configure backlink on ring */
4640                 ring->q_vector = q_vector;
4641
4642                 /* update q_vector Rx values */
4643                 igc_add_ring(ring, &q_vector->rx);
4644
4645                 /* apply Rx specific ring traits */
4646                 ring->count = adapter->rx_ring_count;
4647                 ring->queue_index = rxr_idx;
4648
4649                 /* assign ring to adapter */
4650                 adapter->rx_ring[rxr_idx] = ring;
4651         }
4652
4653         return 0;
4654 }
4655
4656 /**
4657  * igc_alloc_q_vectors - Allocate memory for interrupt vectors
4658  * @adapter: board private structure to initialize
4659  *
4660  * We allocate one q_vector per queue interrupt.  If allocation fails we
4661  * return -ENOMEM.
4662  */
4663 static int igc_alloc_q_vectors(struct igc_adapter *adapter)
4664 {
4665         int rxr_remaining = adapter->num_rx_queues;
4666         int txr_remaining = adapter->num_tx_queues;
4667         int rxr_idx = 0, txr_idx = 0, v_idx = 0;
4668         int q_vectors = adapter->num_q_vectors;
4669         int err;
4670
4671         if (q_vectors >= (rxr_remaining + txr_remaining)) {
4672                 for (; rxr_remaining; v_idx++) {
4673                         err = igc_alloc_q_vector(adapter, q_vectors, v_idx,
4674                                                  0, 0, 1, rxr_idx);
4675
4676                         if (err)
4677                                 goto err_out;
4678
4679                         /* update counts and index */
4680                         rxr_remaining--;
4681                         rxr_idx++;
4682                 }
4683         }
4684
4685         for (; v_idx < q_vectors; v_idx++) {
4686                 int rqpv = DIV_ROUND_UP(rxr_remaining, q_vectors - v_idx);
4687                 int tqpv = DIV_ROUND_UP(txr_remaining, q_vectors - v_idx);
4688
4689                 err = igc_alloc_q_vector(adapter, q_vectors, v_idx,
4690                                          tqpv, txr_idx, rqpv, rxr_idx);
4691
4692                 if (err)
4693                         goto err_out;
4694
4695                 /* update counts and index */
4696                 rxr_remaining -= rqpv;
4697                 txr_remaining -= tqpv;
4698                 rxr_idx++;
4699                 txr_idx++;
4700         }
4701
4702         return 0;
4703
4704 err_out:
4705         adapter->num_tx_queues = 0;
4706         adapter->num_rx_queues = 0;
4707         adapter->num_q_vectors = 0;
4708
4709         while (v_idx--)
4710                 igc_free_q_vector(adapter, v_idx);
4711
4712         return -ENOMEM;
4713 }
4714
4715 /**
4716  * igc_init_interrupt_scheme - initialize interrupts, allocate queues/vectors
4717  * @adapter: Pointer to adapter structure
4718  * @msix: boolean for MSI-X capability
4719  *
4720  * This function initializes the interrupts and allocates all of the queues.
4721  */
4722 static int igc_init_interrupt_scheme(struct igc_adapter *adapter, bool msix)
4723 {
4724         struct net_device *dev = adapter->netdev;
4725         int err = 0;
4726
4727         igc_set_interrupt_capability(adapter, msix);
4728
4729         err = igc_alloc_q_vectors(adapter);
4730         if (err) {
4731                 netdev_err(dev, "Unable to allocate memory for vectors\n");
4732                 goto err_alloc_q_vectors;
4733         }
4734
4735         igc_cache_ring_register(adapter);
4736
4737         return 0;
4738
4739 err_alloc_q_vectors:
4740         igc_reset_interrupt_capability(adapter);
4741         return err;
4742 }
4743
4744 /**
4745  * igc_sw_init - Initialize general software structures (struct igc_adapter)
4746  * @adapter: board private structure to initialize
4747  *
4748  * igc_sw_init initializes the Adapter private data structure.
4749  * Fields are initialized based on PCI device information and
4750  * OS network device settings (MTU size).
4751  */
4752 static int igc_sw_init(struct igc_adapter *adapter)
4753 {
4754         struct net_device *netdev = adapter->netdev;
4755         struct pci_dev *pdev = adapter->pdev;
4756         struct igc_hw *hw = &adapter->hw;
4757
4758         pci_read_config_word(pdev, PCI_COMMAND, &hw->bus.pci_cmd_word);
4759
4760         /* set default ring sizes */
4761         adapter->tx_ring_count = IGC_DEFAULT_TXD;
4762         adapter->rx_ring_count = IGC_DEFAULT_RXD;
4763
4764         /* set default ITR values */
4765         adapter->rx_itr_setting = IGC_DEFAULT_ITR;
4766         adapter->tx_itr_setting = IGC_DEFAULT_ITR;
4767
4768         /* set default work limits */
4769         adapter->tx_work_limit = IGC_DEFAULT_TX_WORK;
4770
4771         /* adjust max frame to be at least the size of a standard frame */
4772         adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN +
4773                                 VLAN_HLEN;
4774         adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
4775
4776         mutex_init(&adapter->nfc_rule_lock);
4777         INIT_LIST_HEAD(&adapter->nfc_rule_list);
4778         adapter->nfc_rule_count = 0;
4779
4780         spin_lock_init(&adapter->stats64_lock);
4781         /* Assume MSI-X interrupts, will be checked during IRQ allocation */
4782         adapter->flags |= IGC_FLAG_HAS_MSIX;
4783
4784         igc_init_queue_configuration(adapter);
4785
4786         /* This call may decrease the number of queues */
4787         if (igc_init_interrupt_scheme(adapter, true)) {
4788                 netdev_err(netdev, "Unable to allocate memory for queues\n");
4789                 return -ENOMEM;
4790         }
4791
4792         /* Explicitly disable IRQ since the NIC can be in any state. */
4793         igc_irq_disable(adapter);
4794
4795         set_bit(__IGC_DOWN, &adapter->state);
4796
4797         return 0;
4798 }
4799
4800 /**
4801  * igc_up - Open the interface and prepare it to handle traffic
4802  * @adapter: board private structure
4803  */
4804 void igc_up(struct igc_adapter *adapter)
4805 {
4806         struct igc_hw *hw = &adapter->hw;
4807         int i = 0;
4808
4809         /* hardware has been reset, we need to reload some things */
4810         igc_configure(adapter);
4811
4812         clear_bit(__IGC_DOWN, &adapter->state);
4813
4814         for (i = 0; i < adapter->num_q_vectors; i++)
4815                 napi_enable(&adapter->q_vector[i]->napi);
4816
4817         if (adapter->msix_entries)
4818                 igc_configure_msix(adapter);
4819         else
4820                 igc_assign_vector(adapter->q_vector[0], 0);
4821
4822         /* Clear any pending interrupts. */
4823         rd32(IGC_ICR);
4824         igc_irq_enable(adapter);
4825
4826         netif_tx_start_all_queues(adapter->netdev);
4827
4828         /* start the watchdog. */
4829         hw->mac.get_link_status = true;
4830         schedule_work(&adapter->watchdog_task);
4831 }
4832
4833 /**
4834  * igc_update_stats - Update the board statistics counters
4835  * @adapter: board private structure
4836  */
4837 void igc_update_stats(struct igc_adapter *adapter)
4838 {
4839         struct rtnl_link_stats64 *net_stats = &adapter->stats64;
4840         struct pci_dev *pdev = adapter->pdev;
4841         struct igc_hw *hw = &adapter->hw;
4842         u64 _bytes, _packets;
4843         u64 bytes, packets;
4844         unsigned int start;
4845         u32 mpc;
4846         int i;
4847
4848         /* Prevent stats update while adapter is being reset, or if the pci
4849          * connection is down.
4850          */
4851         if (adapter->link_speed == 0)
4852                 return;
4853         if (pci_channel_offline(pdev))
4854                 return;
4855
4856         packets = 0;
4857         bytes = 0;
4858
4859         rcu_read_lock();
4860         for (i = 0; i < adapter->num_rx_queues; i++) {
4861                 struct igc_ring *ring = adapter->rx_ring[i];
4862                 u32 rqdpc = rd32(IGC_RQDPC(i));
4863
4864                 if (hw->mac.type >= igc_i225)
4865                         wr32(IGC_RQDPC(i), 0);
4866
4867                 if (rqdpc) {
4868                         ring->rx_stats.drops += rqdpc;
4869                         net_stats->rx_fifo_errors += rqdpc;
4870                 }
4871
4872                 do {
4873                         start = u64_stats_fetch_begin(&ring->rx_syncp);
4874                         _bytes = ring->rx_stats.bytes;
4875                         _packets = ring->rx_stats.packets;
4876                 } while (u64_stats_fetch_retry(&ring->rx_syncp, start));
4877                 bytes += _bytes;
4878                 packets += _packets;
4879         }
4880
4881         net_stats->rx_bytes = bytes;
4882         net_stats->rx_packets = packets;
4883
4884         packets = 0;
4885         bytes = 0;
4886         for (i = 0; i < adapter->num_tx_queues; i++) {
4887                 struct igc_ring *ring = adapter->tx_ring[i];
4888
4889                 do {
4890                         start = u64_stats_fetch_begin(&ring->tx_syncp);
4891                         _bytes = ring->tx_stats.bytes;
4892                         _packets = ring->tx_stats.packets;
4893                 } while (u64_stats_fetch_retry(&ring->tx_syncp, start));
4894                 bytes += _bytes;
4895                 packets += _packets;
4896         }
4897         net_stats->tx_bytes = bytes;
4898         net_stats->tx_packets = packets;
4899         rcu_read_unlock();
4900
4901         /* read stats registers */
4902         adapter->stats.crcerrs += rd32(IGC_CRCERRS);
4903         adapter->stats.gprc += rd32(IGC_GPRC);
4904         adapter->stats.gorc += rd32(IGC_GORCL);
4905         rd32(IGC_GORCH); /* clear GORCL */
4906         adapter->stats.bprc += rd32(IGC_BPRC);
4907         adapter->stats.mprc += rd32(IGC_MPRC);
4908         adapter->stats.roc += rd32(IGC_ROC);
4909
4910         adapter->stats.prc64 += rd32(IGC_PRC64);
4911         adapter->stats.prc127 += rd32(IGC_PRC127);
4912         adapter->stats.prc255 += rd32(IGC_PRC255);
4913         adapter->stats.prc511 += rd32(IGC_PRC511);
4914         adapter->stats.prc1023 += rd32(IGC_PRC1023);
4915         adapter->stats.prc1522 += rd32(IGC_PRC1522);
4916         adapter->stats.tlpic += rd32(IGC_TLPIC);
4917         adapter->stats.rlpic += rd32(IGC_RLPIC);
4918         adapter->stats.hgptc += rd32(IGC_HGPTC);
4919
4920         mpc = rd32(IGC_MPC);
4921         adapter->stats.mpc += mpc;
4922         net_stats->rx_fifo_errors += mpc;
4923         adapter->stats.scc += rd32(IGC_SCC);
4924         adapter->stats.ecol += rd32(IGC_ECOL);
4925         adapter->stats.mcc += rd32(IGC_MCC);
4926         adapter->stats.latecol += rd32(IGC_LATECOL);
4927         adapter->stats.dc += rd32(IGC_DC);
4928         adapter->stats.rlec += rd32(IGC_RLEC);
4929         adapter->stats.xonrxc += rd32(IGC_XONRXC);
4930         adapter->stats.xontxc += rd32(IGC_XONTXC);
4931         adapter->stats.xoffrxc += rd32(IGC_XOFFRXC);
4932         adapter->stats.xofftxc += rd32(IGC_XOFFTXC);
4933         adapter->stats.fcruc += rd32(IGC_FCRUC);
4934         adapter->stats.gptc += rd32(IGC_GPTC);
4935         adapter->stats.gotc += rd32(IGC_GOTCL);
4936         rd32(IGC_GOTCH); /* clear GOTCL */
4937         adapter->stats.rnbc += rd32(IGC_RNBC);
4938         adapter->stats.ruc += rd32(IGC_RUC);
4939         adapter->stats.rfc += rd32(IGC_RFC);
4940         adapter->stats.rjc += rd32(IGC_RJC);
4941         adapter->stats.tor += rd32(IGC_TORH);
4942         adapter->stats.tot += rd32(IGC_TOTH);
4943         adapter->stats.tpr += rd32(IGC_TPR);
4944
4945         adapter->stats.ptc64 += rd32(IGC_PTC64);
4946         adapter->stats.ptc127 += rd32(IGC_PTC127);
4947         adapter->stats.ptc255 += rd32(IGC_PTC255);
4948         adapter->stats.ptc511 += rd32(IGC_PTC511);
4949         adapter->stats.ptc1023 += rd32(IGC_PTC1023);
4950         adapter->stats.ptc1522 += rd32(IGC_PTC1522);
4951
4952         adapter->stats.mptc += rd32(IGC_MPTC);
4953         adapter->stats.bptc += rd32(IGC_BPTC);
4954
4955         adapter->stats.tpt += rd32(IGC_TPT);
4956         adapter->stats.colc += rd32(IGC_COLC);
4957         adapter->stats.colc += rd32(IGC_RERC);
4958
4959         adapter->stats.algnerrc += rd32(IGC_ALGNERRC);
4960
4961         adapter->stats.tsctc += rd32(IGC_TSCTC);
4962
4963         adapter->stats.iac += rd32(IGC_IAC);
4964
4965         /* Fill out the OS statistics structure */
4966         net_stats->multicast = adapter->stats.mprc;
4967         net_stats->collisions = adapter->stats.colc;
4968
4969         /* Rx Errors */
4970
4971         /* RLEC on some newer hardware can be incorrect so build
4972          * our own version based on RUC and ROC
4973          */
4974         net_stats->rx_errors = adapter->stats.rxerrc +
4975                 adapter->stats.crcerrs + adapter->stats.algnerrc +
4976                 adapter->stats.ruc + adapter->stats.roc +
4977                 adapter->stats.cexterr;
4978         net_stats->rx_length_errors = adapter->stats.ruc +
4979                                       adapter->stats.roc;
4980         net_stats->rx_crc_errors = adapter->stats.crcerrs;
4981         net_stats->rx_frame_errors = adapter->stats.algnerrc;
4982         net_stats->rx_missed_errors = adapter->stats.mpc;
4983
4984         /* Tx Errors */
4985         net_stats->tx_errors = adapter->stats.ecol +
4986                                adapter->stats.latecol;
4987         net_stats->tx_aborted_errors = adapter->stats.ecol;
4988         net_stats->tx_window_errors = adapter->stats.latecol;
4989         net_stats->tx_carrier_errors = adapter->stats.tncrs;
4990
4991         /* Tx Dropped */
4992         net_stats->tx_dropped = adapter->stats.txdrop;
4993
4994         /* Management Stats */
4995         adapter->stats.mgptc += rd32(IGC_MGTPTC);
4996         adapter->stats.mgprc += rd32(IGC_MGTPRC);
4997         adapter->stats.mgpdc += rd32(IGC_MGTPDC);
4998 }
4999
5000 /**
5001  * igc_down - Close the interface
5002  * @adapter: board private structure
5003  */
5004 void igc_down(struct igc_adapter *adapter)
5005 {
5006         struct net_device *netdev = adapter->netdev;
5007         struct igc_hw *hw = &adapter->hw;
5008         u32 tctl, rctl;
5009         int i = 0;
5010
5011         set_bit(__IGC_DOWN, &adapter->state);
5012
5013         igc_ptp_suspend(adapter);
5014
5015         if (pci_device_is_present(adapter->pdev)) {
5016                 /* disable receives in the hardware */
5017                 rctl = rd32(IGC_RCTL);
5018                 wr32(IGC_RCTL, rctl & ~IGC_RCTL_EN);
5019                 /* flush and sleep below */
5020         }
5021         /* set trans_start so we don't get spurious watchdogs during reset */
5022         netif_trans_update(netdev);
5023
5024         netif_carrier_off(netdev);
5025         netif_tx_stop_all_queues(netdev);
5026
5027         if (pci_device_is_present(adapter->pdev)) {
5028                 /* disable transmits in the hardware */
5029                 tctl = rd32(IGC_TCTL);
5030                 tctl &= ~IGC_TCTL_EN;
5031                 wr32(IGC_TCTL, tctl);
5032                 /* flush both disables and wait for them to finish */
5033                 wrfl();
5034                 usleep_range(10000, 20000);
5035
5036                 igc_irq_disable(adapter);
5037         }
5038
5039         adapter->flags &= ~IGC_FLAG_NEED_LINK_UPDATE;
5040
5041         for (i = 0; i < adapter->num_q_vectors; i++) {
5042                 if (adapter->q_vector[i]) {
5043                         napi_synchronize(&adapter->q_vector[i]->napi);
5044                         napi_disable(&adapter->q_vector[i]->napi);
5045                 }
5046         }
5047
5048         del_timer_sync(&adapter->watchdog_timer);
5049         del_timer_sync(&adapter->phy_info_timer);
5050
5051         /* record the stats before reset*/
5052         spin_lock(&adapter->stats64_lock);
5053         igc_update_stats(adapter);
5054         spin_unlock(&adapter->stats64_lock);
5055
5056         adapter->link_speed = 0;
5057         adapter->link_duplex = 0;
5058
5059         if (!pci_channel_offline(adapter->pdev))
5060                 igc_reset(adapter);
5061
5062         /* clear VLAN promisc flag so VFTA will be updated if necessary */
5063         adapter->flags &= ~IGC_FLAG_VLAN_PROMISC;
5064
5065         igc_clean_all_tx_rings(adapter);
5066         igc_clean_all_rx_rings(adapter);
5067 }
5068
5069 void igc_reinit_locked(struct igc_adapter *adapter)
5070 {
5071         while (test_and_set_bit(__IGC_RESETTING, &adapter->state))
5072                 usleep_range(1000, 2000);
5073         igc_down(adapter);
5074         igc_up(adapter);
5075         clear_bit(__IGC_RESETTING, &adapter->state);
5076 }
5077
5078 static void igc_reset_task(struct work_struct *work)
5079 {
5080         struct igc_adapter *adapter;
5081
5082         adapter = container_of(work, struct igc_adapter, reset_task);
5083
5084         rtnl_lock();
5085         /* If we're already down or resetting, just bail */
5086         if (test_bit(__IGC_DOWN, &adapter->state) ||
5087             test_bit(__IGC_RESETTING, &adapter->state)) {
5088                 rtnl_unlock();
5089                 return;
5090         }
5091
5092         igc_rings_dump(adapter);
5093         igc_regs_dump(adapter);
5094         netdev_err(adapter->netdev, "Reset adapter\n");
5095         igc_reinit_locked(adapter);
5096         rtnl_unlock();
5097 }
5098
5099 /**
5100  * igc_change_mtu - Change the Maximum Transfer Unit
5101  * @netdev: network interface device structure
5102  * @new_mtu: new value for maximum frame size
5103  *
5104  * Returns 0 on success, negative on failure
5105  */
5106 static int igc_change_mtu(struct net_device *netdev, int new_mtu)
5107 {
5108         int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
5109         struct igc_adapter *adapter = netdev_priv(netdev);
5110
5111         if (igc_xdp_is_enabled(adapter) && new_mtu > ETH_DATA_LEN) {
5112                 netdev_dbg(netdev, "Jumbo frames not supported with XDP");
5113                 return -EINVAL;
5114         }
5115
5116         /* adjust max frame to be at least the size of a standard frame */
5117         if (max_frame < (ETH_FRAME_LEN + ETH_FCS_LEN))
5118                 max_frame = ETH_FRAME_LEN + ETH_FCS_LEN;
5119
5120         while (test_and_set_bit(__IGC_RESETTING, &adapter->state))
5121                 usleep_range(1000, 2000);
5122
5123         /* igc_down has a dependency on max_frame_size */
5124         adapter->max_frame_size = max_frame;
5125
5126         if (netif_running(netdev))
5127                 igc_down(adapter);
5128
5129         netdev_dbg(netdev, "changing MTU from %d to %d\n", netdev->mtu, new_mtu);
5130         netdev->mtu = new_mtu;
5131
5132         if (netif_running(netdev))
5133                 igc_up(adapter);
5134         else
5135                 igc_reset(adapter);
5136
5137         clear_bit(__IGC_RESETTING, &adapter->state);
5138
5139         return 0;
5140 }
5141
5142 /**
5143  * igc_tx_timeout - Respond to a Tx Hang
5144  * @netdev: network interface device structure
5145  * @txqueue: queue number that timed out
5146  **/
5147 static void igc_tx_timeout(struct net_device *netdev,
5148                            unsigned int __always_unused txqueue)
5149 {
5150         struct igc_adapter *adapter = netdev_priv(netdev);
5151         struct igc_hw *hw = &adapter->hw;
5152
5153         /* Do the reset outside of interrupt context */
5154         adapter->tx_timeout_count++;
5155         schedule_work(&adapter->reset_task);
5156         wr32(IGC_EICS,
5157              (adapter->eims_enable_mask & ~adapter->eims_other));
5158 }
5159
5160 /**
5161  * igc_get_stats64 - Get System Network Statistics
5162  * @netdev: network interface device structure
5163  * @stats: rtnl_link_stats64 pointer
5164  *
5165  * Returns the address of the device statistics structure.
5166  * The statistics are updated here and also from the timer callback.
5167  */
5168 static void igc_get_stats64(struct net_device *netdev,
5169                             struct rtnl_link_stats64 *stats)
5170 {
5171         struct igc_adapter *adapter = netdev_priv(netdev);
5172
5173         spin_lock(&adapter->stats64_lock);
5174         if (!test_bit(__IGC_RESETTING, &adapter->state))
5175                 igc_update_stats(adapter);
5176         memcpy(stats, &adapter->stats64, sizeof(*stats));
5177         spin_unlock(&adapter->stats64_lock);
5178 }
5179
5180 static netdev_features_t igc_fix_features(struct net_device *netdev,
5181                                           netdev_features_t features)
5182 {
5183         /* Since there is no support for separate Rx/Tx vlan accel
5184          * enable/disable make sure Tx flag is always in same state as Rx.
5185          */
5186         if (features & NETIF_F_HW_VLAN_CTAG_RX)
5187                 features |= NETIF_F_HW_VLAN_CTAG_TX;
5188         else
5189                 features &= ~NETIF_F_HW_VLAN_CTAG_TX;
5190
5191         return features;
5192 }
5193
5194 static int igc_set_features(struct net_device *netdev,
5195                             netdev_features_t features)
5196 {
5197         netdev_features_t changed = netdev->features ^ features;
5198         struct igc_adapter *adapter = netdev_priv(netdev);
5199
5200         if (changed & NETIF_F_HW_VLAN_CTAG_RX)
5201                 igc_vlan_mode(netdev, features);
5202
5203         /* Add VLAN support */
5204         if (!(changed & (NETIF_F_RXALL | NETIF_F_NTUPLE)))
5205                 return 0;
5206
5207         if (!(features & NETIF_F_NTUPLE))
5208                 igc_flush_nfc_rules(adapter);
5209
5210         netdev->features = features;
5211
5212         if (netif_running(netdev))
5213                 igc_reinit_locked(adapter);
5214         else
5215                 igc_reset(adapter);
5216
5217         return 1;
5218 }
5219
5220 static netdev_features_t
5221 igc_features_check(struct sk_buff *skb, struct net_device *dev,
5222                    netdev_features_t features)
5223 {
5224         unsigned int network_hdr_len, mac_hdr_len;
5225
5226         /* Make certain the headers can be described by a context descriptor */
5227         mac_hdr_len = skb_network_header(skb) - skb->data;
5228         if (unlikely(mac_hdr_len > IGC_MAX_MAC_HDR_LEN))
5229                 return features & ~(NETIF_F_HW_CSUM |
5230                                     NETIF_F_SCTP_CRC |
5231                                     NETIF_F_HW_VLAN_CTAG_TX |
5232                                     NETIF_F_TSO |
5233                                     NETIF_F_TSO6);
5234
5235         network_hdr_len = skb_checksum_start(skb) - skb_network_header(skb);
5236         if (unlikely(network_hdr_len >  IGC_MAX_NETWORK_HDR_LEN))
5237                 return features & ~(NETIF_F_HW_CSUM |
5238                                     NETIF_F_SCTP_CRC |
5239                                     NETIF_F_TSO |
5240                                     NETIF_F_TSO6);
5241
5242         /* We can only support IPv4 TSO in tunnels if we can mangle the
5243          * inner IP ID field, so strip TSO if MANGLEID is not supported.
5244          */
5245         if (skb->encapsulation && !(features & NETIF_F_TSO_MANGLEID))
5246                 features &= ~NETIF_F_TSO;
5247
5248         return features;
5249 }
5250
5251 static void igc_tsync_interrupt(struct igc_adapter *adapter)
5252 {
5253         u32 ack, tsauxc, sec, nsec, tsicr;
5254         struct igc_hw *hw = &adapter->hw;
5255         struct ptp_clock_event event;
5256         struct timespec64 ts;
5257
5258         tsicr = rd32(IGC_TSICR);
5259         ack = 0;
5260
5261         if (tsicr & IGC_TSICR_SYS_WRAP) {
5262                 event.type = PTP_CLOCK_PPS;
5263                 if (adapter->ptp_caps.pps)
5264                         ptp_clock_event(adapter->ptp_clock, &event);
5265                 ack |= IGC_TSICR_SYS_WRAP;
5266         }
5267
5268         if (tsicr & IGC_TSICR_TXTS) {
5269                 /* retrieve hardware timestamp */
5270                 igc_ptp_tx_tstamp_event(adapter);
5271                 ack |= IGC_TSICR_TXTS;
5272         }
5273
5274         if (tsicr & IGC_TSICR_TT0) {
5275                 spin_lock(&adapter->tmreg_lock);
5276                 ts = timespec64_add(adapter->perout[0].start,
5277                                     adapter->perout[0].period);
5278                 wr32(IGC_TRGTTIML0, ts.tv_nsec | IGC_TT_IO_TIMER_SEL_SYSTIM0);
5279                 wr32(IGC_TRGTTIMH0, (u32)ts.tv_sec);
5280                 tsauxc = rd32(IGC_TSAUXC);
5281                 tsauxc |= IGC_TSAUXC_EN_TT0;
5282                 wr32(IGC_TSAUXC, tsauxc);
5283                 adapter->perout[0].start = ts;
5284                 spin_unlock(&adapter->tmreg_lock);
5285                 ack |= IGC_TSICR_TT0;
5286         }
5287
5288         if (tsicr & IGC_TSICR_TT1) {
5289                 spin_lock(&adapter->tmreg_lock);
5290                 ts = timespec64_add(adapter->perout[1].start,
5291                                     adapter->perout[1].period);
5292                 wr32(IGC_TRGTTIML1, ts.tv_nsec | IGC_TT_IO_TIMER_SEL_SYSTIM0);
5293                 wr32(IGC_TRGTTIMH1, (u32)ts.tv_sec);
5294                 tsauxc = rd32(IGC_TSAUXC);
5295                 tsauxc |= IGC_TSAUXC_EN_TT1;
5296                 wr32(IGC_TSAUXC, tsauxc);
5297                 adapter->perout[1].start = ts;
5298                 spin_unlock(&adapter->tmreg_lock);
5299                 ack |= IGC_TSICR_TT1;
5300         }
5301
5302         if (tsicr & IGC_TSICR_AUTT0) {
5303                 nsec = rd32(IGC_AUXSTMPL0);
5304                 sec  = rd32(IGC_AUXSTMPH0);
5305                 event.type = PTP_CLOCK_EXTTS;
5306                 event.index = 0;
5307                 event.timestamp = sec * NSEC_PER_SEC + nsec;
5308                 ptp_clock_event(adapter->ptp_clock, &event);
5309                 ack |= IGC_TSICR_AUTT0;
5310         }
5311
5312         if (tsicr & IGC_TSICR_AUTT1) {
5313                 nsec = rd32(IGC_AUXSTMPL1);
5314                 sec  = rd32(IGC_AUXSTMPH1);
5315                 event.type = PTP_CLOCK_EXTTS;
5316                 event.index = 1;
5317                 event.timestamp = sec * NSEC_PER_SEC + nsec;
5318                 ptp_clock_event(adapter->ptp_clock, &event);
5319                 ack |= IGC_TSICR_AUTT1;
5320         }
5321
5322         /* acknowledge the interrupts */
5323         wr32(IGC_TSICR, ack);
5324 }
5325
5326 /**
5327  * igc_msix_other - msix other interrupt handler
5328  * @irq: interrupt number
5329  * @data: pointer to a q_vector
5330  */
5331 static irqreturn_t igc_msix_other(int irq, void *data)
5332 {
5333         struct igc_adapter *adapter = data;
5334         struct igc_hw *hw = &adapter->hw;
5335         u32 icr = rd32(IGC_ICR);
5336
5337         /* reading ICR causes bit 31 of EICR to be cleared */
5338         if (icr & IGC_ICR_DRSTA)
5339                 schedule_work(&adapter->reset_task);
5340
5341         if (icr & IGC_ICR_DOUTSYNC) {
5342                 /* HW is reporting DMA is out of sync */
5343                 adapter->stats.doosync++;
5344         }
5345
5346         if (icr & IGC_ICR_LSC) {
5347                 hw->mac.get_link_status = true;
5348                 /* guard against interrupt when we're going down */
5349                 if (!test_bit(__IGC_DOWN, &adapter->state))
5350                         mod_timer(&adapter->watchdog_timer, jiffies + 1);
5351         }
5352
5353         if (icr & IGC_ICR_TS)
5354                 igc_tsync_interrupt(adapter);
5355
5356         wr32(IGC_EIMS, adapter->eims_other);
5357
5358         return IRQ_HANDLED;
5359 }
5360
5361 static void igc_write_itr(struct igc_q_vector *q_vector)
5362 {
5363         u32 itr_val = q_vector->itr_val & IGC_QVECTOR_MASK;
5364
5365         if (!q_vector->set_itr)
5366                 return;
5367
5368         if (!itr_val)
5369                 itr_val = IGC_ITR_VAL_MASK;
5370
5371         itr_val |= IGC_EITR_CNT_IGNR;
5372
5373         writel(itr_val, q_vector->itr_register);
5374         q_vector->set_itr = 0;
5375 }
5376
5377 static irqreturn_t igc_msix_ring(int irq, void *data)
5378 {
5379         struct igc_q_vector *q_vector = data;
5380
5381         /* Write the ITR value calculated from the previous interrupt. */
5382         igc_write_itr(q_vector);
5383
5384         napi_schedule(&q_vector->napi);
5385
5386         return IRQ_HANDLED;
5387 }
5388
5389 /**
5390  * igc_request_msix - Initialize MSI-X interrupts
5391  * @adapter: Pointer to adapter structure
5392  *
5393  * igc_request_msix allocates MSI-X vectors and requests interrupts from the
5394  * kernel.
5395  */
5396 static int igc_request_msix(struct igc_adapter *adapter)
5397 {
5398         unsigned int num_q_vectors = adapter->num_q_vectors;
5399         int i = 0, err = 0, vector = 0, free_vector = 0;
5400         struct net_device *netdev = adapter->netdev;
5401
5402         err = request_irq(adapter->msix_entries[vector].vector,
5403                           &igc_msix_other, 0, netdev->name, adapter);
5404         if (err)
5405                 goto err_out;
5406
5407         if (num_q_vectors > MAX_Q_VECTORS) {
5408                 num_q_vectors = MAX_Q_VECTORS;
5409                 dev_warn(&adapter->pdev->dev,
5410                          "The number of queue vectors (%d) is higher than max allowed (%d)\n",
5411                          adapter->num_q_vectors, MAX_Q_VECTORS);
5412         }
5413         for (i = 0; i < num_q_vectors; i++) {
5414                 struct igc_q_vector *q_vector = adapter->q_vector[i];
5415
5416                 vector++;
5417
5418                 q_vector->itr_register = adapter->io_addr + IGC_EITR(vector);
5419
5420                 if (q_vector->rx.ring && q_vector->tx.ring)
5421                         sprintf(q_vector->name, "%s-TxRx-%u", netdev->name,
5422                                 q_vector->rx.ring->queue_index);
5423                 else if (q_vector->tx.ring)
5424                         sprintf(q_vector->name, "%s-tx-%u", netdev->name,
5425                                 q_vector->tx.ring->queue_index);
5426                 else if (q_vector->rx.ring)
5427                         sprintf(q_vector->name, "%s-rx-%u", netdev->name,
5428                                 q_vector->rx.ring->queue_index);
5429                 else
5430                         sprintf(q_vector->name, "%s-unused", netdev->name);
5431
5432                 err = request_irq(adapter->msix_entries[vector].vector,
5433                                   igc_msix_ring, 0, q_vector->name,
5434                                   q_vector);
5435                 if (err)
5436                         goto err_free;
5437         }
5438
5439         igc_configure_msix(adapter);
5440         return 0;
5441
5442 err_free:
5443         /* free already assigned IRQs */
5444         free_irq(adapter->msix_entries[free_vector++].vector, adapter);
5445
5446         vector--;
5447         for (i = 0; i < vector; i++) {
5448                 free_irq(adapter->msix_entries[free_vector++].vector,
5449                          adapter->q_vector[i]);
5450         }
5451 err_out:
5452         return err;
5453 }
5454
5455 /**
5456  * igc_clear_interrupt_scheme - reset the device to a state of no interrupts
5457  * @adapter: Pointer to adapter structure
5458  *
5459  * This function resets the device so that it has 0 rx queues, tx queues, and
5460  * MSI-X interrupts allocated.
5461  */
5462 static void igc_clear_interrupt_scheme(struct igc_adapter *adapter)
5463 {
5464         igc_free_q_vectors(adapter);
5465         igc_reset_interrupt_capability(adapter);
5466 }
5467
5468 /* Need to wait a few seconds after link up to get diagnostic information from
5469  * the phy
5470  */
5471 static void igc_update_phy_info(struct timer_list *t)
5472 {
5473         struct igc_adapter *adapter = from_timer(adapter, t, phy_info_timer);
5474
5475         igc_get_phy_info(&adapter->hw);
5476 }
5477
5478 /**
5479  * igc_has_link - check shared code for link and determine up/down
5480  * @adapter: pointer to driver private info
5481  */
5482 bool igc_has_link(struct igc_adapter *adapter)
5483 {
5484         struct igc_hw *hw = &adapter->hw;
5485         bool link_active = false;
5486
5487         /* get_link_status is set on LSC (link status) interrupt or
5488          * rx sequence error interrupt.  get_link_status will stay
5489          * false until the igc_check_for_link establishes link
5490          * for copper adapters ONLY
5491          */
5492         if (!hw->mac.get_link_status)
5493                 return true;
5494         hw->mac.ops.check_for_link(hw);
5495         link_active = !hw->mac.get_link_status;
5496
5497         if (hw->mac.type == igc_i225) {
5498                 if (!netif_carrier_ok(adapter->netdev)) {
5499                         adapter->flags &= ~IGC_FLAG_NEED_LINK_UPDATE;
5500                 } else if (!(adapter->flags & IGC_FLAG_NEED_LINK_UPDATE)) {
5501                         adapter->flags |= IGC_FLAG_NEED_LINK_UPDATE;
5502                         adapter->link_check_timeout = jiffies;
5503                 }
5504         }
5505
5506         return link_active;
5507 }
5508
5509 /**
5510  * igc_watchdog - Timer Call-back
5511  * @t: timer for the watchdog
5512  */
5513 static void igc_watchdog(struct timer_list *t)
5514 {
5515         struct igc_adapter *adapter = from_timer(adapter, t, watchdog_timer);
5516         /* Do the rest outside of interrupt context */
5517         schedule_work(&adapter->watchdog_task);
5518 }
5519
5520 static void igc_watchdog_task(struct work_struct *work)
5521 {
5522         struct igc_adapter *adapter = container_of(work,
5523                                                    struct igc_adapter,
5524                                                    watchdog_task);
5525         struct net_device *netdev = adapter->netdev;
5526         struct igc_hw *hw = &adapter->hw;
5527         struct igc_phy_info *phy = &hw->phy;
5528         u16 phy_data, retry_count = 20;
5529         u32 link;
5530         int i;
5531
5532         link = igc_has_link(adapter);
5533
5534         if (adapter->flags & IGC_FLAG_NEED_LINK_UPDATE) {
5535                 if (time_after(jiffies, (adapter->link_check_timeout + HZ)))
5536                         adapter->flags &= ~IGC_FLAG_NEED_LINK_UPDATE;
5537                 else
5538                         link = false;
5539         }
5540
5541         if (link) {
5542                 /* Cancel scheduled suspend requests. */
5543                 pm_runtime_resume(netdev->dev.parent);
5544
5545                 if (!netif_carrier_ok(netdev)) {
5546                         u32 ctrl;
5547
5548                         hw->mac.ops.get_speed_and_duplex(hw,
5549                                                          &adapter->link_speed,
5550                                                          &adapter->link_duplex);
5551
5552                         ctrl = rd32(IGC_CTRL);
5553                         /* Link status message must follow this format */
5554                         netdev_info(netdev,
5555                                     "NIC Link is Up %d Mbps %s Duplex, Flow Control: %s\n",
5556                                     adapter->link_speed,
5557                                     adapter->link_duplex == FULL_DUPLEX ?
5558                                     "Full" : "Half",
5559                                     (ctrl & IGC_CTRL_TFCE) &&
5560                                     (ctrl & IGC_CTRL_RFCE) ? "RX/TX" :
5561                                     (ctrl & IGC_CTRL_RFCE) ?  "RX" :
5562                                     (ctrl & IGC_CTRL_TFCE) ?  "TX" : "None");
5563
5564                         /* disable EEE if enabled */
5565                         if ((adapter->flags & IGC_FLAG_EEE) &&
5566                             adapter->link_duplex == HALF_DUPLEX) {
5567                                 netdev_info(netdev,
5568                                             "EEE Disabled: unsupported at half duplex. Re-enable using ethtool when at full duplex\n");
5569                                 adapter->hw.dev_spec._base.eee_enable = false;
5570                                 adapter->flags &= ~IGC_FLAG_EEE;
5571                         }
5572
5573                         /* check if SmartSpeed worked */
5574                         igc_check_downshift(hw);
5575                         if (phy->speed_downgraded)
5576                                 netdev_warn(netdev, "Link Speed was downgraded by SmartSpeed\n");
5577
5578                         /* adjust timeout factor according to speed/duplex */
5579                         adapter->tx_timeout_factor = 1;
5580                         switch (adapter->link_speed) {
5581                         case SPEED_10:
5582                                 adapter->tx_timeout_factor = 14;
5583                                 break;
5584                         case SPEED_100:
5585                         case SPEED_1000:
5586                         case SPEED_2500:
5587                                 adapter->tx_timeout_factor = 1;
5588                                 break;
5589                         }
5590
5591                         /* Once the launch time has been set on the wire, there
5592                          * is a delay before the link speed can be determined
5593                          * based on link-up activity. Write into the register
5594                          * as soon as we know the correct link speed.
5595                          */
5596                         igc_tsn_adjust_txtime_offset(adapter);
5597
5598                         if (adapter->link_speed != SPEED_1000)
5599                                 goto no_wait;
5600
5601                         /* wait for Remote receiver status OK */
5602 retry_read_status:
5603                         if (!igc_read_phy_reg(hw, PHY_1000T_STATUS,
5604                                               &phy_data)) {
5605                                 if (!(phy_data & SR_1000T_REMOTE_RX_STATUS) &&
5606                                     retry_count) {
5607                                         msleep(100);
5608                                         retry_count--;
5609                                         goto retry_read_status;
5610                                 } else if (!retry_count) {
5611                                         netdev_err(netdev, "exceed max 2 second\n");
5612                                 }
5613                         } else {
5614                                 netdev_err(netdev, "read 1000Base-T Status Reg\n");
5615                         }
5616 no_wait:
5617                         netif_carrier_on(netdev);
5618
5619                         /* link state has changed, schedule phy info update */
5620                         if (!test_bit(__IGC_DOWN, &adapter->state))
5621                                 mod_timer(&adapter->phy_info_timer,
5622                                           round_jiffies(jiffies + 2 * HZ));
5623                 }
5624         } else {
5625                 if (netif_carrier_ok(netdev)) {
5626                         adapter->link_speed = 0;
5627                         adapter->link_duplex = 0;
5628
5629                         /* Links status message must follow this format */
5630                         netdev_info(netdev, "NIC Link is Down\n");
5631                         netif_carrier_off(netdev);
5632
5633                         /* link state has changed, schedule phy info update */
5634                         if (!test_bit(__IGC_DOWN, &adapter->state))
5635                                 mod_timer(&adapter->phy_info_timer,
5636                                           round_jiffies(jiffies + 2 * HZ));
5637
5638                         pm_schedule_suspend(netdev->dev.parent,
5639                                             MSEC_PER_SEC * 5);
5640                 }
5641         }
5642
5643         spin_lock(&adapter->stats64_lock);
5644         igc_update_stats(adapter);
5645         spin_unlock(&adapter->stats64_lock);
5646
5647         for (i = 0; i < adapter->num_tx_queues; i++) {
5648                 struct igc_ring *tx_ring = adapter->tx_ring[i];
5649
5650                 if (!netif_carrier_ok(netdev)) {
5651                         /* We've lost link, so the controller stops DMA,
5652                          * but we've got queued Tx work that's never going
5653                          * to get done, so reset controller to flush Tx.
5654                          * (Do the reset outside of interrupt context).
5655                          */
5656                         if (igc_desc_unused(tx_ring) + 1 < tx_ring->count) {
5657                                 adapter->tx_timeout_count++;
5658                                 schedule_work(&adapter->reset_task);
5659                                 /* return immediately since reset is imminent */
5660                                 return;
5661                         }
5662                 }
5663
5664                 /* Force detection of hung controller every watchdog period */
5665                 set_bit(IGC_RING_FLAG_TX_DETECT_HANG, &tx_ring->flags);
5666         }
5667
5668         /* Cause software interrupt to ensure Rx ring is cleaned */
5669         if (adapter->flags & IGC_FLAG_HAS_MSIX) {
5670                 u32 eics = 0;
5671
5672                 for (i = 0; i < adapter->num_q_vectors; i++)
5673                         eics |= adapter->q_vector[i]->eims_value;
5674                 wr32(IGC_EICS, eics);
5675         } else {
5676                 wr32(IGC_ICS, IGC_ICS_RXDMT0);
5677         }
5678
5679         igc_ptp_tx_hang(adapter);
5680
5681         /* Reset the timer */
5682         if (!test_bit(__IGC_DOWN, &adapter->state)) {
5683                 if (adapter->flags & IGC_FLAG_NEED_LINK_UPDATE)
5684                         mod_timer(&adapter->watchdog_timer,
5685                                   round_jiffies(jiffies +  HZ));
5686                 else
5687                         mod_timer(&adapter->watchdog_timer,
5688                                   round_jiffies(jiffies + 2 * HZ));
5689         }
5690 }
5691
5692 /**
5693  * igc_intr_msi - Interrupt Handler
5694  * @irq: interrupt number
5695  * @data: pointer to a network interface device structure
5696  */
5697 static irqreturn_t igc_intr_msi(int irq, void *data)
5698 {
5699         struct igc_adapter *adapter = data;
5700         struct igc_q_vector *q_vector = adapter->q_vector[0];
5701         struct igc_hw *hw = &adapter->hw;
5702         /* read ICR disables interrupts using IAM */
5703         u32 icr = rd32(IGC_ICR);
5704
5705         igc_write_itr(q_vector);
5706
5707         if (icr & IGC_ICR_DRSTA)
5708                 schedule_work(&adapter->reset_task);
5709
5710         if (icr & IGC_ICR_DOUTSYNC) {
5711                 /* HW is reporting DMA is out of sync */
5712                 adapter->stats.doosync++;
5713         }
5714
5715         if (icr & (IGC_ICR_RXSEQ | IGC_ICR_LSC)) {
5716                 hw->mac.get_link_status = true;
5717                 if (!test_bit(__IGC_DOWN, &adapter->state))
5718                         mod_timer(&adapter->watchdog_timer, jiffies + 1);
5719         }
5720
5721         if (icr & IGC_ICR_TS)
5722                 igc_tsync_interrupt(adapter);
5723
5724         napi_schedule(&q_vector->napi);
5725
5726         return IRQ_HANDLED;
5727 }
5728
5729 /**
5730  * igc_intr - Legacy Interrupt Handler
5731  * @irq: interrupt number
5732  * @data: pointer to a network interface device structure
5733  */
5734 static irqreturn_t igc_intr(int irq, void *data)
5735 {
5736         struct igc_adapter *adapter = data;
5737         struct igc_q_vector *q_vector = adapter->q_vector[0];
5738         struct igc_hw *hw = &adapter->hw;
5739         /* Interrupt Auto-Mask...upon reading ICR, interrupts are masked.  No
5740          * need for the IMC write
5741          */
5742         u32 icr = rd32(IGC_ICR);
5743
5744         /* IMS will not auto-mask if INT_ASSERTED is not set, and if it is
5745          * not set, then the adapter didn't send an interrupt
5746          */
5747         if (!(icr & IGC_ICR_INT_ASSERTED))
5748                 return IRQ_NONE;
5749
5750         igc_write_itr(q_vector);
5751
5752         if (icr & IGC_ICR_DRSTA)
5753                 schedule_work(&adapter->reset_task);
5754
5755         if (icr & IGC_ICR_DOUTSYNC) {
5756                 /* HW is reporting DMA is out of sync */
5757                 adapter->stats.doosync++;
5758         }
5759
5760         if (icr & (IGC_ICR_RXSEQ | IGC_ICR_LSC)) {
5761                 hw->mac.get_link_status = true;
5762                 /* guard against interrupt when we're going down */
5763                 if (!test_bit(__IGC_DOWN, &adapter->state))
5764                         mod_timer(&adapter->watchdog_timer, jiffies + 1);
5765         }
5766
5767         if (icr & IGC_ICR_TS)
5768                 igc_tsync_interrupt(adapter);
5769
5770         napi_schedule(&q_vector->napi);
5771
5772         return IRQ_HANDLED;
5773 }
5774
5775 static void igc_free_irq(struct igc_adapter *adapter)
5776 {
5777         if (adapter->msix_entries) {
5778                 int vector = 0, i;
5779
5780                 free_irq(adapter->msix_entries[vector++].vector, adapter);
5781
5782                 for (i = 0; i < adapter->num_q_vectors; i++)
5783                         free_irq(adapter->msix_entries[vector++].vector,
5784                                  adapter->q_vector[i]);
5785         } else {
5786                 free_irq(adapter->pdev->irq, adapter);
5787         }
5788 }
5789
5790 /**
5791  * igc_request_irq - initialize interrupts
5792  * @adapter: Pointer to adapter structure
5793  *
5794  * Attempts to configure interrupts using the best available
5795  * capabilities of the hardware and kernel.
5796  */
5797 static int igc_request_irq(struct igc_adapter *adapter)
5798 {
5799         struct net_device *netdev = adapter->netdev;
5800         struct pci_dev *pdev = adapter->pdev;
5801         int err = 0;
5802
5803         if (adapter->flags & IGC_FLAG_HAS_MSIX) {
5804                 err = igc_request_msix(adapter);
5805                 if (!err)
5806                         goto request_done;
5807                 /* fall back to MSI */
5808                 igc_free_all_tx_resources(adapter);
5809                 igc_free_all_rx_resources(adapter);
5810
5811                 igc_clear_interrupt_scheme(adapter);
5812                 err = igc_init_interrupt_scheme(adapter, false);
5813                 if (err)
5814                         goto request_done;
5815                 igc_setup_all_tx_resources(adapter);
5816                 igc_setup_all_rx_resources(adapter);
5817                 igc_configure(adapter);
5818         }
5819
5820         igc_assign_vector(adapter->q_vector[0], 0);
5821
5822         if (adapter->flags & IGC_FLAG_HAS_MSI) {
5823                 err = request_irq(pdev->irq, &igc_intr_msi, 0,
5824                                   netdev->name, adapter);
5825                 if (!err)
5826                         goto request_done;
5827
5828                 /* fall back to legacy interrupts */
5829                 igc_reset_interrupt_capability(adapter);
5830                 adapter->flags &= ~IGC_FLAG_HAS_MSI;
5831         }
5832
5833         err = request_irq(pdev->irq, &igc_intr, IRQF_SHARED,
5834                           netdev->name, adapter);
5835
5836         if (err)
5837                 netdev_err(netdev, "Error %d getting interrupt\n", err);
5838
5839 request_done:
5840         return err;
5841 }
5842
5843 /**
5844  * __igc_open - Called when a network interface is made active
5845  * @netdev: network interface device structure
5846  * @resuming: boolean indicating if the device is resuming
5847  *
5848  * Returns 0 on success, negative value on failure
5849  *
5850  * The open entry point is called when a network interface is made
5851  * active by the system (IFF_UP).  At this point all resources needed
5852  * for transmit and receive operations are allocated, the interrupt
5853  * handler is registered with the OS, the watchdog timer is started,
5854  * and the stack is notified that the interface is ready.
5855  */
5856 static int __igc_open(struct net_device *netdev, bool resuming)
5857 {
5858         struct igc_adapter *adapter = netdev_priv(netdev);
5859         struct pci_dev *pdev = adapter->pdev;
5860         struct igc_hw *hw = &adapter->hw;
5861         int err = 0;
5862         int i = 0;
5863
5864         /* disallow open during test */
5865
5866         if (test_bit(__IGC_TESTING, &adapter->state)) {
5867                 WARN_ON(resuming);
5868                 return -EBUSY;
5869         }
5870
5871         if (!resuming)
5872                 pm_runtime_get_sync(&pdev->dev);
5873
5874         netif_carrier_off(netdev);
5875
5876         /* allocate transmit descriptors */
5877         err = igc_setup_all_tx_resources(adapter);
5878         if (err)
5879                 goto err_setup_tx;
5880
5881         /* allocate receive descriptors */
5882         err = igc_setup_all_rx_resources(adapter);
5883         if (err)
5884                 goto err_setup_rx;
5885
5886         igc_power_up_link(adapter);
5887
5888         igc_configure(adapter);
5889
5890         err = igc_request_irq(adapter);
5891         if (err)
5892                 goto err_req_irq;
5893
5894         /* Notify the stack of the actual queue counts. */
5895         err = netif_set_real_num_tx_queues(netdev, adapter->num_tx_queues);
5896         if (err)
5897                 goto err_set_queues;
5898
5899         err = netif_set_real_num_rx_queues(netdev, adapter->num_rx_queues);
5900         if (err)
5901                 goto err_set_queues;
5902
5903         clear_bit(__IGC_DOWN, &adapter->state);
5904
5905         for (i = 0; i < adapter->num_q_vectors; i++)
5906                 napi_enable(&adapter->q_vector[i]->napi);
5907
5908         /* Clear any pending interrupts. */
5909         rd32(IGC_ICR);
5910         igc_irq_enable(adapter);
5911
5912         if (!resuming)
5913                 pm_runtime_put(&pdev->dev);
5914
5915         netif_tx_start_all_queues(netdev);
5916
5917         /* start the watchdog. */
5918         hw->mac.get_link_status = true;
5919         schedule_work(&adapter->watchdog_task);
5920
5921         return IGC_SUCCESS;
5922
5923 err_set_queues:
5924         igc_free_irq(adapter);
5925 err_req_irq:
5926         igc_release_hw_control(adapter);
5927         igc_power_down_phy_copper_base(&adapter->hw);
5928         igc_free_all_rx_resources(adapter);
5929 err_setup_rx:
5930         igc_free_all_tx_resources(adapter);
5931 err_setup_tx:
5932         igc_reset(adapter);
5933         if (!resuming)
5934                 pm_runtime_put(&pdev->dev);
5935
5936         return err;
5937 }
5938
5939 int igc_open(struct net_device *netdev)
5940 {
5941         return __igc_open(netdev, false);
5942 }
5943
5944 /**
5945  * __igc_close - Disables a network interface
5946  * @netdev: network interface device structure
5947  * @suspending: boolean indicating the device is suspending
5948  *
5949  * Returns 0, this is not allowed to fail
5950  *
5951  * The close entry point is called when an interface is de-activated
5952  * by the OS.  The hardware is still under the driver's control, but
5953  * needs to be disabled.  A global MAC reset is issued to stop the
5954  * hardware, and all transmit and receive resources are freed.
5955  */
5956 static int __igc_close(struct net_device *netdev, bool suspending)
5957 {
5958         struct igc_adapter *adapter = netdev_priv(netdev);
5959         struct pci_dev *pdev = adapter->pdev;
5960
5961         WARN_ON(test_bit(__IGC_RESETTING, &adapter->state));
5962
5963         if (!suspending)
5964                 pm_runtime_get_sync(&pdev->dev);
5965
5966         igc_down(adapter);
5967
5968         igc_release_hw_control(adapter);
5969
5970         igc_free_irq(adapter);
5971
5972         igc_free_all_tx_resources(adapter);
5973         igc_free_all_rx_resources(adapter);
5974
5975         if (!suspending)
5976                 pm_runtime_put_sync(&pdev->dev);
5977
5978         return 0;
5979 }
5980
5981 int igc_close(struct net_device *netdev)
5982 {
5983         if (netif_device_present(netdev) || netdev->dismantle)
5984                 return __igc_close(netdev, false);
5985         return 0;
5986 }
5987
5988 /**
5989  * igc_ioctl - Access the hwtstamp interface
5990  * @netdev: network interface device structure
5991  * @ifr: interface request data
5992  * @cmd: ioctl command
5993  **/
5994 static int igc_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
5995 {
5996         switch (cmd) {
5997         case SIOCGHWTSTAMP:
5998                 return igc_ptp_get_ts_config(netdev, ifr);
5999         case SIOCSHWTSTAMP:
6000                 return igc_ptp_set_ts_config(netdev, ifr);
6001         default:
6002                 return -EOPNOTSUPP;
6003         }
6004 }
6005
6006 static int igc_save_launchtime_params(struct igc_adapter *adapter, int queue,
6007                                       bool enable)
6008 {
6009         struct igc_ring *ring;
6010
6011         if (queue < 0 || queue >= adapter->num_tx_queues)
6012                 return -EINVAL;
6013
6014         ring = adapter->tx_ring[queue];
6015         ring->launchtime_enable = enable;
6016
6017         return 0;
6018 }
6019
6020 static bool is_base_time_past(ktime_t base_time, const struct timespec64 *now)
6021 {
6022         struct timespec64 b;
6023
6024         b = ktime_to_timespec64(base_time);
6025
6026         return timespec64_compare(now, &b) > 0;
6027 }
6028
6029 static bool validate_schedule(struct igc_adapter *adapter,
6030                               const struct tc_taprio_qopt_offload *qopt)
6031 {
6032         int queue_uses[IGC_MAX_TX_QUEUES] = { };
6033         struct igc_hw *hw = &adapter->hw;
6034         struct timespec64 now;
6035         size_t n;
6036
6037         if (qopt->cycle_time_extension)
6038                 return false;
6039
6040         igc_ptp_read(adapter, &now);
6041
6042         /* If we program the controller's BASET registers with a time
6043          * in the future, it will hold all the packets until that
6044          * time, causing a lot of TX Hangs, so to avoid that, we
6045          * reject schedules that would start in the future.
6046          * Note: Limitation above is no longer in i226.
6047          */
6048         if (!is_base_time_past(qopt->base_time, &now) &&
6049             igc_is_device_id_i225(hw))
6050                 return false;
6051
6052         for (n = 0; n < qopt->num_entries; n++) {
6053                 const struct tc_taprio_sched_entry *e, *prev;
6054                 int i;
6055
6056                 prev = n ? &qopt->entries[n - 1] : NULL;
6057                 e = &qopt->entries[n];
6058
6059                 /* i225 only supports "global" frame preemption
6060                  * settings.
6061                  */
6062                 if (e->command != TC_TAPRIO_CMD_SET_GATES)
6063                         return false;
6064
6065                 for (i = 0; i < adapter->num_tx_queues; i++)
6066                         if (e->gate_mask & BIT(i)) {
6067                                 queue_uses[i]++;
6068
6069                                 /* There are limitations: A single queue cannot
6070                                  * be opened and closed multiple times per cycle
6071                                  * unless the gate stays open. Check for it.
6072                                  */
6073                                 if (queue_uses[i] > 1 &&
6074                                     !(prev->gate_mask & BIT(i)))
6075                                         return false;
6076                         }
6077         }
6078
6079         return true;
6080 }
6081
6082 static int igc_tsn_enable_launchtime(struct igc_adapter *adapter,
6083                                      struct tc_etf_qopt_offload *qopt)
6084 {
6085         struct igc_hw *hw = &adapter->hw;
6086         int err;
6087
6088         if (hw->mac.type != igc_i225)
6089                 return -EOPNOTSUPP;
6090
6091         err = igc_save_launchtime_params(adapter, qopt->queue, qopt->enable);
6092         if (err)
6093                 return err;
6094
6095         return igc_tsn_offload_apply(adapter);
6096 }
6097
6098 static int igc_tsn_clear_schedule(struct igc_adapter *adapter)
6099 {
6100         int i;
6101
6102         adapter->base_time = 0;
6103         adapter->cycle_time = NSEC_PER_SEC;
6104         adapter->qbv_config_change_errors = 0;
6105
6106         for (i = 0; i < adapter->num_tx_queues; i++) {
6107                 struct igc_ring *ring = adapter->tx_ring[i];
6108
6109                 ring->start_time = 0;
6110                 ring->end_time = NSEC_PER_SEC;
6111                 ring->max_sdu = 0;
6112         }
6113
6114         return 0;
6115 }
6116
6117 static int igc_save_qbv_schedule(struct igc_adapter *adapter,
6118                                  struct tc_taprio_qopt_offload *qopt)
6119 {
6120         bool queue_configured[IGC_MAX_TX_QUEUES] = { };
6121         struct igc_hw *hw = &adapter->hw;
6122         u32 start_time = 0, end_time = 0;
6123         size_t n;
6124         int i;
6125
6126         switch (qopt->cmd) {
6127         case TAPRIO_CMD_REPLACE:
6128                 adapter->qbv_enable = true;
6129                 break;
6130         case TAPRIO_CMD_DESTROY:
6131                 adapter->qbv_enable = false;
6132                 break;
6133         default:
6134                 return -EOPNOTSUPP;
6135         }
6136
6137         if (!adapter->qbv_enable)
6138                 return igc_tsn_clear_schedule(adapter);
6139
6140         if (qopt->base_time < 0)
6141                 return -ERANGE;
6142
6143         if (igc_is_device_id_i225(hw) && adapter->base_time)
6144                 return -EALREADY;
6145
6146         if (!validate_schedule(adapter, qopt))
6147                 return -EINVAL;
6148
6149         adapter->cycle_time = qopt->cycle_time;
6150         adapter->base_time = qopt->base_time;
6151
6152         for (n = 0; n < qopt->num_entries; n++) {
6153                 struct tc_taprio_sched_entry *e = &qopt->entries[n];
6154
6155                 end_time += e->interval;
6156
6157                 /* If any of the conditions below are true, we need to manually
6158                  * control the end time of the cycle.
6159                  * 1. Qbv users can specify a cycle time that is not equal
6160                  * to the total GCL intervals. Hence, recalculation is
6161                  * necessary here to exclude the time interval that
6162                  * exceeds the cycle time.
6163                  * 2. According to IEEE Std. 802.1Q-2018 section 8.6.9.2,
6164                  * once the end of the list is reached, it will switch
6165                  * to the END_OF_CYCLE state and leave the gates in the
6166                  * same state until the next cycle is started.
6167                  */
6168                 if (end_time > adapter->cycle_time ||
6169                     n + 1 == qopt->num_entries)
6170                         end_time = adapter->cycle_time;
6171
6172                 for (i = 0; i < adapter->num_tx_queues; i++) {
6173                         struct igc_ring *ring = adapter->tx_ring[i];
6174
6175                         if (!(e->gate_mask & BIT(i)))
6176                                 continue;
6177
6178                         /* Check whether a queue stays open for more than one
6179                          * entry. If so, keep the start and advance the end
6180                          * time.
6181                          */
6182                         if (!queue_configured[i])
6183                                 ring->start_time = start_time;
6184                         ring->end_time = end_time;
6185
6186                         queue_configured[i] = true;
6187                 }
6188
6189                 start_time += e->interval;
6190         }
6191
6192         /* Check whether a queue gets configured.
6193          * If not, set the start and end time to be end time.
6194          */
6195         for (i = 0; i < adapter->num_tx_queues; i++) {
6196                 if (!queue_configured[i]) {
6197                         struct igc_ring *ring = adapter->tx_ring[i];
6198
6199                         ring->start_time = end_time;
6200                         ring->end_time = end_time;
6201                 }
6202         }
6203
6204         for (i = 0; i < adapter->num_tx_queues; i++) {
6205                 struct igc_ring *ring = adapter->tx_ring[i];
6206                 struct net_device *dev = adapter->netdev;
6207
6208                 if (qopt->max_sdu[i])
6209                         ring->max_sdu = qopt->max_sdu[i] + dev->hard_header_len;
6210                 else
6211                         ring->max_sdu = 0;
6212         }
6213
6214         return 0;
6215 }
6216
6217 static int igc_tsn_enable_qbv_scheduling(struct igc_adapter *adapter,
6218                                          struct tc_taprio_qopt_offload *qopt)
6219 {
6220         struct igc_hw *hw = &adapter->hw;
6221         int err;
6222
6223         if (hw->mac.type != igc_i225)
6224                 return -EOPNOTSUPP;
6225
6226         err = igc_save_qbv_schedule(adapter, qopt);
6227         if (err)
6228                 return err;
6229
6230         return igc_tsn_offload_apply(adapter);
6231 }
6232
6233 static int igc_save_cbs_params(struct igc_adapter *adapter, int queue,
6234                                bool enable, int idleslope, int sendslope,
6235                                int hicredit, int locredit)
6236 {
6237         bool cbs_status[IGC_MAX_SR_QUEUES] = { false };
6238         struct net_device *netdev = adapter->netdev;
6239         struct igc_ring *ring;
6240         int i;
6241
6242         /* i225 has two sets of credit-based shaper logic.
6243          * Supporting it only on the top two priority queues
6244          */
6245         if (queue < 0 || queue > 1)
6246                 return -EINVAL;
6247
6248         ring = adapter->tx_ring[queue];
6249
6250         for (i = 0; i < IGC_MAX_SR_QUEUES; i++)
6251                 if (adapter->tx_ring[i])
6252                         cbs_status[i] = adapter->tx_ring[i]->cbs_enable;
6253
6254         /* CBS should be enabled on the highest priority queue first in order
6255          * for the CBS algorithm to operate as intended.
6256          */
6257         if (enable) {
6258                 if (queue == 1 && !cbs_status[0]) {
6259                         netdev_err(netdev,
6260                                    "Enabling CBS on queue1 before queue0\n");
6261                         return -EINVAL;
6262                 }
6263         } else {
6264                 if (queue == 0 && cbs_status[1]) {
6265                         netdev_err(netdev,
6266                                    "Disabling CBS on queue0 before queue1\n");
6267                         return -EINVAL;
6268                 }
6269         }
6270
6271         ring->cbs_enable = enable;
6272         ring->idleslope = idleslope;
6273         ring->sendslope = sendslope;
6274         ring->hicredit = hicredit;
6275         ring->locredit = locredit;
6276
6277         return 0;
6278 }
6279
6280 static int igc_tsn_enable_cbs(struct igc_adapter *adapter,
6281                               struct tc_cbs_qopt_offload *qopt)
6282 {
6283         struct igc_hw *hw = &adapter->hw;
6284         int err;
6285
6286         if (hw->mac.type != igc_i225)
6287                 return -EOPNOTSUPP;
6288
6289         if (qopt->queue < 0 || qopt->queue > 1)
6290                 return -EINVAL;
6291
6292         err = igc_save_cbs_params(adapter, qopt->queue, qopt->enable,
6293                                   qopt->idleslope, qopt->sendslope,
6294                                   qopt->hicredit, qopt->locredit);
6295         if (err)
6296                 return err;
6297
6298         return igc_tsn_offload_apply(adapter);
6299 }
6300
6301 static int igc_tc_query_caps(struct igc_adapter *adapter,
6302                              struct tc_query_caps_base *base)
6303 {
6304         struct igc_hw *hw = &adapter->hw;
6305
6306         switch (base->type) {
6307         case TC_SETUP_QDISC_TAPRIO: {
6308                 struct tc_taprio_caps *caps = base->caps;
6309
6310                 caps->broken_mqprio = true;
6311
6312                 if (hw->mac.type == igc_i225) {
6313                         caps->supports_queue_max_sdu = true;
6314                         caps->gate_mask_per_txq = true;
6315                 }
6316
6317                 return 0;
6318         }
6319         default:
6320                 return -EOPNOTSUPP;
6321         }
6322 }
6323
6324 static int igc_setup_tc(struct net_device *dev, enum tc_setup_type type,
6325                         void *type_data)
6326 {
6327         struct igc_adapter *adapter = netdev_priv(dev);
6328
6329         adapter->tc_setup_type = type;
6330
6331         switch (type) {
6332         case TC_QUERY_CAPS:
6333                 return igc_tc_query_caps(adapter, type_data);
6334         case TC_SETUP_QDISC_TAPRIO:
6335                 return igc_tsn_enable_qbv_scheduling(adapter, type_data);
6336
6337         case TC_SETUP_QDISC_ETF:
6338                 return igc_tsn_enable_launchtime(adapter, type_data);
6339
6340         case TC_SETUP_QDISC_CBS:
6341                 return igc_tsn_enable_cbs(adapter, type_data);
6342
6343         default:
6344                 return -EOPNOTSUPP;
6345         }
6346 }
6347
6348 static int igc_bpf(struct net_device *dev, struct netdev_bpf *bpf)
6349 {
6350         struct igc_adapter *adapter = netdev_priv(dev);
6351
6352         switch (bpf->command) {
6353         case XDP_SETUP_PROG:
6354                 return igc_xdp_set_prog(adapter, bpf->prog, bpf->extack);
6355         case XDP_SETUP_XSK_POOL:
6356                 return igc_xdp_setup_pool(adapter, bpf->xsk.pool,
6357                                           bpf->xsk.queue_id);
6358         default:
6359                 return -EOPNOTSUPP;
6360         }
6361 }
6362
6363 static int igc_xdp_xmit(struct net_device *dev, int num_frames,
6364                         struct xdp_frame **frames, u32 flags)
6365 {
6366         struct igc_adapter *adapter = netdev_priv(dev);
6367         int cpu = smp_processor_id();
6368         struct netdev_queue *nq;
6369         struct igc_ring *ring;
6370         int i, drops;
6371
6372         if (unlikely(test_bit(__IGC_DOWN, &adapter->state)))
6373                 return -ENETDOWN;
6374
6375         if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
6376                 return -EINVAL;
6377
6378         ring = igc_xdp_get_tx_ring(adapter, cpu);
6379         nq = txring_txq(ring);
6380
6381         __netif_tx_lock(nq, cpu);
6382
6383         /* Avoid transmit queue timeout since we share it with the slow path */
6384         txq_trans_cond_update(nq);
6385
6386         drops = 0;
6387         for (i = 0; i < num_frames; i++) {
6388                 int err;
6389                 struct xdp_frame *xdpf = frames[i];
6390
6391                 err = igc_xdp_init_tx_descriptor(ring, xdpf);
6392                 if (err) {
6393                         xdp_return_frame_rx_napi(xdpf);
6394                         drops++;
6395                 }
6396         }
6397
6398         if (flags & XDP_XMIT_FLUSH)
6399                 igc_flush_tx_descriptors(ring);
6400
6401         __netif_tx_unlock(nq);
6402
6403         return num_frames - drops;
6404 }
6405
6406 static void igc_trigger_rxtxq_interrupt(struct igc_adapter *adapter,
6407                                         struct igc_q_vector *q_vector)
6408 {
6409         struct igc_hw *hw = &adapter->hw;
6410         u32 eics = 0;
6411
6412         eics |= q_vector->eims_value;
6413         wr32(IGC_EICS, eics);
6414 }
6415
6416 int igc_xsk_wakeup(struct net_device *dev, u32 queue_id, u32 flags)
6417 {
6418         struct igc_adapter *adapter = netdev_priv(dev);
6419         struct igc_q_vector *q_vector;
6420         struct igc_ring *ring;
6421
6422         if (test_bit(__IGC_DOWN, &adapter->state))
6423                 return -ENETDOWN;
6424
6425         if (!igc_xdp_is_enabled(adapter))
6426                 return -ENXIO;
6427
6428         if (queue_id >= adapter->num_rx_queues)
6429                 return -EINVAL;
6430
6431         ring = adapter->rx_ring[queue_id];
6432
6433         if (!ring->xsk_pool)
6434                 return -ENXIO;
6435
6436         q_vector = adapter->q_vector[queue_id];
6437         if (!napi_if_scheduled_mark_missed(&q_vector->napi))
6438                 igc_trigger_rxtxq_interrupt(adapter, q_vector);
6439
6440         return 0;
6441 }
6442
6443 static const struct net_device_ops igc_netdev_ops = {
6444         .ndo_open               = igc_open,
6445         .ndo_stop               = igc_close,
6446         .ndo_start_xmit         = igc_xmit_frame,
6447         .ndo_set_rx_mode        = igc_set_rx_mode,
6448         .ndo_set_mac_address    = igc_set_mac,
6449         .ndo_change_mtu         = igc_change_mtu,
6450         .ndo_tx_timeout         = igc_tx_timeout,
6451         .ndo_get_stats64        = igc_get_stats64,
6452         .ndo_fix_features       = igc_fix_features,
6453         .ndo_set_features       = igc_set_features,
6454         .ndo_features_check     = igc_features_check,
6455         .ndo_eth_ioctl          = igc_ioctl,
6456         .ndo_setup_tc           = igc_setup_tc,
6457         .ndo_bpf                = igc_bpf,
6458         .ndo_xdp_xmit           = igc_xdp_xmit,
6459         .ndo_xsk_wakeup         = igc_xsk_wakeup,
6460 };
6461
6462 /* PCIe configuration access */
6463 void igc_read_pci_cfg(struct igc_hw *hw, u32 reg, u16 *value)
6464 {
6465         struct igc_adapter *adapter = hw->back;
6466
6467         pci_read_config_word(adapter->pdev, reg, value);
6468 }
6469
6470 void igc_write_pci_cfg(struct igc_hw *hw, u32 reg, u16 *value)
6471 {
6472         struct igc_adapter *adapter = hw->back;
6473
6474         pci_write_config_word(adapter->pdev, reg, *value);
6475 }
6476
6477 s32 igc_read_pcie_cap_reg(struct igc_hw *hw, u32 reg, u16 *value)
6478 {
6479         struct igc_adapter *adapter = hw->back;
6480
6481         if (!pci_is_pcie(adapter->pdev))
6482                 return -IGC_ERR_CONFIG;
6483
6484         pcie_capability_read_word(adapter->pdev, reg, value);
6485
6486         return IGC_SUCCESS;
6487 }
6488
6489 s32 igc_write_pcie_cap_reg(struct igc_hw *hw, u32 reg, u16 *value)
6490 {
6491         struct igc_adapter *adapter = hw->back;
6492
6493         if (!pci_is_pcie(adapter->pdev))
6494                 return -IGC_ERR_CONFIG;
6495
6496         pcie_capability_write_word(adapter->pdev, reg, *value);
6497
6498         return IGC_SUCCESS;
6499 }
6500
6501 u32 igc_rd32(struct igc_hw *hw, u32 reg)
6502 {
6503         struct igc_adapter *igc = container_of(hw, struct igc_adapter, hw);
6504         u8 __iomem *hw_addr = READ_ONCE(hw->hw_addr);
6505         u32 value = 0;
6506
6507         if (IGC_REMOVED(hw_addr))
6508                 return ~value;
6509
6510         value = readl(&hw_addr[reg]);
6511
6512         /* reads should not return all F's */
6513         if (!(~value) && (!reg || !(~readl(hw_addr)))) {
6514                 struct net_device *netdev = igc->netdev;
6515
6516                 hw->hw_addr = NULL;
6517                 netif_device_detach(netdev);
6518                 netdev_err(netdev, "PCIe link lost, device now detached\n");
6519                 WARN(pci_device_is_present(igc->pdev),
6520                      "igc: Failed to read reg 0x%x!\n", reg);
6521         }
6522
6523         return value;
6524 }
6525
6526 /* Mapping HW RSS Type to enum xdp_rss_hash_type */
6527 static enum xdp_rss_hash_type igc_xdp_rss_type[IGC_RSS_TYPE_MAX_TABLE] = {
6528         [IGC_RSS_TYPE_NO_HASH]          = XDP_RSS_TYPE_L2,
6529         [IGC_RSS_TYPE_HASH_TCP_IPV4]    = XDP_RSS_TYPE_L4_IPV4_TCP,
6530         [IGC_RSS_TYPE_HASH_IPV4]        = XDP_RSS_TYPE_L3_IPV4,
6531         [IGC_RSS_TYPE_HASH_TCP_IPV6]    = XDP_RSS_TYPE_L4_IPV6_TCP,
6532         [IGC_RSS_TYPE_HASH_IPV6_EX]     = XDP_RSS_TYPE_L3_IPV6_EX,
6533         [IGC_RSS_TYPE_HASH_IPV6]        = XDP_RSS_TYPE_L3_IPV6,
6534         [IGC_RSS_TYPE_HASH_TCP_IPV6_EX] = XDP_RSS_TYPE_L4_IPV6_TCP_EX,
6535         [IGC_RSS_TYPE_HASH_UDP_IPV4]    = XDP_RSS_TYPE_L4_IPV4_UDP,
6536         [IGC_RSS_TYPE_HASH_UDP_IPV6]    = XDP_RSS_TYPE_L4_IPV6_UDP,
6537         [IGC_RSS_TYPE_HASH_UDP_IPV6_EX] = XDP_RSS_TYPE_L4_IPV6_UDP_EX,
6538         [10] = XDP_RSS_TYPE_NONE, /* RSS Type above 9 "Reserved" by HW  */
6539         [11] = XDP_RSS_TYPE_NONE, /* keep array sized for SW bit-mask   */
6540         [12] = XDP_RSS_TYPE_NONE, /* to handle future HW revisons       */
6541         [13] = XDP_RSS_TYPE_NONE,
6542         [14] = XDP_RSS_TYPE_NONE,
6543         [15] = XDP_RSS_TYPE_NONE,
6544 };
6545
6546 static int igc_xdp_rx_hash(const struct xdp_md *_ctx, u32 *hash,
6547                            enum xdp_rss_hash_type *rss_type)
6548 {
6549         const struct igc_xdp_buff *ctx = (void *)_ctx;
6550
6551         if (!(ctx->xdp.rxq->dev->features & NETIF_F_RXHASH))
6552                 return -ENODATA;
6553
6554         *hash = le32_to_cpu(ctx->rx_desc->wb.lower.hi_dword.rss);
6555         *rss_type = igc_xdp_rss_type[igc_rss_type(ctx->rx_desc)];
6556
6557         return 0;
6558 }
6559
6560 static int igc_xdp_rx_timestamp(const struct xdp_md *_ctx, u64 *timestamp)
6561 {
6562         const struct igc_xdp_buff *ctx = (void *)_ctx;
6563
6564         if (igc_test_staterr(ctx->rx_desc, IGC_RXDADV_STAT_TSIP)) {
6565                 *timestamp = ctx->rx_ts;
6566
6567                 return 0;
6568         }
6569
6570         return -ENODATA;
6571 }
6572
6573 static const struct xdp_metadata_ops igc_xdp_metadata_ops = {
6574         .xmo_rx_hash                    = igc_xdp_rx_hash,
6575         .xmo_rx_timestamp               = igc_xdp_rx_timestamp,
6576 };
6577
6578 /**
6579  * igc_probe - Device Initialization Routine
6580  * @pdev: PCI device information struct
6581  * @ent: entry in igc_pci_tbl
6582  *
6583  * Returns 0 on success, negative on failure
6584  *
6585  * igc_probe initializes an adapter identified by a pci_dev structure.
6586  * The OS initialization, configuring the adapter private structure,
6587  * and a hardware reset occur.
6588  */
6589 static int igc_probe(struct pci_dev *pdev,
6590                      const struct pci_device_id *ent)
6591 {
6592         struct igc_adapter *adapter;
6593         struct net_device *netdev;
6594         struct igc_hw *hw;
6595         const struct igc_info *ei = igc_info_tbl[ent->driver_data];
6596         int err;
6597
6598         err = pci_enable_device_mem(pdev);
6599         if (err)
6600                 return err;
6601
6602         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
6603         if (err) {
6604                 dev_err(&pdev->dev,
6605                         "No usable DMA configuration, aborting\n");
6606                 goto err_dma;
6607         }
6608
6609         err = pci_request_mem_regions(pdev, igc_driver_name);
6610         if (err)
6611                 goto err_pci_reg;
6612
6613         err = pci_enable_ptm(pdev, NULL);
6614         if (err < 0)
6615                 dev_info(&pdev->dev, "PCIe PTM not supported by PCIe bus/controller\n");
6616
6617         pci_set_master(pdev);
6618
6619         err = -ENOMEM;
6620         netdev = alloc_etherdev_mq(sizeof(struct igc_adapter),
6621                                    IGC_MAX_TX_QUEUES);
6622
6623         if (!netdev)
6624                 goto err_alloc_etherdev;
6625
6626         SET_NETDEV_DEV(netdev, &pdev->dev);
6627
6628         pci_set_drvdata(pdev, netdev);
6629         adapter = netdev_priv(netdev);
6630         adapter->netdev = netdev;
6631         adapter->pdev = pdev;
6632         hw = &adapter->hw;
6633         hw->back = adapter;
6634         adapter->port_num = hw->bus.func;
6635         adapter->msg_enable = netif_msg_init(debug, DEFAULT_MSG_ENABLE);
6636
6637         err = pci_save_state(pdev);
6638         if (err)
6639                 goto err_ioremap;
6640
6641         err = -EIO;
6642         adapter->io_addr = ioremap(pci_resource_start(pdev, 0),
6643                                    pci_resource_len(pdev, 0));
6644         if (!adapter->io_addr)
6645                 goto err_ioremap;
6646
6647         /* hw->hw_addr can be zeroed, so use adapter->io_addr for unmap */
6648         hw->hw_addr = adapter->io_addr;
6649
6650         netdev->netdev_ops = &igc_netdev_ops;
6651         netdev->xdp_metadata_ops = &igc_xdp_metadata_ops;
6652         igc_ethtool_set_ops(netdev);
6653         netdev->watchdog_timeo = 5 * HZ;
6654
6655         netdev->mem_start = pci_resource_start(pdev, 0);
6656         netdev->mem_end = pci_resource_end(pdev, 0);
6657
6658         /* PCI config space info */
6659         hw->vendor_id = pdev->vendor;
6660         hw->device_id = pdev->device;
6661         hw->revision_id = pdev->revision;
6662         hw->subsystem_vendor_id = pdev->subsystem_vendor;
6663         hw->subsystem_device_id = pdev->subsystem_device;
6664
6665         /* Copy the default MAC and PHY function pointers */
6666         memcpy(&hw->mac.ops, ei->mac_ops, sizeof(hw->mac.ops));
6667         memcpy(&hw->phy.ops, ei->phy_ops, sizeof(hw->phy.ops));
6668
6669         /* Initialize skew-specific constants */
6670         err = ei->get_invariants(hw);
6671         if (err)
6672                 goto err_sw_init;
6673
6674         /* Add supported features to the features list*/
6675         netdev->features |= NETIF_F_SG;
6676         netdev->features |= NETIF_F_TSO;
6677         netdev->features |= NETIF_F_TSO6;
6678         netdev->features |= NETIF_F_TSO_ECN;
6679         netdev->features |= NETIF_F_RXHASH;
6680         netdev->features |= NETIF_F_RXCSUM;
6681         netdev->features |= NETIF_F_HW_CSUM;
6682         netdev->features |= NETIF_F_SCTP_CRC;
6683         netdev->features |= NETIF_F_HW_TC;
6684
6685 #define IGC_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE | \
6686                                   NETIF_F_GSO_GRE_CSUM | \
6687                                   NETIF_F_GSO_IPXIP4 | \
6688                                   NETIF_F_GSO_IPXIP6 | \
6689                                   NETIF_F_GSO_UDP_TUNNEL | \
6690                                   NETIF_F_GSO_UDP_TUNNEL_CSUM)
6691
6692         netdev->gso_partial_features = IGC_GSO_PARTIAL_FEATURES;
6693         netdev->features |= NETIF_F_GSO_PARTIAL | IGC_GSO_PARTIAL_FEATURES;
6694
6695         /* setup the private structure */
6696         err = igc_sw_init(adapter);
6697         if (err)
6698                 goto err_sw_init;
6699
6700         /* copy netdev features into list of user selectable features */
6701         netdev->hw_features |= NETIF_F_NTUPLE;
6702         netdev->hw_features |= NETIF_F_HW_VLAN_CTAG_TX;
6703         netdev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX;
6704         netdev->hw_features |= netdev->features;
6705
6706         netdev->features |= NETIF_F_HIGHDMA;
6707
6708         netdev->vlan_features |= netdev->features | NETIF_F_TSO_MANGLEID;
6709         netdev->mpls_features |= NETIF_F_HW_CSUM;
6710         netdev->hw_enc_features |= netdev->vlan_features;
6711
6712         netdev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT |
6713                                NETDEV_XDP_ACT_XSK_ZEROCOPY;
6714
6715         /* MTU range: 68 - 9216 */
6716         netdev->min_mtu = ETH_MIN_MTU;
6717         netdev->max_mtu = MAX_STD_JUMBO_FRAME_SIZE;
6718
6719         /* before reading the NVM, reset the controller to put the device in a
6720          * known good starting state
6721          */
6722         hw->mac.ops.reset_hw(hw);
6723
6724         if (igc_get_flash_presence_i225(hw)) {
6725                 if (hw->nvm.ops.validate(hw) < 0) {
6726                         dev_err(&pdev->dev, "The NVM Checksum Is Not Valid\n");
6727                         err = -EIO;
6728                         goto err_eeprom;
6729                 }
6730         }
6731
6732         if (eth_platform_get_mac_address(&pdev->dev, hw->mac.addr)) {
6733                 /* copy the MAC address out of the NVM */
6734                 if (hw->mac.ops.read_mac_addr(hw))
6735                         dev_err(&pdev->dev, "NVM Read Error\n");
6736         }
6737
6738         eth_hw_addr_set(netdev, hw->mac.addr);
6739
6740         if (!is_valid_ether_addr(netdev->dev_addr)) {
6741                 dev_err(&pdev->dev, "Invalid MAC Address\n");
6742                 err = -EIO;
6743                 goto err_eeprom;
6744         }
6745
6746         /* configure RXPBSIZE and TXPBSIZE */
6747         wr32(IGC_RXPBS, I225_RXPBSIZE_DEFAULT);
6748         wr32(IGC_TXPBS, I225_TXPBSIZE_DEFAULT);
6749
6750         timer_setup(&adapter->watchdog_timer, igc_watchdog, 0);
6751         timer_setup(&adapter->phy_info_timer, igc_update_phy_info, 0);
6752
6753         INIT_WORK(&adapter->reset_task, igc_reset_task);
6754         INIT_WORK(&adapter->watchdog_task, igc_watchdog_task);
6755
6756         /* Initialize link properties that are user-changeable */
6757         adapter->fc_autoneg = true;
6758         hw->mac.autoneg = true;
6759         hw->phy.autoneg_advertised = 0xaf;
6760
6761         hw->fc.requested_mode = igc_fc_default;
6762         hw->fc.current_mode = igc_fc_default;
6763
6764         /* By default, support wake on port A */
6765         adapter->flags |= IGC_FLAG_WOL_SUPPORTED;
6766
6767         /* initialize the wol settings based on the eeprom settings */
6768         if (adapter->flags & IGC_FLAG_WOL_SUPPORTED)
6769                 adapter->wol |= IGC_WUFC_MAG;
6770
6771         device_set_wakeup_enable(&adapter->pdev->dev,
6772                                  adapter->flags & IGC_FLAG_WOL_SUPPORTED);
6773
6774         igc_ptp_init(adapter);
6775
6776         igc_tsn_clear_schedule(adapter);
6777
6778         /* reset the hardware with the new settings */
6779         igc_reset(adapter);
6780
6781         /* let the f/w know that the h/w is now under the control of the
6782          * driver.
6783          */
6784         igc_get_hw_control(adapter);
6785
6786         strncpy(netdev->name, "eth%d", IFNAMSIZ);
6787         err = register_netdev(netdev);
6788         if (err)
6789                 goto err_register;
6790
6791          /* carrier off reporting is important to ethtool even BEFORE open */
6792         netif_carrier_off(netdev);
6793
6794         /* Check if Media Autosense is enabled */
6795         adapter->ei = *ei;
6796
6797         /* print pcie link status and MAC address */
6798         pcie_print_link_status(pdev);
6799         netdev_info(netdev, "MAC: %pM\n", netdev->dev_addr);
6800
6801         dev_pm_set_driver_flags(&pdev->dev, DPM_FLAG_NO_DIRECT_COMPLETE);
6802         /* Disable EEE for internal PHY devices */
6803         hw->dev_spec._base.eee_enable = false;
6804         adapter->flags &= ~IGC_FLAG_EEE;
6805         igc_set_eee_i225(hw, false, false, false);
6806
6807         pm_runtime_put_noidle(&pdev->dev);
6808
6809         return 0;
6810
6811 err_register:
6812         igc_release_hw_control(adapter);
6813 err_eeprom:
6814         if (!igc_check_reset_block(hw))
6815                 igc_reset_phy(hw);
6816 err_sw_init:
6817         igc_clear_interrupt_scheme(adapter);
6818         iounmap(adapter->io_addr);
6819 err_ioremap:
6820         free_netdev(netdev);
6821 err_alloc_etherdev:
6822         pci_release_mem_regions(pdev);
6823 err_pci_reg:
6824 err_dma:
6825         pci_disable_device(pdev);
6826         return err;
6827 }
6828
6829 /**
6830  * igc_remove - Device Removal Routine
6831  * @pdev: PCI device information struct
6832  *
6833  * igc_remove is called by the PCI subsystem to alert the driver
6834  * that it should release a PCI device.  This could be caused by a
6835  * Hot-Plug event, or because the driver is going to be removed from
6836  * memory.
6837  */
6838 static void igc_remove(struct pci_dev *pdev)
6839 {
6840         struct net_device *netdev = pci_get_drvdata(pdev);
6841         struct igc_adapter *adapter = netdev_priv(netdev);
6842
6843         pm_runtime_get_noresume(&pdev->dev);
6844
6845         igc_flush_nfc_rules(adapter);
6846
6847         igc_ptp_stop(adapter);
6848
6849         pci_disable_ptm(pdev);
6850         pci_clear_master(pdev);
6851
6852         set_bit(__IGC_DOWN, &adapter->state);
6853
6854         del_timer_sync(&adapter->watchdog_timer);
6855         del_timer_sync(&adapter->phy_info_timer);
6856
6857         cancel_work_sync(&adapter->reset_task);
6858         cancel_work_sync(&adapter->watchdog_task);
6859
6860         /* Release control of h/w to f/w.  If f/w is AMT enabled, this
6861          * would have already happened in close and is redundant.
6862          */
6863         igc_release_hw_control(adapter);
6864         unregister_netdev(netdev);
6865
6866         igc_clear_interrupt_scheme(adapter);
6867         pci_iounmap(pdev, adapter->io_addr);
6868         pci_release_mem_regions(pdev);
6869
6870         free_netdev(netdev);
6871
6872         pci_disable_device(pdev);
6873 }
6874
6875 static int __igc_shutdown(struct pci_dev *pdev, bool *enable_wake,
6876                           bool runtime)
6877 {
6878         struct net_device *netdev = pci_get_drvdata(pdev);
6879         struct igc_adapter *adapter = netdev_priv(netdev);
6880         u32 wufc = runtime ? IGC_WUFC_LNKC : adapter->wol;
6881         struct igc_hw *hw = &adapter->hw;
6882         u32 ctrl, rctl, status;
6883         bool wake;
6884
6885         rtnl_lock();
6886         netif_device_detach(netdev);
6887
6888         if (netif_running(netdev))
6889                 __igc_close(netdev, true);
6890
6891         igc_ptp_suspend(adapter);
6892
6893         igc_clear_interrupt_scheme(adapter);
6894         rtnl_unlock();
6895
6896         status = rd32(IGC_STATUS);
6897         if (status & IGC_STATUS_LU)
6898                 wufc &= ~IGC_WUFC_LNKC;
6899
6900         if (wufc) {
6901                 igc_setup_rctl(adapter);
6902                 igc_set_rx_mode(netdev);
6903
6904                 /* turn on all-multi mode if wake on multicast is enabled */
6905                 if (wufc & IGC_WUFC_MC) {
6906                         rctl = rd32(IGC_RCTL);
6907                         rctl |= IGC_RCTL_MPE;
6908                         wr32(IGC_RCTL, rctl);
6909                 }
6910
6911                 ctrl = rd32(IGC_CTRL);
6912                 ctrl |= IGC_CTRL_ADVD3WUC;
6913                 wr32(IGC_CTRL, ctrl);
6914
6915                 /* Allow time for pending master requests to run */
6916                 igc_disable_pcie_master(hw);
6917
6918                 wr32(IGC_WUC, IGC_WUC_PME_EN);
6919                 wr32(IGC_WUFC, wufc);
6920         } else {
6921                 wr32(IGC_WUC, 0);
6922                 wr32(IGC_WUFC, 0);
6923         }
6924
6925         wake = wufc || adapter->en_mng_pt;
6926         if (!wake)
6927                 igc_power_down_phy_copper_base(&adapter->hw);
6928         else
6929                 igc_power_up_link(adapter);
6930
6931         if (enable_wake)
6932                 *enable_wake = wake;
6933
6934         /* Release control of h/w to f/w.  If f/w is AMT enabled, this
6935          * would have already happened in close and is redundant.
6936          */
6937         igc_release_hw_control(adapter);
6938
6939         pci_disable_device(pdev);
6940
6941         return 0;
6942 }
6943
6944 #ifdef CONFIG_PM
6945 static int __maybe_unused igc_runtime_suspend(struct device *dev)
6946 {
6947         return __igc_shutdown(to_pci_dev(dev), NULL, 1);
6948 }
6949
6950 static void igc_deliver_wake_packet(struct net_device *netdev)
6951 {
6952         struct igc_adapter *adapter = netdev_priv(netdev);
6953         struct igc_hw *hw = &adapter->hw;
6954         struct sk_buff *skb;
6955         u32 wupl;
6956
6957         wupl = rd32(IGC_WUPL) & IGC_WUPL_MASK;
6958
6959         /* WUPM stores only the first 128 bytes of the wake packet.
6960          * Read the packet only if we have the whole thing.
6961          */
6962         if (wupl == 0 || wupl > IGC_WUPM_BYTES)
6963                 return;
6964
6965         skb = netdev_alloc_skb_ip_align(netdev, IGC_WUPM_BYTES);
6966         if (!skb)
6967                 return;
6968
6969         skb_put(skb, wupl);
6970
6971         /* Ensure reads are 32-bit aligned */
6972         wupl = roundup(wupl, 4);
6973
6974         memcpy_fromio(skb->data, hw->hw_addr + IGC_WUPM_REG(0), wupl);
6975
6976         skb->protocol = eth_type_trans(skb, netdev);
6977         netif_rx(skb);
6978 }
6979
6980 static int __maybe_unused igc_resume(struct device *dev)
6981 {
6982         struct pci_dev *pdev = to_pci_dev(dev);
6983         struct net_device *netdev = pci_get_drvdata(pdev);
6984         struct igc_adapter *adapter = netdev_priv(netdev);
6985         struct igc_hw *hw = &adapter->hw;
6986         u32 err, val;
6987
6988         pci_set_power_state(pdev, PCI_D0);
6989         pci_restore_state(pdev);
6990         pci_save_state(pdev);
6991
6992         if (!pci_device_is_present(pdev))
6993                 return -ENODEV;
6994         err = pci_enable_device_mem(pdev);
6995         if (err) {
6996                 netdev_err(netdev, "Cannot enable PCI device from suspend\n");
6997                 return err;
6998         }
6999         pci_set_master(pdev);
7000
7001         pci_enable_wake(pdev, PCI_D3hot, 0);
7002         pci_enable_wake(pdev, PCI_D3cold, 0);
7003
7004         if (igc_init_interrupt_scheme(adapter, true)) {
7005                 netdev_err(netdev, "Unable to allocate memory for queues\n");
7006                 return -ENOMEM;
7007         }
7008
7009         igc_reset(adapter);
7010
7011         /* let the f/w know that the h/w is now under the control of the
7012          * driver.
7013          */
7014         igc_get_hw_control(adapter);
7015
7016         val = rd32(IGC_WUS);
7017         if (val & WAKE_PKT_WUS)
7018                 igc_deliver_wake_packet(netdev);
7019
7020         wr32(IGC_WUS, ~0);
7021
7022         rtnl_lock();
7023         if (!err && netif_running(netdev))
7024                 err = __igc_open(netdev, true);
7025
7026         if (!err)
7027                 netif_device_attach(netdev);
7028         rtnl_unlock();
7029
7030         return err;
7031 }
7032
7033 static int __maybe_unused igc_runtime_resume(struct device *dev)
7034 {
7035         return igc_resume(dev);
7036 }
7037
7038 static int __maybe_unused igc_suspend(struct device *dev)
7039 {
7040         return __igc_shutdown(to_pci_dev(dev), NULL, 0);
7041 }
7042
7043 static int __maybe_unused igc_runtime_idle(struct device *dev)
7044 {
7045         struct net_device *netdev = dev_get_drvdata(dev);
7046         struct igc_adapter *adapter = netdev_priv(netdev);
7047
7048         if (!igc_has_link(adapter))
7049                 pm_schedule_suspend(dev, MSEC_PER_SEC * 5);
7050
7051         return -EBUSY;
7052 }
7053 #endif /* CONFIG_PM */
7054
7055 static void igc_shutdown(struct pci_dev *pdev)
7056 {
7057         bool wake;
7058
7059         __igc_shutdown(pdev, &wake, 0);
7060
7061         if (system_state == SYSTEM_POWER_OFF) {
7062                 pci_wake_from_d3(pdev, wake);
7063                 pci_set_power_state(pdev, PCI_D3hot);
7064         }
7065 }
7066
7067 /**
7068  *  igc_io_error_detected - called when PCI error is detected
7069  *  @pdev: Pointer to PCI device
7070  *  @state: The current PCI connection state
7071  *
7072  *  This function is called after a PCI bus error affecting
7073  *  this device has been detected.
7074  **/
7075 static pci_ers_result_t igc_io_error_detected(struct pci_dev *pdev,
7076                                               pci_channel_state_t state)
7077 {
7078         struct net_device *netdev = pci_get_drvdata(pdev);
7079         struct igc_adapter *adapter = netdev_priv(netdev);
7080
7081         netif_device_detach(netdev);
7082
7083         if (state == pci_channel_io_perm_failure)
7084                 return PCI_ERS_RESULT_DISCONNECT;
7085
7086         if (netif_running(netdev))
7087                 igc_down(adapter);
7088         pci_disable_device(pdev);
7089
7090         /* Request a slot reset. */
7091         return PCI_ERS_RESULT_NEED_RESET;
7092 }
7093
7094 /**
7095  *  igc_io_slot_reset - called after the PCI bus has been reset.
7096  *  @pdev: Pointer to PCI device
7097  *
7098  *  Restart the card from scratch, as if from a cold-boot. Implementation
7099  *  resembles the first-half of the igc_resume routine.
7100  **/
7101 static pci_ers_result_t igc_io_slot_reset(struct pci_dev *pdev)
7102 {
7103         struct net_device *netdev = pci_get_drvdata(pdev);
7104         struct igc_adapter *adapter = netdev_priv(netdev);
7105         struct igc_hw *hw = &adapter->hw;
7106         pci_ers_result_t result;
7107
7108         if (pci_enable_device_mem(pdev)) {
7109                 netdev_err(netdev, "Could not re-enable PCI device after reset\n");
7110                 result = PCI_ERS_RESULT_DISCONNECT;
7111         } else {
7112                 pci_set_master(pdev);
7113                 pci_restore_state(pdev);
7114                 pci_save_state(pdev);
7115
7116                 pci_enable_wake(pdev, PCI_D3hot, 0);
7117                 pci_enable_wake(pdev, PCI_D3cold, 0);
7118
7119                 /* In case of PCI error, adapter loses its HW address
7120                  * so we should re-assign it here.
7121                  */
7122                 hw->hw_addr = adapter->io_addr;
7123
7124                 igc_reset(adapter);
7125                 wr32(IGC_WUS, ~0);
7126                 result = PCI_ERS_RESULT_RECOVERED;
7127         }
7128
7129         return result;
7130 }
7131
7132 /**
7133  *  igc_io_resume - called when traffic can start to flow again.
7134  *  @pdev: Pointer to PCI device
7135  *
7136  *  This callback is called when the error recovery driver tells us that
7137  *  its OK to resume normal operation. Implementation resembles the
7138  *  second-half of the igc_resume routine.
7139  */
7140 static void igc_io_resume(struct pci_dev *pdev)
7141 {
7142         struct net_device *netdev = pci_get_drvdata(pdev);
7143         struct igc_adapter *adapter = netdev_priv(netdev);
7144
7145         rtnl_lock();
7146         if (netif_running(netdev)) {
7147                 if (igc_open(netdev)) {
7148                         netdev_err(netdev, "igc_open failed after reset\n");
7149                         return;
7150                 }
7151         }
7152
7153         netif_device_attach(netdev);
7154
7155         /* let the f/w know that the h/w is now under the control of the
7156          * driver.
7157          */
7158         igc_get_hw_control(adapter);
7159         rtnl_unlock();
7160 }
7161
7162 static const struct pci_error_handlers igc_err_handler = {
7163         .error_detected = igc_io_error_detected,
7164         .slot_reset = igc_io_slot_reset,
7165         .resume = igc_io_resume,
7166 };
7167
7168 #ifdef CONFIG_PM
7169 static const struct dev_pm_ops igc_pm_ops = {
7170         SET_SYSTEM_SLEEP_PM_OPS(igc_suspend, igc_resume)
7171         SET_RUNTIME_PM_OPS(igc_runtime_suspend, igc_runtime_resume,
7172                            igc_runtime_idle)
7173 };
7174 #endif
7175
7176 static struct pci_driver igc_driver = {
7177         .name     = igc_driver_name,
7178         .id_table = igc_pci_tbl,
7179         .probe    = igc_probe,
7180         .remove   = igc_remove,
7181 #ifdef CONFIG_PM
7182         .driver.pm = &igc_pm_ops,
7183 #endif
7184         .shutdown = igc_shutdown,
7185         .err_handler = &igc_err_handler,
7186 };
7187
7188 /**
7189  * igc_reinit_queues - return error
7190  * @adapter: pointer to adapter structure
7191  */
7192 int igc_reinit_queues(struct igc_adapter *adapter)
7193 {
7194         struct net_device *netdev = adapter->netdev;
7195         int err = 0;
7196
7197         if (netif_running(netdev))
7198                 igc_close(netdev);
7199
7200         igc_reset_interrupt_capability(adapter);
7201
7202         if (igc_init_interrupt_scheme(adapter, true)) {
7203                 netdev_err(netdev, "Unable to allocate memory for queues\n");
7204                 return -ENOMEM;
7205         }
7206
7207         if (netif_running(netdev))
7208                 err = igc_open(netdev);
7209
7210         return err;
7211 }
7212
7213 /**
7214  * igc_get_hw_dev - return device
7215  * @hw: pointer to hardware structure
7216  *
7217  * used by hardware layer to print debugging information
7218  */
7219 struct net_device *igc_get_hw_dev(struct igc_hw *hw)
7220 {
7221         struct igc_adapter *adapter = hw->back;
7222
7223         return adapter->netdev;
7224 }
7225
7226 static void igc_disable_rx_ring_hw(struct igc_ring *ring)
7227 {
7228         struct igc_hw *hw = &ring->q_vector->adapter->hw;
7229         u8 idx = ring->reg_idx;
7230         u32 rxdctl;
7231
7232         rxdctl = rd32(IGC_RXDCTL(idx));
7233         rxdctl &= ~IGC_RXDCTL_QUEUE_ENABLE;
7234         rxdctl |= IGC_RXDCTL_SWFLUSH;
7235         wr32(IGC_RXDCTL(idx), rxdctl);
7236 }
7237
7238 void igc_disable_rx_ring(struct igc_ring *ring)
7239 {
7240         igc_disable_rx_ring_hw(ring);
7241         igc_clean_rx_ring(ring);
7242 }
7243
7244 void igc_enable_rx_ring(struct igc_ring *ring)
7245 {
7246         struct igc_adapter *adapter = ring->q_vector->adapter;
7247
7248         igc_configure_rx_ring(adapter, ring);
7249
7250         if (ring->xsk_pool)
7251                 igc_alloc_rx_buffers_zc(ring, igc_desc_unused(ring));
7252         else
7253                 igc_alloc_rx_buffers(ring, igc_desc_unused(ring));
7254 }
7255
7256 static void igc_disable_tx_ring_hw(struct igc_ring *ring)
7257 {
7258         struct igc_hw *hw = &ring->q_vector->adapter->hw;
7259         u8 idx = ring->reg_idx;
7260         u32 txdctl;
7261
7262         txdctl = rd32(IGC_TXDCTL(idx));
7263         txdctl &= ~IGC_TXDCTL_QUEUE_ENABLE;
7264         txdctl |= IGC_TXDCTL_SWFLUSH;
7265         wr32(IGC_TXDCTL(idx), txdctl);
7266 }
7267
7268 void igc_disable_tx_ring(struct igc_ring *ring)
7269 {
7270         igc_disable_tx_ring_hw(ring);
7271         igc_clean_tx_ring(ring);
7272 }
7273
7274 void igc_enable_tx_ring(struct igc_ring *ring)
7275 {
7276         struct igc_adapter *adapter = ring->q_vector->adapter;
7277
7278         igc_configure_tx_ring(adapter, ring);
7279 }
7280
7281 /**
7282  * igc_init_module - Driver Registration Routine
7283  *
7284  * igc_init_module is the first routine called when the driver is
7285  * loaded. All it does is register with the PCI subsystem.
7286  */
7287 static int __init igc_init_module(void)
7288 {
7289         int ret;
7290
7291         pr_info("%s\n", igc_driver_string);
7292         pr_info("%s\n", igc_copyright);
7293
7294         ret = pci_register_driver(&igc_driver);
7295         return ret;
7296 }
7297
7298 module_init(igc_init_module);
7299
7300 /**
7301  * igc_exit_module - Driver Exit Cleanup Routine
7302  *
7303  * igc_exit_module is called just before the driver is removed
7304  * from memory.
7305  */
7306 static void __exit igc_exit_module(void)
7307 {
7308         pci_unregister_driver(&igc_driver);
7309 }
7310
7311 module_exit(igc_exit_module);
7312 /* igc_main.c */
This page took 0.466777 seconds and 4 git commands to generate.