]> git.itanic.dy.fi Git - linux-stable/blob - drivers/net/ethernet/intel/i40e/i40e_main.c
i40e: Fix set max_tx_rate when it is lower than 1 Mbps
[linux-stable] / drivers / net / ethernet / intel / i40e / i40e_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2021 Intel Corporation. */
3
4 #include <linux/etherdevice.h>
5 #include <linux/of_net.h>
6 #include <linux/pci.h>
7 #include <linux/bpf.h>
8 #include <generated/utsrelease.h>
9 #include <linux/crash_dump.h>
10
11 /* Local includes */
12 #include "i40e.h"
13 #include "i40e_diag.h"
14 #include "i40e_xsk.h"
15 #include <net/udp_tunnel.h>
16 #include <net/xdp_sock_drv.h>
17 /* All i40e tracepoints are defined by the include below, which
18  * must be included exactly once across the whole kernel with
19  * CREATE_TRACE_POINTS defined
20  */
21 #define CREATE_TRACE_POINTS
22 #include "i40e_trace.h"
23
24 const char i40e_driver_name[] = "i40e";
25 static const char i40e_driver_string[] =
26                         "Intel(R) Ethernet Connection XL710 Network Driver";
27
28 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
29
30 /* a bit of forward declarations */
31 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
32 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
33 static int i40e_add_vsi(struct i40e_vsi *vsi);
34 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
35 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
36 static int i40e_setup_misc_vector(struct i40e_pf *pf);
37 static void i40e_determine_queue_usage(struct i40e_pf *pf);
38 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
39 static void i40e_prep_for_reset(struct i40e_pf *pf);
40 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
41                                    bool lock_acquired);
42 static int i40e_reset(struct i40e_pf *pf);
43 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
44 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
45 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
46 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
47 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
48 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
49 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
50 static int i40e_get_capabilities(struct i40e_pf *pf,
51                                  enum i40e_admin_queue_opc list_type);
52 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
53
54 /* i40e_pci_tbl - PCI Device ID Table
55  *
56  * Last entry must be all 0s
57  *
58  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
59  *   Class, Class Mask, private data (not used) }
60  */
61 static const struct pci_device_id i40e_pci_tbl[] = {
62         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
63         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
64         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
65         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
66         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
67         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
68         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
69         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
70         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
71         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
72         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
73         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
74         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
75         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
76         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
77         {PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
78         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
79         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
80         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
81         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
82         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
83         {PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
84         {PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
85         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
86         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
87         /* required last entry */
88         {0, }
89 };
90 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
91
92 #define I40E_MAX_VF_COUNT 128
93 static int debug = -1;
94 module_param(debug, uint, 0);
95 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
96
97 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
98 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
99 MODULE_LICENSE("GPL v2");
100
101 static struct workqueue_struct *i40e_wq;
102
103 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
104                                   struct net_device *netdev, int delta)
105 {
106         struct netdev_hw_addr *ha;
107
108         if (!f || !netdev)
109                 return;
110
111         netdev_for_each_mc_addr(ha, netdev) {
112                 if (ether_addr_equal(ha->addr, f->macaddr)) {
113                         ha->refcount += delta;
114                         if (ha->refcount <= 0)
115                                 ha->refcount = 1;
116                         break;
117                 }
118         }
119 }
120
121 /**
122  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
123  * @hw:   pointer to the HW structure
124  * @mem:  ptr to mem struct to fill out
125  * @size: size of memory requested
126  * @alignment: what to align the allocation to
127  **/
128 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
129                             u64 size, u32 alignment)
130 {
131         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
132
133         mem->size = ALIGN(size, alignment);
134         mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
135                                      GFP_KERNEL);
136         if (!mem->va)
137                 return -ENOMEM;
138
139         return 0;
140 }
141
142 /**
143  * i40e_free_dma_mem_d - OS specific memory free for shared code
144  * @hw:   pointer to the HW structure
145  * @mem:  ptr to mem struct to free
146  **/
147 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
148 {
149         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
150
151         dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
152         mem->va = NULL;
153         mem->pa = 0;
154         mem->size = 0;
155
156         return 0;
157 }
158
159 /**
160  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
161  * @hw:   pointer to the HW structure
162  * @mem:  ptr to mem struct to fill out
163  * @size: size of memory requested
164  **/
165 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
166                              u32 size)
167 {
168         mem->size = size;
169         mem->va = kzalloc(size, GFP_KERNEL);
170
171         if (!mem->va)
172                 return -ENOMEM;
173
174         return 0;
175 }
176
177 /**
178  * i40e_free_virt_mem_d - OS specific memory free for shared code
179  * @hw:   pointer to the HW structure
180  * @mem:  ptr to mem struct to free
181  **/
182 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
183 {
184         /* it's ok to kfree a NULL pointer */
185         kfree(mem->va);
186         mem->va = NULL;
187         mem->size = 0;
188
189         return 0;
190 }
191
192 /**
193  * i40e_get_lump - find a lump of free generic resource
194  * @pf: board private structure
195  * @pile: the pile of resource to search
196  * @needed: the number of items needed
197  * @id: an owner id to stick on the items assigned
198  *
199  * Returns the base item index of the lump, or negative for error
200  **/
201 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
202                          u16 needed, u16 id)
203 {
204         int ret = -ENOMEM;
205         int i, j;
206
207         if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
208                 dev_info(&pf->pdev->dev,
209                          "param err: pile=%s needed=%d id=0x%04x\n",
210                          pile ? "<valid>" : "<null>", needed, id);
211                 return -EINVAL;
212         }
213
214         /* Allocate last queue in the pile for FDIR VSI queue
215          * so it doesn't fragment the qp_pile
216          */
217         if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
218                 if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
219                         dev_err(&pf->pdev->dev,
220                                 "Cannot allocate queue %d for I40E_VSI_FDIR\n",
221                                 pile->num_entries - 1);
222                         return -ENOMEM;
223                 }
224                 pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
225                 return pile->num_entries - 1;
226         }
227
228         i = 0;
229         while (i < pile->num_entries) {
230                 /* skip already allocated entries */
231                 if (pile->list[i] & I40E_PILE_VALID_BIT) {
232                         i++;
233                         continue;
234                 }
235
236                 /* do we have enough in this lump? */
237                 for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
238                         if (pile->list[i+j] & I40E_PILE_VALID_BIT)
239                                 break;
240                 }
241
242                 if (j == needed) {
243                         /* there was enough, so assign it to the requestor */
244                         for (j = 0; j < needed; j++)
245                                 pile->list[i+j] = id | I40E_PILE_VALID_BIT;
246                         ret = i;
247                         break;
248                 }
249
250                 /* not enough, so skip over it and continue looking */
251                 i += j;
252         }
253
254         return ret;
255 }
256
257 /**
258  * i40e_put_lump - return a lump of generic resource
259  * @pile: the pile of resource to search
260  * @index: the base item index
261  * @id: the owner id of the items assigned
262  *
263  * Returns the count of items in the lump
264  **/
265 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
266 {
267         int valid_id = (id | I40E_PILE_VALID_BIT);
268         int count = 0;
269         u16 i;
270
271         if (!pile || index >= pile->num_entries)
272                 return -EINVAL;
273
274         for (i = index;
275              i < pile->num_entries && pile->list[i] == valid_id;
276              i++) {
277                 pile->list[i] = 0;
278                 count++;
279         }
280
281
282         return count;
283 }
284
285 /**
286  * i40e_find_vsi_from_id - searches for the vsi with the given id
287  * @pf: the pf structure to search for the vsi
288  * @id: id of the vsi it is searching for
289  **/
290 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
291 {
292         int i;
293
294         for (i = 0; i < pf->num_alloc_vsi; i++)
295                 if (pf->vsi[i] && (pf->vsi[i]->id == id))
296                         return pf->vsi[i];
297
298         return NULL;
299 }
300
301 /**
302  * i40e_service_event_schedule - Schedule the service task to wake up
303  * @pf: board private structure
304  *
305  * If not already scheduled, this puts the task into the work queue
306  **/
307 void i40e_service_event_schedule(struct i40e_pf *pf)
308 {
309         if ((!test_bit(__I40E_DOWN, pf->state) &&
310              !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
311               test_bit(__I40E_RECOVERY_MODE, pf->state))
312                 queue_work(i40e_wq, &pf->service_task);
313 }
314
315 /**
316  * i40e_tx_timeout - Respond to a Tx Hang
317  * @netdev: network interface device structure
318  * @txqueue: queue number timing out
319  *
320  * If any port has noticed a Tx timeout, it is likely that the whole
321  * device is munged, not just the one netdev port, so go for the full
322  * reset.
323  **/
324 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
325 {
326         struct i40e_netdev_priv *np = netdev_priv(netdev);
327         struct i40e_vsi *vsi = np->vsi;
328         struct i40e_pf *pf = vsi->back;
329         struct i40e_ring *tx_ring = NULL;
330         unsigned int i;
331         u32 head, val;
332
333         pf->tx_timeout_count++;
334
335         /* with txqueue index, find the tx_ring struct */
336         for (i = 0; i < vsi->num_queue_pairs; i++) {
337                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
338                         if (txqueue ==
339                             vsi->tx_rings[i]->queue_index) {
340                                 tx_ring = vsi->tx_rings[i];
341                                 break;
342                         }
343                 }
344         }
345
346         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
347                 pf->tx_timeout_recovery_level = 1;  /* reset after some time */
348         else if (time_before(jiffies,
349                       (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
350                 return;   /* don't do any new action before the next timeout */
351
352         /* don't kick off another recovery if one is already pending */
353         if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
354                 return;
355
356         if (tx_ring) {
357                 head = i40e_get_head(tx_ring);
358                 /* Read interrupt register */
359                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
360                         val = rd32(&pf->hw,
361                              I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
362                                                 tx_ring->vsi->base_vector - 1));
363                 else
364                         val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
365
366                 netdev_info(netdev, "tx_timeout: VSI_seid: %d, Q %d, NTC: 0x%x, HWB: 0x%x, NTU: 0x%x, TAIL: 0x%x, INT: 0x%x\n",
367                             vsi->seid, txqueue, tx_ring->next_to_clean,
368                             head, tx_ring->next_to_use,
369                             readl(tx_ring->tail), val);
370         }
371
372         pf->tx_timeout_last_recovery = jiffies;
373         netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
374                     pf->tx_timeout_recovery_level, txqueue);
375
376         switch (pf->tx_timeout_recovery_level) {
377         case 1:
378                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
379                 break;
380         case 2:
381                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
382                 break;
383         case 3:
384                 set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
385                 break;
386         default:
387                 netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
388                 set_bit(__I40E_DOWN_REQUESTED, pf->state);
389                 set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
390                 break;
391         }
392
393         i40e_service_event_schedule(pf);
394         pf->tx_timeout_recovery_level++;
395 }
396
397 /**
398  * i40e_get_vsi_stats_struct - Get System Network Statistics
399  * @vsi: the VSI we care about
400  *
401  * Returns the address of the device statistics structure.
402  * The statistics are actually updated from the service task.
403  **/
404 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
405 {
406         return &vsi->net_stats;
407 }
408
409 /**
410  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
411  * @ring: Tx ring to get statistics from
412  * @stats: statistics entry to be updated
413  **/
414 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
415                                             struct rtnl_link_stats64 *stats)
416 {
417         u64 bytes, packets;
418         unsigned int start;
419
420         do {
421                 start = u64_stats_fetch_begin_irq(&ring->syncp);
422                 packets = ring->stats.packets;
423                 bytes   = ring->stats.bytes;
424         } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
425
426         stats->tx_packets += packets;
427         stats->tx_bytes   += bytes;
428 }
429
430 /**
431  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
432  * @netdev: network interface device structure
433  * @stats: data structure to store statistics
434  *
435  * Returns the address of the device statistics structure.
436  * The statistics are actually updated from the service task.
437  **/
438 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
439                                   struct rtnl_link_stats64 *stats)
440 {
441         struct i40e_netdev_priv *np = netdev_priv(netdev);
442         struct i40e_vsi *vsi = np->vsi;
443         struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
444         struct i40e_ring *ring;
445         int i;
446
447         if (test_bit(__I40E_VSI_DOWN, vsi->state))
448                 return;
449
450         if (!vsi->tx_rings)
451                 return;
452
453         rcu_read_lock();
454         for (i = 0; i < vsi->num_queue_pairs; i++) {
455                 u64 bytes, packets;
456                 unsigned int start;
457
458                 ring = READ_ONCE(vsi->tx_rings[i]);
459                 if (!ring)
460                         continue;
461                 i40e_get_netdev_stats_struct_tx(ring, stats);
462
463                 if (i40e_enabled_xdp_vsi(vsi)) {
464                         ring = READ_ONCE(vsi->xdp_rings[i]);
465                         if (!ring)
466                                 continue;
467                         i40e_get_netdev_stats_struct_tx(ring, stats);
468                 }
469
470                 ring = READ_ONCE(vsi->rx_rings[i]);
471                 if (!ring)
472                         continue;
473                 do {
474                         start   = u64_stats_fetch_begin_irq(&ring->syncp);
475                         packets = ring->stats.packets;
476                         bytes   = ring->stats.bytes;
477                 } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
478
479                 stats->rx_packets += packets;
480                 stats->rx_bytes   += bytes;
481
482         }
483         rcu_read_unlock();
484
485         /* following stats updated by i40e_watchdog_subtask() */
486         stats->multicast        = vsi_stats->multicast;
487         stats->tx_errors        = vsi_stats->tx_errors;
488         stats->tx_dropped       = vsi_stats->tx_dropped;
489         stats->rx_errors        = vsi_stats->rx_errors;
490         stats->rx_dropped       = vsi_stats->rx_dropped;
491         stats->rx_crc_errors    = vsi_stats->rx_crc_errors;
492         stats->rx_length_errors = vsi_stats->rx_length_errors;
493 }
494
495 /**
496  * i40e_vsi_reset_stats - Resets all stats of the given vsi
497  * @vsi: the VSI to have its stats reset
498  **/
499 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
500 {
501         struct rtnl_link_stats64 *ns;
502         int i;
503
504         if (!vsi)
505                 return;
506
507         ns = i40e_get_vsi_stats_struct(vsi);
508         memset(ns, 0, sizeof(*ns));
509         memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
510         memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
511         memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
512         if (vsi->rx_rings && vsi->rx_rings[0]) {
513                 for (i = 0; i < vsi->num_queue_pairs; i++) {
514                         memset(&vsi->rx_rings[i]->stats, 0,
515                                sizeof(vsi->rx_rings[i]->stats));
516                         memset(&vsi->rx_rings[i]->rx_stats, 0,
517                                sizeof(vsi->rx_rings[i]->rx_stats));
518                         memset(&vsi->tx_rings[i]->stats, 0,
519                                sizeof(vsi->tx_rings[i]->stats));
520                         memset(&vsi->tx_rings[i]->tx_stats, 0,
521                                sizeof(vsi->tx_rings[i]->tx_stats));
522                 }
523         }
524         vsi->stat_offsets_loaded = false;
525 }
526
527 /**
528  * i40e_pf_reset_stats - Reset all of the stats for the given PF
529  * @pf: the PF to be reset
530  **/
531 void i40e_pf_reset_stats(struct i40e_pf *pf)
532 {
533         int i;
534
535         memset(&pf->stats, 0, sizeof(pf->stats));
536         memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
537         pf->stat_offsets_loaded = false;
538
539         for (i = 0; i < I40E_MAX_VEB; i++) {
540                 if (pf->veb[i]) {
541                         memset(&pf->veb[i]->stats, 0,
542                                sizeof(pf->veb[i]->stats));
543                         memset(&pf->veb[i]->stats_offsets, 0,
544                                sizeof(pf->veb[i]->stats_offsets));
545                         memset(&pf->veb[i]->tc_stats, 0,
546                                sizeof(pf->veb[i]->tc_stats));
547                         memset(&pf->veb[i]->tc_stats_offsets, 0,
548                                sizeof(pf->veb[i]->tc_stats_offsets));
549                         pf->veb[i]->stat_offsets_loaded = false;
550                 }
551         }
552         pf->hw_csum_rx_error = 0;
553 }
554
555 /**
556  * i40e_compute_pci_to_hw_id - compute index form PCI function.
557  * @vsi: ptr to the VSI to read from.
558  * @hw: ptr to the hardware info.
559  **/
560 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
561 {
562         int pf_count = i40e_get_pf_count(hw);
563
564         if (vsi->type == I40E_VSI_SRIOV)
565                 return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
566
567         return hw->port + BIT(7);
568 }
569
570 /**
571  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
572  * @hw: ptr to the hardware info.
573  * @hireg: the high 32 bit reg to read.
574  * @loreg: the low 32 bit reg to read.
575  * @offset_loaded: has the initial offset been loaded yet.
576  * @offset: ptr to current offset value.
577  * @stat: ptr to the stat.
578  *
579  * Since the device stats are not reset at PFReset, they will not
580  * be zeroed when the driver starts.  We'll save the first values read
581  * and use them as offsets to be subtracted from the raw values in order
582  * to report stats that count from zero.
583  **/
584 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
585                                bool offset_loaded, u64 *offset, u64 *stat)
586 {
587         u64 new_data;
588
589         new_data = rd64(hw, loreg);
590
591         if (!offset_loaded || new_data < *offset)
592                 *offset = new_data;
593         *stat = new_data - *offset;
594 }
595
596 /**
597  * i40e_stat_update48 - read and update a 48 bit stat from the chip
598  * @hw: ptr to the hardware info
599  * @hireg: the high 32 bit reg to read
600  * @loreg: the low 32 bit reg to read
601  * @offset_loaded: has the initial offset been loaded yet
602  * @offset: ptr to current offset value
603  * @stat: ptr to the stat
604  *
605  * Since the device stats are not reset at PFReset, they likely will not
606  * be zeroed when the driver starts.  We'll save the first values read
607  * and use them as offsets to be subtracted from the raw values in order
608  * to report stats that count from zero.  In the process, we also manage
609  * the potential roll-over.
610  **/
611 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
612                                bool offset_loaded, u64 *offset, u64 *stat)
613 {
614         u64 new_data;
615
616         if (hw->device_id == I40E_DEV_ID_QEMU) {
617                 new_data = rd32(hw, loreg);
618                 new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
619         } else {
620                 new_data = rd64(hw, loreg);
621         }
622         if (!offset_loaded)
623                 *offset = new_data;
624         if (likely(new_data >= *offset))
625                 *stat = new_data - *offset;
626         else
627                 *stat = (new_data + BIT_ULL(48)) - *offset;
628         *stat &= 0xFFFFFFFFFFFFULL;
629 }
630
631 /**
632  * i40e_stat_update32 - read and update a 32 bit stat from the chip
633  * @hw: ptr to the hardware info
634  * @reg: the hw reg to read
635  * @offset_loaded: has the initial offset been loaded yet
636  * @offset: ptr to current offset value
637  * @stat: ptr to the stat
638  **/
639 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
640                                bool offset_loaded, u64 *offset, u64 *stat)
641 {
642         u32 new_data;
643
644         new_data = rd32(hw, reg);
645         if (!offset_loaded)
646                 *offset = new_data;
647         if (likely(new_data >= *offset))
648                 *stat = (u32)(new_data - *offset);
649         else
650                 *stat = (u32)((new_data + BIT_ULL(32)) - *offset);
651 }
652
653 /**
654  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
655  * @hw: ptr to the hardware info
656  * @reg: the hw reg to read and clear
657  * @stat: ptr to the stat
658  **/
659 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
660 {
661         u32 new_data = rd32(hw, reg);
662
663         wr32(hw, reg, 1); /* must write a nonzero value to clear register */
664         *stat += new_data;
665 }
666
667 /**
668  * i40e_stats_update_rx_discards - update rx_discards.
669  * @vsi: ptr to the VSI to be updated.
670  * @hw: ptr to the hardware info.
671  * @stat_idx: VSI's stat_counter_idx.
672  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
673  * @stat_offset: ptr to stat_offset to store first read of specific register.
674  * @stat: ptr to VSI's stat to be updated.
675  **/
676 static void
677 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
678                               int stat_idx, bool offset_loaded,
679                               struct i40e_eth_stats *stat_offset,
680                               struct i40e_eth_stats *stat)
681 {
682         u64 rx_rdpc, rx_rxerr;
683
684         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
685                            &stat_offset->rx_discards, &rx_rdpc);
686         i40e_stat_update64(hw,
687                            I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
688                            I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
689                            offset_loaded, &stat_offset->rx_discards_other,
690                            &rx_rxerr);
691
692         stat->rx_discards = rx_rdpc + rx_rxerr;
693 }
694
695 /**
696  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
697  * @vsi: the VSI to be updated
698  **/
699 void i40e_update_eth_stats(struct i40e_vsi *vsi)
700 {
701         int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
702         struct i40e_pf *pf = vsi->back;
703         struct i40e_hw *hw = &pf->hw;
704         struct i40e_eth_stats *oes;
705         struct i40e_eth_stats *es;     /* device's eth stats */
706
707         es = &vsi->eth_stats;
708         oes = &vsi->eth_stats_offsets;
709
710         /* Gather up the stats that the hw collects */
711         i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
712                            vsi->stat_offsets_loaded,
713                            &oes->tx_errors, &es->tx_errors);
714         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
715                            vsi->stat_offsets_loaded,
716                            &oes->rx_discards, &es->rx_discards);
717         i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
718                            vsi->stat_offsets_loaded,
719                            &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
720
721         i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
722                            I40E_GLV_GORCL(stat_idx),
723                            vsi->stat_offsets_loaded,
724                            &oes->rx_bytes, &es->rx_bytes);
725         i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
726                            I40E_GLV_UPRCL(stat_idx),
727                            vsi->stat_offsets_loaded,
728                            &oes->rx_unicast, &es->rx_unicast);
729         i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
730                            I40E_GLV_MPRCL(stat_idx),
731                            vsi->stat_offsets_loaded,
732                            &oes->rx_multicast, &es->rx_multicast);
733         i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
734                            I40E_GLV_BPRCL(stat_idx),
735                            vsi->stat_offsets_loaded,
736                            &oes->rx_broadcast, &es->rx_broadcast);
737
738         i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
739                            I40E_GLV_GOTCL(stat_idx),
740                            vsi->stat_offsets_loaded,
741                            &oes->tx_bytes, &es->tx_bytes);
742         i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
743                            I40E_GLV_UPTCL(stat_idx),
744                            vsi->stat_offsets_loaded,
745                            &oes->tx_unicast, &es->tx_unicast);
746         i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
747                            I40E_GLV_MPTCL(stat_idx),
748                            vsi->stat_offsets_loaded,
749                            &oes->tx_multicast, &es->tx_multicast);
750         i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
751                            I40E_GLV_BPTCL(stat_idx),
752                            vsi->stat_offsets_loaded,
753                            &oes->tx_broadcast, &es->tx_broadcast);
754
755         i40e_stats_update_rx_discards(vsi, hw, stat_idx,
756                                       vsi->stat_offsets_loaded, oes, es);
757
758         vsi->stat_offsets_loaded = true;
759 }
760
761 /**
762  * i40e_update_veb_stats - Update Switch component statistics
763  * @veb: the VEB being updated
764  **/
765 void i40e_update_veb_stats(struct i40e_veb *veb)
766 {
767         struct i40e_pf *pf = veb->pf;
768         struct i40e_hw *hw = &pf->hw;
769         struct i40e_eth_stats *oes;
770         struct i40e_eth_stats *es;     /* device's eth stats */
771         struct i40e_veb_tc_stats *veb_oes;
772         struct i40e_veb_tc_stats *veb_es;
773         int i, idx = 0;
774
775         idx = veb->stats_idx;
776         es = &veb->stats;
777         oes = &veb->stats_offsets;
778         veb_es = &veb->tc_stats;
779         veb_oes = &veb->tc_stats_offsets;
780
781         /* Gather up the stats that the hw collects */
782         i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
783                            veb->stat_offsets_loaded,
784                            &oes->tx_discards, &es->tx_discards);
785         if (hw->revision_id > 0)
786                 i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
787                                    veb->stat_offsets_loaded,
788                                    &oes->rx_unknown_protocol,
789                                    &es->rx_unknown_protocol);
790         i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
791                            veb->stat_offsets_loaded,
792                            &oes->rx_bytes, &es->rx_bytes);
793         i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
794                            veb->stat_offsets_loaded,
795                            &oes->rx_unicast, &es->rx_unicast);
796         i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
797                            veb->stat_offsets_loaded,
798                            &oes->rx_multicast, &es->rx_multicast);
799         i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
800                            veb->stat_offsets_loaded,
801                            &oes->rx_broadcast, &es->rx_broadcast);
802
803         i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
804                            veb->stat_offsets_loaded,
805                            &oes->tx_bytes, &es->tx_bytes);
806         i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
807                            veb->stat_offsets_loaded,
808                            &oes->tx_unicast, &es->tx_unicast);
809         i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
810                            veb->stat_offsets_loaded,
811                            &oes->tx_multicast, &es->tx_multicast);
812         i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
813                            veb->stat_offsets_loaded,
814                            &oes->tx_broadcast, &es->tx_broadcast);
815         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
816                 i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
817                                    I40E_GLVEBTC_RPCL(i, idx),
818                                    veb->stat_offsets_loaded,
819                                    &veb_oes->tc_rx_packets[i],
820                                    &veb_es->tc_rx_packets[i]);
821                 i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
822                                    I40E_GLVEBTC_RBCL(i, idx),
823                                    veb->stat_offsets_loaded,
824                                    &veb_oes->tc_rx_bytes[i],
825                                    &veb_es->tc_rx_bytes[i]);
826                 i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
827                                    I40E_GLVEBTC_TPCL(i, idx),
828                                    veb->stat_offsets_loaded,
829                                    &veb_oes->tc_tx_packets[i],
830                                    &veb_es->tc_tx_packets[i]);
831                 i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
832                                    I40E_GLVEBTC_TBCL(i, idx),
833                                    veb->stat_offsets_loaded,
834                                    &veb_oes->tc_tx_bytes[i],
835                                    &veb_es->tc_tx_bytes[i]);
836         }
837         veb->stat_offsets_loaded = true;
838 }
839
840 /**
841  * i40e_update_vsi_stats - Update the vsi statistics counters.
842  * @vsi: the VSI to be updated
843  *
844  * There are a few instances where we store the same stat in a
845  * couple of different structs.  This is partly because we have
846  * the netdev stats that need to be filled out, which is slightly
847  * different from the "eth_stats" defined by the chip and used in
848  * VF communications.  We sort it out here.
849  **/
850 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
851 {
852         u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
853         struct i40e_pf *pf = vsi->back;
854         struct rtnl_link_stats64 *ons;
855         struct rtnl_link_stats64 *ns;   /* netdev stats */
856         struct i40e_eth_stats *oes;
857         struct i40e_eth_stats *es;     /* device's eth stats */
858         u64 tx_restart, tx_busy;
859         struct i40e_ring *p;
860         u64 bytes, packets;
861         unsigned int start;
862         u64 tx_linearize;
863         u64 tx_force_wb;
864         u64 tx_stopped;
865         u64 rx_p, rx_b;
866         u64 tx_p, tx_b;
867         u16 q;
868
869         if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
870             test_bit(__I40E_CONFIG_BUSY, pf->state))
871                 return;
872
873         ns = i40e_get_vsi_stats_struct(vsi);
874         ons = &vsi->net_stats_offsets;
875         es = &vsi->eth_stats;
876         oes = &vsi->eth_stats_offsets;
877
878         /* Gather up the netdev and vsi stats that the driver collects
879          * on the fly during packet processing
880          */
881         rx_b = rx_p = 0;
882         tx_b = tx_p = 0;
883         tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
884         tx_stopped = 0;
885         rx_page = 0;
886         rx_buf = 0;
887         rx_reuse = 0;
888         rx_alloc = 0;
889         rx_waive = 0;
890         rx_busy = 0;
891         rcu_read_lock();
892         for (q = 0; q < vsi->num_queue_pairs; q++) {
893                 /* locate Tx ring */
894                 p = READ_ONCE(vsi->tx_rings[q]);
895                 if (!p)
896                         continue;
897
898                 do {
899                         start = u64_stats_fetch_begin_irq(&p->syncp);
900                         packets = p->stats.packets;
901                         bytes = p->stats.bytes;
902                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
903                 tx_b += bytes;
904                 tx_p += packets;
905                 tx_restart += p->tx_stats.restart_queue;
906                 tx_busy += p->tx_stats.tx_busy;
907                 tx_linearize += p->tx_stats.tx_linearize;
908                 tx_force_wb += p->tx_stats.tx_force_wb;
909                 tx_stopped += p->tx_stats.tx_stopped;
910
911                 /* locate Rx ring */
912                 p = READ_ONCE(vsi->rx_rings[q]);
913                 if (!p)
914                         continue;
915
916                 do {
917                         start = u64_stats_fetch_begin_irq(&p->syncp);
918                         packets = p->stats.packets;
919                         bytes = p->stats.bytes;
920                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
921                 rx_b += bytes;
922                 rx_p += packets;
923                 rx_buf += p->rx_stats.alloc_buff_failed;
924                 rx_page += p->rx_stats.alloc_page_failed;
925                 rx_reuse += p->rx_stats.page_reuse_count;
926                 rx_alloc += p->rx_stats.page_alloc_count;
927                 rx_waive += p->rx_stats.page_waive_count;
928                 rx_busy += p->rx_stats.page_busy_count;
929
930                 if (i40e_enabled_xdp_vsi(vsi)) {
931                         /* locate XDP ring */
932                         p = READ_ONCE(vsi->xdp_rings[q]);
933                         if (!p)
934                                 continue;
935
936                         do {
937                                 start = u64_stats_fetch_begin_irq(&p->syncp);
938                                 packets = p->stats.packets;
939                                 bytes = p->stats.bytes;
940                         } while (u64_stats_fetch_retry_irq(&p->syncp, start));
941                         tx_b += bytes;
942                         tx_p += packets;
943                         tx_restart += p->tx_stats.restart_queue;
944                         tx_busy += p->tx_stats.tx_busy;
945                         tx_linearize += p->tx_stats.tx_linearize;
946                         tx_force_wb += p->tx_stats.tx_force_wb;
947                 }
948         }
949         rcu_read_unlock();
950         vsi->tx_restart = tx_restart;
951         vsi->tx_busy = tx_busy;
952         vsi->tx_linearize = tx_linearize;
953         vsi->tx_force_wb = tx_force_wb;
954         vsi->tx_stopped = tx_stopped;
955         vsi->rx_page_failed = rx_page;
956         vsi->rx_buf_failed = rx_buf;
957         vsi->rx_page_reuse = rx_reuse;
958         vsi->rx_page_alloc = rx_alloc;
959         vsi->rx_page_waive = rx_waive;
960         vsi->rx_page_busy = rx_busy;
961
962         ns->rx_packets = rx_p;
963         ns->rx_bytes = rx_b;
964         ns->tx_packets = tx_p;
965         ns->tx_bytes = tx_b;
966
967         /* update netdev stats from eth stats */
968         i40e_update_eth_stats(vsi);
969         ons->tx_errors = oes->tx_errors;
970         ns->tx_errors = es->tx_errors;
971         ons->multicast = oes->rx_multicast;
972         ns->multicast = es->rx_multicast;
973         ons->rx_dropped = oes->rx_discards;
974         ns->rx_dropped = es->rx_discards;
975         ons->tx_dropped = oes->tx_discards;
976         ns->tx_dropped = es->tx_discards;
977
978         /* pull in a couple PF stats if this is the main vsi */
979         if (vsi == pf->vsi[pf->lan_vsi]) {
980                 ns->rx_crc_errors = pf->stats.crc_errors;
981                 ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
982                 ns->rx_length_errors = pf->stats.rx_length_errors;
983         }
984 }
985
986 /**
987  * i40e_update_pf_stats - Update the PF statistics counters.
988  * @pf: the PF to be updated
989  **/
990 static void i40e_update_pf_stats(struct i40e_pf *pf)
991 {
992         struct i40e_hw_port_stats *osd = &pf->stats_offsets;
993         struct i40e_hw_port_stats *nsd = &pf->stats;
994         struct i40e_hw *hw = &pf->hw;
995         u32 val;
996         int i;
997
998         i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
999                            I40E_GLPRT_GORCL(hw->port),
1000                            pf->stat_offsets_loaded,
1001                            &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1002         i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1003                            I40E_GLPRT_GOTCL(hw->port),
1004                            pf->stat_offsets_loaded,
1005                            &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1006         i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1007                            pf->stat_offsets_loaded,
1008                            &osd->eth.rx_discards,
1009                            &nsd->eth.rx_discards);
1010         i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1011                            I40E_GLPRT_UPRCL(hw->port),
1012                            pf->stat_offsets_loaded,
1013                            &osd->eth.rx_unicast,
1014                            &nsd->eth.rx_unicast);
1015         i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1016                            I40E_GLPRT_MPRCL(hw->port),
1017                            pf->stat_offsets_loaded,
1018                            &osd->eth.rx_multicast,
1019                            &nsd->eth.rx_multicast);
1020         i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1021                            I40E_GLPRT_BPRCL(hw->port),
1022                            pf->stat_offsets_loaded,
1023                            &osd->eth.rx_broadcast,
1024                            &nsd->eth.rx_broadcast);
1025         i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1026                            I40E_GLPRT_UPTCL(hw->port),
1027                            pf->stat_offsets_loaded,
1028                            &osd->eth.tx_unicast,
1029                            &nsd->eth.tx_unicast);
1030         i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1031                            I40E_GLPRT_MPTCL(hw->port),
1032                            pf->stat_offsets_loaded,
1033                            &osd->eth.tx_multicast,
1034                            &nsd->eth.tx_multicast);
1035         i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1036                            I40E_GLPRT_BPTCL(hw->port),
1037                            pf->stat_offsets_loaded,
1038                            &osd->eth.tx_broadcast,
1039                            &nsd->eth.tx_broadcast);
1040
1041         i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1042                            pf->stat_offsets_loaded,
1043                            &osd->tx_dropped_link_down,
1044                            &nsd->tx_dropped_link_down);
1045
1046         i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1047                            pf->stat_offsets_loaded,
1048                            &osd->crc_errors, &nsd->crc_errors);
1049
1050         i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1051                            pf->stat_offsets_loaded,
1052                            &osd->illegal_bytes, &nsd->illegal_bytes);
1053
1054         i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1055                            pf->stat_offsets_loaded,
1056                            &osd->mac_local_faults,
1057                            &nsd->mac_local_faults);
1058         i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1059                            pf->stat_offsets_loaded,
1060                            &osd->mac_remote_faults,
1061                            &nsd->mac_remote_faults);
1062
1063         i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1064                            pf->stat_offsets_loaded,
1065                            &osd->rx_length_errors,
1066                            &nsd->rx_length_errors);
1067
1068         i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1069                            pf->stat_offsets_loaded,
1070                            &osd->link_xon_rx, &nsd->link_xon_rx);
1071         i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1072                            pf->stat_offsets_loaded,
1073                            &osd->link_xon_tx, &nsd->link_xon_tx);
1074         i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1075                            pf->stat_offsets_loaded,
1076                            &osd->link_xoff_rx, &nsd->link_xoff_rx);
1077         i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1078                            pf->stat_offsets_loaded,
1079                            &osd->link_xoff_tx, &nsd->link_xoff_tx);
1080
1081         for (i = 0; i < 8; i++) {
1082                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1083                                    pf->stat_offsets_loaded,
1084                                    &osd->priority_xoff_rx[i],
1085                                    &nsd->priority_xoff_rx[i]);
1086                 i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1087                                    pf->stat_offsets_loaded,
1088                                    &osd->priority_xon_rx[i],
1089                                    &nsd->priority_xon_rx[i]);
1090                 i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1091                                    pf->stat_offsets_loaded,
1092                                    &osd->priority_xon_tx[i],
1093                                    &nsd->priority_xon_tx[i]);
1094                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1095                                    pf->stat_offsets_loaded,
1096                                    &osd->priority_xoff_tx[i],
1097                                    &nsd->priority_xoff_tx[i]);
1098                 i40e_stat_update32(hw,
1099                                    I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1100                                    pf->stat_offsets_loaded,
1101                                    &osd->priority_xon_2_xoff[i],
1102                                    &nsd->priority_xon_2_xoff[i]);
1103         }
1104
1105         i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1106                            I40E_GLPRT_PRC64L(hw->port),
1107                            pf->stat_offsets_loaded,
1108                            &osd->rx_size_64, &nsd->rx_size_64);
1109         i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1110                            I40E_GLPRT_PRC127L(hw->port),
1111                            pf->stat_offsets_loaded,
1112                            &osd->rx_size_127, &nsd->rx_size_127);
1113         i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1114                            I40E_GLPRT_PRC255L(hw->port),
1115                            pf->stat_offsets_loaded,
1116                            &osd->rx_size_255, &nsd->rx_size_255);
1117         i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1118                            I40E_GLPRT_PRC511L(hw->port),
1119                            pf->stat_offsets_loaded,
1120                            &osd->rx_size_511, &nsd->rx_size_511);
1121         i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1122                            I40E_GLPRT_PRC1023L(hw->port),
1123                            pf->stat_offsets_loaded,
1124                            &osd->rx_size_1023, &nsd->rx_size_1023);
1125         i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1126                            I40E_GLPRT_PRC1522L(hw->port),
1127                            pf->stat_offsets_loaded,
1128                            &osd->rx_size_1522, &nsd->rx_size_1522);
1129         i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1130                            I40E_GLPRT_PRC9522L(hw->port),
1131                            pf->stat_offsets_loaded,
1132                            &osd->rx_size_big, &nsd->rx_size_big);
1133
1134         i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1135                            I40E_GLPRT_PTC64L(hw->port),
1136                            pf->stat_offsets_loaded,
1137                            &osd->tx_size_64, &nsd->tx_size_64);
1138         i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1139                            I40E_GLPRT_PTC127L(hw->port),
1140                            pf->stat_offsets_loaded,
1141                            &osd->tx_size_127, &nsd->tx_size_127);
1142         i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1143                            I40E_GLPRT_PTC255L(hw->port),
1144                            pf->stat_offsets_loaded,
1145                            &osd->tx_size_255, &nsd->tx_size_255);
1146         i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1147                            I40E_GLPRT_PTC511L(hw->port),
1148                            pf->stat_offsets_loaded,
1149                            &osd->tx_size_511, &nsd->tx_size_511);
1150         i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1151                            I40E_GLPRT_PTC1023L(hw->port),
1152                            pf->stat_offsets_loaded,
1153                            &osd->tx_size_1023, &nsd->tx_size_1023);
1154         i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1155                            I40E_GLPRT_PTC1522L(hw->port),
1156                            pf->stat_offsets_loaded,
1157                            &osd->tx_size_1522, &nsd->tx_size_1522);
1158         i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1159                            I40E_GLPRT_PTC9522L(hw->port),
1160                            pf->stat_offsets_loaded,
1161                            &osd->tx_size_big, &nsd->tx_size_big);
1162
1163         i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1164                            pf->stat_offsets_loaded,
1165                            &osd->rx_undersize, &nsd->rx_undersize);
1166         i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1167                            pf->stat_offsets_loaded,
1168                            &osd->rx_fragments, &nsd->rx_fragments);
1169         i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1170                            pf->stat_offsets_loaded,
1171                            &osd->rx_oversize, &nsd->rx_oversize);
1172         i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1173                            pf->stat_offsets_loaded,
1174                            &osd->rx_jabber, &nsd->rx_jabber);
1175
1176         /* FDIR stats */
1177         i40e_stat_update_and_clear32(hw,
1178                         I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1179                         &nsd->fd_atr_match);
1180         i40e_stat_update_and_clear32(hw,
1181                         I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1182                         &nsd->fd_sb_match);
1183         i40e_stat_update_and_clear32(hw,
1184                         I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1185                         &nsd->fd_atr_tunnel_match);
1186
1187         val = rd32(hw, I40E_PRTPM_EEE_STAT);
1188         nsd->tx_lpi_status =
1189                        (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1190                         I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1191         nsd->rx_lpi_status =
1192                        (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1193                         I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1194         i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1195                            pf->stat_offsets_loaded,
1196                            &osd->tx_lpi_count, &nsd->tx_lpi_count);
1197         i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1198                            pf->stat_offsets_loaded,
1199                            &osd->rx_lpi_count, &nsd->rx_lpi_count);
1200
1201         if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1202             !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1203                 nsd->fd_sb_status = true;
1204         else
1205                 nsd->fd_sb_status = false;
1206
1207         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1208             !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1209                 nsd->fd_atr_status = true;
1210         else
1211                 nsd->fd_atr_status = false;
1212
1213         pf->stat_offsets_loaded = true;
1214 }
1215
1216 /**
1217  * i40e_update_stats - Update the various statistics counters.
1218  * @vsi: the VSI to be updated
1219  *
1220  * Update the various stats for this VSI and its related entities.
1221  **/
1222 void i40e_update_stats(struct i40e_vsi *vsi)
1223 {
1224         struct i40e_pf *pf = vsi->back;
1225
1226         if (vsi == pf->vsi[pf->lan_vsi])
1227                 i40e_update_pf_stats(pf);
1228
1229         i40e_update_vsi_stats(vsi);
1230 }
1231
1232 /**
1233  * i40e_count_filters - counts VSI mac filters
1234  * @vsi: the VSI to be searched
1235  *
1236  * Returns count of mac filters
1237  **/
1238 int i40e_count_filters(struct i40e_vsi *vsi)
1239 {
1240         struct i40e_mac_filter *f;
1241         struct hlist_node *h;
1242         int bkt;
1243         int cnt = 0;
1244
1245         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1246                 ++cnt;
1247
1248         return cnt;
1249 }
1250
1251 /**
1252  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1253  * @vsi: the VSI to be searched
1254  * @macaddr: the MAC address
1255  * @vlan: the vlan
1256  *
1257  * Returns ptr to the filter object or NULL
1258  **/
1259 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1260                                                 const u8 *macaddr, s16 vlan)
1261 {
1262         struct i40e_mac_filter *f;
1263         u64 key;
1264
1265         if (!vsi || !macaddr)
1266                 return NULL;
1267
1268         key = i40e_addr_to_hkey(macaddr);
1269         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1270                 if ((ether_addr_equal(macaddr, f->macaddr)) &&
1271                     (vlan == f->vlan))
1272                         return f;
1273         }
1274         return NULL;
1275 }
1276
1277 /**
1278  * i40e_find_mac - Find a mac addr in the macvlan filters list
1279  * @vsi: the VSI to be searched
1280  * @macaddr: the MAC address we are searching for
1281  *
1282  * Returns the first filter with the provided MAC address or NULL if
1283  * MAC address was not found
1284  **/
1285 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1286 {
1287         struct i40e_mac_filter *f;
1288         u64 key;
1289
1290         if (!vsi || !macaddr)
1291                 return NULL;
1292
1293         key = i40e_addr_to_hkey(macaddr);
1294         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1295                 if ((ether_addr_equal(macaddr, f->macaddr)))
1296                         return f;
1297         }
1298         return NULL;
1299 }
1300
1301 /**
1302  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1303  * @vsi: the VSI to be searched
1304  *
1305  * Returns true if VSI is in vlan mode or false otherwise
1306  **/
1307 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1308 {
1309         /* If we have a PVID, always operate in VLAN mode */
1310         if (vsi->info.pvid)
1311                 return true;
1312
1313         /* We need to operate in VLAN mode whenever we have any filters with
1314          * a VLAN other than I40E_VLAN_ALL. We could check the table each
1315          * time, incurring search cost repeatedly. However, we can notice two
1316          * things:
1317          *
1318          * 1) the only place where we can gain a VLAN filter is in
1319          *    i40e_add_filter.
1320          *
1321          * 2) the only place where filters are actually removed is in
1322          *    i40e_sync_filters_subtask.
1323          *
1324          * Thus, we can simply use a boolean value, has_vlan_filters which we
1325          * will set to true when we add a VLAN filter in i40e_add_filter. Then
1326          * we have to perform the full search after deleting filters in
1327          * i40e_sync_filters_subtask, but we already have to search
1328          * filters here and can perform the check at the same time. This
1329          * results in avoiding embedding a loop for VLAN mode inside another
1330          * loop over all the filters, and should maintain correctness as noted
1331          * above.
1332          */
1333         return vsi->has_vlan_filter;
1334 }
1335
1336 /**
1337  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1338  * @vsi: the VSI to configure
1339  * @tmp_add_list: list of filters ready to be added
1340  * @tmp_del_list: list of filters ready to be deleted
1341  * @vlan_filters: the number of active VLAN filters
1342  *
1343  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1344  * behave as expected. If we have any active VLAN filters remaining or about
1345  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1346  * so that they only match against untagged traffic. If we no longer have any
1347  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1348  * so that they match against both tagged and untagged traffic. In this way,
1349  * we ensure that we correctly receive the desired traffic. This ensures that
1350  * when we have an active VLAN we will receive only untagged traffic and
1351  * traffic matching active VLANs. If we have no active VLANs then we will
1352  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1353  *
1354  * Finally, in a similar fashion, this function also corrects filters when
1355  * there is an active PVID assigned to this VSI.
1356  *
1357  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1358  *
1359  * This function is only expected to be called from within
1360  * i40e_sync_vsi_filters.
1361  *
1362  * NOTE: This function expects to be called while under the
1363  * mac_filter_hash_lock
1364  */
1365 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1366                                          struct hlist_head *tmp_add_list,
1367                                          struct hlist_head *tmp_del_list,
1368                                          int vlan_filters)
1369 {
1370         s16 pvid = le16_to_cpu(vsi->info.pvid);
1371         struct i40e_mac_filter *f, *add_head;
1372         struct i40e_new_mac_filter *new;
1373         struct hlist_node *h;
1374         int bkt, new_vlan;
1375
1376         /* To determine if a particular filter needs to be replaced we
1377          * have the three following conditions:
1378          *
1379          * a) if we have a PVID assigned, then all filters which are
1380          *    not marked as VLAN=PVID must be replaced with filters that
1381          *    are.
1382          * b) otherwise, if we have any active VLANS, all filters
1383          *    which are marked as VLAN=-1 must be replaced with
1384          *    filters marked as VLAN=0
1385          * c) finally, if we do not have any active VLANS, all filters
1386          *    which are marked as VLAN=0 must be replaced with filters
1387          *    marked as VLAN=-1
1388          */
1389
1390         /* Update the filters about to be added in place */
1391         hlist_for_each_entry(new, tmp_add_list, hlist) {
1392                 if (pvid && new->f->vlan != pvid)
1393                         new->f->vlan = pvid;
1394                 else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1395                         new->f->vlan = 0;
1396                 else if (!vlan_filters && new->f->vlan == 0)
1397                         new->f->vlan = I40E_VLAN_ANY;
1398         }
1399
1400         /* Update the remaining active filters */
1401         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1402                 /* Combine the checks for whether a filter needs to be changed
1403                  * and then determine the new VLAN inside the if block, in
1404                  * order to avoid duplicating code for adding the new filter
1405                  * then deleting the old filter.
1406                  */
1407                 if ((pvid && f->vlan != pvid) ||
1408                     (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1409                     (!vlan_filters && f->vlan == 0)) {
1410                         /* Determine the new vlan we will be adding */
1411                         if (pvid)
1412                                 new_vlan = pvid;
1413                         else if (vlan_filters)
1414                                 new_vlan = 0;
1415                         else
1416                                 new_vlan = I40E_VLAN_ANY;
1417
1418                         /* Create the new filter */
1419                         add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1420                         if (!add_head)
1421                                 return -ENOMEM;
1422
1423                         /* Create a temporary i40e_new_mac_filter */
1424                         new = kzalloc(sizeof(*new), GFP_ATOMIC);
1425                         if (!new)
1426                                 return -ENOMEM;
1427
1428                         new->f = add_head;
1429                         new->state = add_head->state;
1430
1431                         /* Add the new filter to the tmp list */
1432                         hlist_add_head(&new->hlist, tmp_add_list);
1433
1434                         /* Put the original filter into the delete list */
1435                         f->state = I40E_FILTER_REMOVE;
1436                         hash_del(&f->hlist);
1437                         hlist_add_head(&f->hlist, tmp_del_list);
1438                 }
1439         }
1440
1441         vsi->has_vlan_filter = !!vlan_filters;
1442
1443         return 0;
1444 }
1445
1446 /**
1447  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1448  * @vsi: the PF Main VSI - inappropriate for any other VSI
1449  * @macaddr: the MAC address
1450  *
1451  * Remove whatever filter the firmware set up so the driver can manage
1452  * its own filtering intelligently.
1453  **/
1454 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1455 {
1456         struct i40e_aqc_remove_macvlan_element_data element;
1457         struct i40e_pf *pf = vsi->back;
1458
1459         /* Only appropriate for the PF main VSI */
1460         if (vsi->type != I40E_VSI_MAIN)
1461                 return;
1462
1463         memset(&element, 0, sizeof(element));
1464         ether_addr_copy(element.mac_addr, macaddr);
1465         element.vlan_tag = 0;
1466         /* Ignore error returns, some firmware does it this way... */
1467         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1468         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1469
1470         memset(&element, 0, sizeof(element));
1471         ether_addr_copy(element.mac_addr, macaddr);
1472         element.vlan_tag = 0;
1473         /* ...and some firmware does it this way. */
1474         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1475                         I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1476         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1477 }
1478
1479 /**
1480  * i40e_add_filter - Add a mac/vlan filter to the VSI
1481  * @vsi: the VSI to be searched
1482  * @macaddr: the MAC address
1483  * @vlan: the vlan
1484  *
1485  * Returns ptr to the filter object or NULL when no memory available.
1486  *
1487  * NOTE: This function is expected to be called with mac_filter_hash_lock
1488  * being held.
1489  **/
1490 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1491                                         const u8 *macaddr, s16 vlan)
1492 {
1493         struct i40e_mac_filter *f;
1494         u64 key;
1495
1496         if (!vsi || !macaddr)
1497                 return NULL;
1498
1499         f = i40e_find_filter(vsi, macaddr, vlan);
1500         if (!f) {
1501                 f = kzalloc(sizeof(*f), GFP_ATOMIC);
1502                 if (!f)
1503                         return NULL;
1504
1505                 /* Update the boolean indicating if we need to function in
1506                  * VLAN mode.
1507                  */
1508                 if (vlan >= 0)
1509                         vsi->has_vlan_filter = true;
1510
1511                 ether_addr_copy(f->macaddr, macaddr);
1512                 f->vlan = vlan;
1513                 f->state = I40E_FILTER_NEW;
1514                 INIT_HLIST_NODE(&f->hlist);
1515
1516                 key = i40e_addr_to_hkey(macaddr);
1517                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
1518
1519                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1520                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1521         }
1522
1523         /* If we're asked to add a filter that has been marked for removal, it
1524          * is safe to simply restore it to active state. __i40e_del_filter
1525          * will have simply deleted any filters which were previously marked
1526          * NEW or FAILED, so if it is currently marked REMOVE it must have
1527          * previously been ACTIVE. Since we haven't yet run the sync filters
1528          * task, just restore this filter to the ACTIVE state so that the
1529          * sync task leaves it in place
1530          */
1531         if (f->state == I40E_FILTER_REMOVE)
1532                 f->state = I40E_FILTER_ACTIVE;
1533
1534         return f;
1535 }
1536
1537 /**
1538  * __i40e_del_filter - Remove a specific filter from the VSI
1539  * @vsi: VSI to remove from
1540  * @f: the filter to remove from the list
1541  *
1542  * This function should be called instead of i40e_del_filter only if you know
1543  * the exact filter you will remove already, such as via i40e_find_filter or
1544  * i40e_find_mac.
1545  *
1546  * NOTE: This function is expected to be called with mac_filter_hash_lock
1547  * being held.
1548  * ANOTHER NOTE: This function MUST be called from within the context of
1549  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1550  * instead of list_for_each_entry().
1551  **/
1552 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1553 {
1554         if (!f)
1555                 return;
1556
1557         /* If the filter was never added to firmware then we can just delete it
1558          * directly and we don't want to set the status to remove or else an
1559          * admin queue command will unnecessarily fire.
1560          */
1561         if ((f->state == I40E_FILTER_FAILED) ||
1562             (f->state == I40E_FILTER_NEW)) {
1563                 hash_del(&f->hlist);
1564                 kfree(f);
1565         } else {
1566                 f->state = I40E_FILTER_REMOVE;
1567         }
1568
1569         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1570         set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1571 }
1572
1573 /**
1574  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1575  * @vsi: the VSI to be searched
1576  * @macaddr: the MAC address
1577  * @vlan: the VLAN
1578  *
1579  * NOTE: This function is expected to be called with mac_filter_hash_lock
1580  * being held.
1581  * ANOTHER NOTE: This function MUST be called from within the context of
1582  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1583  * instead of list_for_each_entry().
1584  **/
1585 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1586 {
1587         struct i40e_mac_filter *f;
1588
1589         if (!vsi || !macaddr)
1590                 return;
1591
1592         f = i40e_find_filter(vsi, macaddr, vlan);
1593         __i40e_del_filter(vsi, f);
1594 }
1595
1596 /**
1597  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1598  * @vsi: the VSI to be searched
1599  * @macaddr: the mac address to be filtered
1600  *
1601  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1602  * go through all the macvlan filters and add a macvlan filter for each
1603  * unique vlan that already exists. If a PVID has been assigned, instead only
1604  * add the macaddr to that VLAN.
1605  *
1606  * Returns last filter added on success, else NULL
1607  **/
1608 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1609                                             const u8 *macaddr)
1610 {
1611         struct i40e_mac_filter *f, *add = NULL;
1612         struct hlist_node *h;
1613         int bkt;
1614
1615         if (vsi->info.pvid)
1616                 return i40e_add_filter(vsi, macaddr,
1617                                        le16_to_cpu(vsi->info.pvid));
1618
1619         if (!i40e_is_vsi_in_vlan(vsi))
1620                 return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1621
1622         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1623                 if (f->state == I40E_FILTER_REMOVE)
1624                         continue;
1625                 add = i40e_add_filter(vsi, macaddr, f->vlan);
1626                 if (!add)
1627                         return NULL;
1628         }
1629
1630         return add;
1631 }
1632
1633 /**
1634  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1635  * @vsi: the VSI to be searched
1636  * @macaddr: the mac address to be removed
1637  *
1638  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1639  * associated with.
1640  *
1641  * Returns 0 for success, or error
1642  **/
1643 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1644 {
1645         struct i40e_mac_filter *f;
1646         struct hlist_node *h;
1647         bool found = false;
1648         int bkt;
1649
1650         lockdep_assert_held(&vsi->mac_filter_hash_lock);
1651         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1652                 if (ether_addr_equal(macaddr, f->macaddr)) {
1653                         __i40e_del_filter(vsi, f);
1654                         found = true;
1655                 }
1656         }
1657
1658         if (found)
1659                 return 0;
1660         else
1661                 return -ENOENT;
1662 }
1663
1664 /**
1665  * i40e_set_mac - NDO callback to set mac address
1666  * @netdev: network interface device structure
1667  * @p: pointer to an address structure
1668  *
1669  * Returns 0 on success, negative on failure
1670  **/
1671 static int i40e_set_mac(struct net_device *netdev, void *p)
1672 {
1673         struct i40e_netdev_priv *np = netdev_priv(netdev);
1674         struct i40e_vsi *vsi = np->vsi;
1675         struct i40e_pf *pf = vsi->back;
1676         struct i40e_hw *hw = &pf->hw;
1677         struct sockaddr *addr = p;
1678
1679         if (!is_valid_ether_addr(addr->sa_data))
1680                 return -EADDRNOTAVAIL;
1681
1682         if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1683                 netdev_info(netdev, "already using mac address %pM\n",
1684                             addr->sa_data);
1685                 return 0;
1686         }
1687
1688         if (test_bit(__I40E_DOWN, pf->state) ||
1689             test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1690                 return -EADDRNOTAVAIL;
1691
1692         if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1693                 netdev_info(netdev, "returning to hw mac address %pM\n",
1694                             hw->mac.addr);
1695         else
1696                 netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1697
1698         /* Copy the address first, so that we avoid a possible race with
1699          * .set_rx_mode().
1700          * - Remove old address from MAC filter
1701          * - Copy new address
1702          * - Add new address to MAC filter
1703          */
1704         spin_lock_bh(&vsi->mac_filter_hash_lock);
1705         i40e_del_mac_filter(vsi, netdev->dev_addr);
1706         eth_hw_addr_set(netdev, addr->sa_data);
1707         i40e_add_mac_filter(vsi, netdev->dev_addr);
1708         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1709
1710         if (vsi->type == I40E_VSI_MAIN) {
1711                 i40e_status ret;
1712
1713                 ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1714                                                 addr->sa_data, NULL);
1715                 if (ret)
1716                         netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1717                                     i40e_stat_str(hw, ret),
1718                                     i40e_aq_str(hw, hw->aq.asq_last_status));
1719         }
1720
1721         /* schedule our worker thread which will take care of
1722          * applying the new filter changes
1723          */
1724         i40e_service_event_schedule(pf);
1725         return 0;
1726 }
1727
1728 /**
1729  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1730  * @vsi: vsi structure
1731  * @seed: RSS hash seed
1732  * @lut: pointer to lookup table of lut_size
1733  * @lut_size: size of the lookup table
1734  **/
1735 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1736                               u8 *lut, u16 lut_size)
1737 {
1738         struct i40e_pf *pf = vsi->back;
1739         struct i40e_hw *hw = &pf->hw;
1740         int ret = 0;
1741
1742         if (seed) {
1743                 struct i40e_aqc_get_set_rss_key_data *seed_dw =
1744                         (struct i40e_aqc_get_set_rss_key_data *)seed;
1745                 ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1746                 if (ret) {
1747                         dev_info(&pf->pdev->dev,
1748                                  "Cannot set RSS key, err %s aq_err %s\n",
1749                                  i40e_stat_str(hw, ret),
1750                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1751                         return ret;
1752                 }
1753         }
1754         if (lut) {
1755                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
1756
1757                 ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1758                 if (ret) {
1759                         dev_info(&pf->pdev->dev,
1760                                  "Cannot set RSS lut, err %s aq_err %s\n",
1761                                  i40e_stat_str(hw, ret),
1762                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1763                         return ret;
1764                 }
1765         }
1766         return ret;
1767 }
1768
1769 /**
1770  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1771  * @vsi: VSI structure
1772  **/
1773 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1774 {
1775         struct i40e_pf *pf = vsi->back;
1776         u8 seed[I40E_HKEY_ARRAY_SIZE];
1777         u8 *lut;
1778         int ret;
1779
1780         if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1781                 return 0;
1782         if (!vsi->rss_size)
1783                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
1784                                       vsi->num_queue_pairs);
1785         if (!vsi->rss_size)
1786                 return -EINVAL;
1787         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1788         if (!lut)
1789                 return -ENOMEM;
1790
1791         /* Use the user configured hash keys and lookup table if there is one,
1792          * otherwise use default
1793          */
1794         if (vsi->rss_lut_user)
1795                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1796         else
1797                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1798         if (vsi->rss_hkey_user)
1799                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1800         else
1801                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1802         ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1803         kfree(lut);
1804         return ret;
1805 }
1806
1807 /**
1808  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1809  * @vsi: the VSI being configured,
1810  * @ctxt: VSI context structure
1811  * @enabled_tc: number of traffic classes to enable
1812  *
1813  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1814  **/
1815 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1816                                            struct i40e_vsi_context *ctxt,
1817                                            u8 enabled_tc)
1818 {
1819         u16 qcount = 0, max_qcount, qmap, sections = 0;
1820         int i, override_q, pow, num_qps, ret;
1821         u8 netdev_tc = 0, offset = 0;
1822
1823         if (vsi->type != I40E_VSI_MAIN)
1824                 return -EINVAL;
1825         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1826         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1827         vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1828         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1829         num_qps = vsi->mqprio_qopt.qopt.count[0];
1830
1831         /* find the next higher power-of-2 of num queue pairs */
1832         pow = ilog2(num_qps);
1833         if (!is_power_of_2(num_qps))
1834                 pow++;
1835         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1836                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1837
1838         /* Setup queue offset/count for all TCs for given VSI */
1839         max_qcount = vsi->mqprio_qopt.qopt.count[0];
1840         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1841                 /* See if the given TC is enabled for the given VSI */
1842                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1843                         offset = vsi->mqprio_qopt.qopt.offset[i];
1844                         qcount = vsi->mqprio_qopt.qopt.count[i];
1845                         if (qcount > max_qcount)
1846                                 max_qcount = qcount;
1847                         vsi->tc_config.tc_info[i].qoffset = offset;
1848                         vsi->tc_config.tc_info[i].qcount = qcount;
1849                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1850                 } else {
1851                         /* TC is not enabled so set the offset to
1852                          * default queue and allocate one queue
1853                          * for the given TC.
1854                          */
1855                         vsi->tc_config.tc_info[i].qoffset = 0;
1856                         vsi->tc_config.tc_info[i].qcount = 1;
1857                         vsi->tc_config.tc_info[i].netdev_tc = 0;
1858                 }
1859         }
1860
1861         /* Set actual Tx/Rx queue pairs */
1862         vsi->num_queue_pairs = offset + qcount;
1863
1864         /* Setup queue TC[0].qmap for given VSI context */
1865         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1866         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1867         ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1868         ctxt->info.valid_sections |= cpu_to_le16(sections);
1869
1870         /* Reconfigure RSS for main VSI with max queue count */
1871         vsi->rss_size = max_qcount;
1872         ret = i40e_vsi_config_rss(vsi);
1873         if (ret) {
1874                 dev_info(&vsi->back->pdev->dev,
1875                          "Failed to reconfig rss for num_queues (%u)\n",
1876                          max_qcount);
1877                 return ret;
1878         }
1879         vsi->reconfig_rss = true;
1880         dev_dbg(&vsi->back->pdev->dev,
1881                 "Reconfigured rss with num_queues (%u)\n", max_qcount);
1882
1883         /* Find queue count available for channel VSIs and starting offset
1884          * for channel VSIs
1885          */
1886         override_q = vsi->mqprio_qopt.qopt.count[0];
1887         if (override_q && override_q < vsi->num_queue_pairs) {
1888                 vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1889                 vsi->next_base_queue = override_q;
1890         }
1891         return 0;
1892 }
1893
1894 /**
1895  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1896  * @vsi: the VSI being setup
1897  * @ctxt: VSI context structure
1898  * @enabled_tc: Enabled TCs bitmap
1899  * @is_add: True if called before Add VSI
1900  *
1901  * Setup VSI queue mapping for enabled traffic classes.
1902  **/
1903 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
1904                                      struct i40e_vsi_context *ctxt,
1905                                      u8 enabled_tc,
1906                                      bool is_add)
1907 {
1908         struct i40e_pf *pf = vsi->back;
1909         u16 num_tc_qps = 0;
1910         u16 sections = 0;
1911         u8 netdev_tc = 0;
1912         u16 numtc = 1;
1913         u16 qcount;
1914         u8 offset;
1915         u16 qmap;
1916         int i;
1917
1918         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1919         offset = 0;
1920         /* zero out queue mapping, it will get updated on the end of the function */
1921         memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
1922
1923         if (vsi->type == I40E_VSI_MAIN) {
1924                 /* This code helps add more queue to the VSI if we have
1925                  * more cores than RSS can support, the higher cores will
1926                  * be served by ATR or other filters. Furthermore, the
1927                  * non-zero req_queue_pairs says that user requested a new
1928                  * queue count via ethtool's set_channels, so use this
1929                  * value for queues distribution across traffic classes
1930                  * We need at least one queue pair for the interface
1931                  * to be usable as we see in else statement.
1932                  */
1933                 if (vsi->req_queue_pairs > 0)
1934                         vsi->num_queue_pairs = vsi->req_queue_pairs;
1935                 else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1936                         vsi->num_queue_pairs = pf->num_lan_msix;
1937                 else
1938                         vsi->num_queue_pairs = 1;
1939         }
1940
1941         /* Number of queues per enabled TC */
1942         if (vsi->type == I40E_VSI_MAIN ||
1943             (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
1944                 num_tc_qps = vsi->num_queue_pairs;
1945         else
1946                 num_tc_qps = vsi->alloc_queue_pairs;
1947
1948         if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
1949                 /* Find numtc from enabled TC bitmap */
1950                 for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1951                         if (enabled_tc & BIT(i)) /* TC is enabled */
1952                                 numtc++;
1953                 }
1954                 if (!numtc) {
1955                         dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
1956                         numtc = 1;
1957                 }
1958                 num_tc_qps = num_tc_qps / numtc;
1959                 num_tc_qps = min_t(int, num_tc_qps,
1960                                    i40e_pf_get_max_q_per_tc(pf));
1961         }
1962
1963         vsi->tc_config.numtc = numtc;
1964         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1965
1966         /* Do not allow use more TC queue pairs than MSI-X vectors exist */
1967         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1968                 num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
1969
1970         /* Setup queue offset/count for all TCs for given VSI */
1971         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1972                 /* See if the given TC is enabled for the given VSI */
1973                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1974                         /* TC is enabled */
1975                         int pow, num_qps;
1976
1977                         switch (vsi->type) {
1978                         case I40E_VSI_MAIN:
1979                                 if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
1980                                     I40E_FLAG_FD_ATR_ENABLED)) ||
1981                                     vsi->tc_config.enabled_tc != 1) {
1982                                         qcount = min_t(int, pf->alloc_rss_size,
1983                                                        num_tc_qps);
1984                                         break;
1985                                 }
1986                                 fallthrough;
1987                         case I40E_VSI_FDIR:
1988                         case I40E_VSI_SRIOV:
1989                         case I40E_VSI_VMDQ2:
1990                         default:
1991                                 qcount = num_tc_qps;
1992                                 WARN_ON(i != 0);
1993                                 break;
1994                         }
1995                         vsi->tc_config.tc_info[i].qoffset = offset;
1996                         vsi->tc_config.tc_info[i].qcount = qcount;
1997
1998                         /* find the next higher power-of-2 of num queue pairs */
1999                         num_qps = qcount;
2000                         pow = 0;
2001                         while (num_qps && (BIT_ULL(pow) < qcount)) {
2002                                 pow++;
2003                                 num_qps >>= 1;
2004                         }
2005
2006                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2007                         qmap =
2008                             (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2009                             (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2010
2011                         offset += qcount;
2012                 } else {
2013                         /* TC is not enabled so set the offset to
2014                          * default queue and allocate one queue
2015                          * for the given TC.
2016                          */
2017                         vsi->tc_config.tc_info[i].qoffset = 0;
2018                         vsi->tc_config.tc_info[i].qcount = 1;
2019                         vsi->tc_config.tc_info[i].netdev_tc = 0;
2020
2021                         qmap = 0;
2022                 }
2023                 ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2024         }
2025         /* Do not change previously set num_queue_pairs for PFs and VFs*/
2026         if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2027             (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2028             (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2029                 vsi->num_queue_pairs = offset;
2030
2031         /* Scheduler section valid can only be set for ADD VSI */
2032         if (is_add) {
2033                 sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2034
2035                 ctxt->info.up_enable_bits = enabled_tc;
2036         }
2037         if (vsi->type == I40E_VSI_SRIOV) {
2038                 ctxt->info.mapping_flags |=
2039                                      cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2040                 for (i = 0; i < vsi->num_queue_pairs; i++)
2041                         ctxt->info.queue_mapping[i] =
2042                                                cpu_to_le16(vsi->base_queue + i);
2043         } else {
2044                 ctxt->info.mapping_flags |=
2045                                         cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2046                 ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2047         }
2048         ctxt->info.valid_sections |= cpu_to_le16(sections);
2049 }
2050
2051 /**
2052  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2053  * @netdev: the netdevice
2054  * @addr: address to add
2055  *
2056  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2057  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2058  */
2059 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2060 {
2061         struct i40e_netdev_priv *np = netdev_priv(netdev);
2062         struct i40e_vsi *vsi = np->vsi;
2063
2064         if (i40e_add_mac_filter(vsi, addr))
2065                 return 0;
2066         else
2067                 return -ENOMEM;
2068 }
2069
2070 /**
2071  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2072  * @netdev: the netdevice
2073  * @addr: address to add
2074  *
2075  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2076  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2077  */
2078 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2079 {
2080         struct i40e_netdev_priv *np = netdev_priv(netdev);
2081         struct i40e_vsi *vsi = np->vsi;
2082
2083         /* Under some circumstances, we might receive a request to delete
2084          * our own device address from our uc list. Because we store the
2085          * device address in the VSI's MAC/VLAN filter list, we need to ignore
2086          * such requests and not delete our device address from this list.
2087          */
2088         if (ether_addr_equal(addr, netdev->dev_addr))
2089                 return 0;
2090
2091         i40e_del_mac_filter(vsi, addr);
2092
2093         return 0;
2094 }
2095
2096 /**
2097  * i40e_set_rx_mode - NDO callback to set the netdev filters
2098  * @netdev: network interface device structure
2099  **/
2100 static void i40e_set_rx_mode(struct net_device *netdev)
2101 {
2102         struct i40e_netdev_priv *np = netdev_priv(netdev);
2103         struct i40e_vsi *vsi = np->vsi;
2104
2105         spin_lock_bh(&vsi->mac_filter_hash_lock);
2106
2107         __dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2108         __dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2109
2110         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2111
2112         /* check for other flag changes */
2113         if (vsi->current_netdev_flags != vsi->netdev->flags) {
2114                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2115                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2116         }
2117 }
2118
2119 /**
2120  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2121  * @vsi: Pointer to VSI struct
2122  * @from: Pointer to list which contains MAC filter entries - changes to
2123  *        those entries needs to be undone.
2124  *
2125  * MAC filter entries from this list were slated for deletion.
2126  **/
2127 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2128                                          struct hlist_head *from)
2129 {
2130         struct i40e_mac_filter *f;
2131         struct hlist_node *h;
2132
2133         hlist_for_each_entry_safe(f, h, from, hlist) {
2134                 u64 key = i40e_addr_to_hkey(f->macaddr);
2135
2136                 /* Move the element back into MAC filter list*/
2137                 hlist_del(&f->hlist);
2138                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
2139         }
2140 }
2141
2142 /**
2143  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2144  * @vsi: Pointer to vsi struct
2145  * @from: Pointer to list which contains MAC filter entries - changes to
2146  *        those entries needs to be undone.
2147  *
2148  * MAC filter entries from this list were slated for addition.
2149  **/
2150 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2151                                          struct hlist_head *from)
2152 {
2153         struct i40e_new_mac_filter *new;
2154         struct hlist_node *h;
2155
2156         hlist_for_each_entry_safe(new, h, from, hlist) {
2157                 /* We can simply free the wrapper structure */
2158                 hlist_del(&new->hlist);
2159                 netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2160                 kfree(new);
2161         }
2162 }
2163
2164 /**
2165  * i40e_next_filter - Get the next non-broadcast filter from a list
2166  * @next: pointer to filter in list
2167  *
2168  * Returns the next non-broadcast filter in the list. Required so that we
2169  * ignore broadcast filters within the list, since these are not handled via
2170  * the normal firmware update path.
2171  */
2172 static
2173 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2174 {
2175         hlist_for_each_entry_continue(next, hlist) {
2176                 if (!is_broadcast_ether_addr(next->f->macaddr))
2177                         return next;
2178         }
2179
2180         return NULL;
2181 }
2182
2183 /**
2184  * i40e_update_filter_state - Update filter state based on return data
2185  * from firmware
2186  * @count: Number of filters added
2187  * @add_list: return data from fw
2188  * @add_head: pointer to first filter in current batch
2189  *
2190  * MAC filter entries from list were slated to be added to device. Returns
2191  * number of successful filters. Note that 0 does NOT mean success!
2192  **/
2193 static int
2194 i40e_update_filter_state(int count,
2195                          struct i40e_aqc_add_macvlan_element_data *add_list,
2196                          struct i40e_new_mac_filter *add_head)
2197 {
2198         int retval = 0;
2199         int i;
2200
2201         for (i = 0; i < count; i++) {
2202                 /* Always check status of each filter. We don't need to check
2203                  * the firmware return status because we pre-set the filter
2204                  * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2205                  * request to the adminq. Thus, if it no longer matches then
2206                  * we know the filter is active.
2207                  */
2208                 if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2209                         add_head->state = I40E_FILTER_FAILED;
2210                 } else {
2211                         add_head->state = I40E_FILTER_ACTIVE;
2212                         retval++;
2213                 }
2214
2215                 add_head = i40e_next_filter(add_head);
2216                 if (!add_head)
2217                         break;
2218         }
2219
2220         return retval;
2221 }
2222
2223 /**
2224  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2225  * @vsi: ptr to the VSI
2226  * @vsi_name: name to display in messages
2227  * @list: the list of filters to send to firmware
2228  * @num_del: the number of filters to delete
2229  * @retval: Set to -EIO on failure to delete
2230  *
2231  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2232  * *retval instead of a return value so that success does not force ret_val to
2233  * be set to 0. This ensures that a sequence of calls to this function
2234  * preserve the previous value of *retval on successful delete.
2235  */
2236 static
2237 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2238                           struct i40e_aqc_remove_macvlan_element_data *list,
2239                           int num_del, int *retval)
2240 {
2241         struct i40e_hw *hw = &vsi->back->hw;
2242         enum i40e_admin_queue_err aq_status;
2243         i40e_status aq_ret;
2244
2245         aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2246                                            &aq_status);
2247
2248         /* Explicitly ignore and do not report when firmware returns ENOENT */
2249         if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2250                 *retval = -EIO;
2251                 dev_info(&vsi->back->pdev->dev,
2252                          "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
2253                          vsi_name, i40e_stat_str(hw, aq_ret),
2254                          i40e_aq_str(hw, aq_status));
2255         }
2256 }
2257
2258 /**
2259  * i40e_aqc_add_filters - Request firmware to add a set of filters
2260  * @vsi: ptr to the VSI
2261  * @vsi_name: name to display in messages
2262  * @list: the list of filters to send to firmware
2263  * @add_head: Position in the add hlist
2264  * @num_add: the number of filters to add
2265  *
2266  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2267  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2268  * space for more filters.
2269  */
2270 static
2271 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2272                           struct i40e_aqc_add_macvlan_element_data *list,
2273                           struct i40e_new_mac_filter *add_head,
2274                           int num_add)
2275 {
2276         struct i40e_hw *hw = &vsi->back->hw;
2277         enum i40e_admin_queue_err aq_status;
2278         int fcnt;
2279
2280         i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2281         fcnt = i40e_update_filter_state(num_add, list, add_head);
2282
2283         if (fcnt != num_add) {
2284                 if (vsi->type == I40E_VSI_MAIN) {
2285                         set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2286                         dev_warn(&vsi->back->pdev->dev,
2287                                  "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2288                                  i40e_aq_str(hw, aq_status), vsi_name);
2289                 } else if (vsi->type == I40E_VSI_SRIOV ||
2290                            vsi->type == I40E_VSI_VMDQ1 ||
2291                            vsi->type == I40E_VSI_VMDQ2) {
2292                         dev_warn(&vsi->back->pdev->dev,
2293                                  "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2294                                  i40e_aq_str(hw, aq_status), vsi_name,
2295                                              vsi_name);
2296                 } else {
2297                         dev_warn(&vsi->back->pdev->dev,
2298                                  "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2299                                  i40e_aq_str(hw, aq_status), vsi_name,
2300                                              vsi->type);
2301                 }
2302         }
2303 }
2304
2305 /**
2306  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2307  * @vsi: pointer to the VSI
2308  * @vsi_name: the VSI name
2309  * @f: filter data
2310  *
2311  * This function sets or clears the promiscuous broadcast flags for VLAN
2312  * filters in order to properly receive broadcast frames. Assumes that only
2313  * broadcast filters are passed.
2314  *
2315  * Returns status indicating success or failure;
2316  **/
2317 static i40e_status
2318 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2319                           struct i40e_mac_filter *f)
2320 {
2321         bool enable = f->state == I40E_FILTER_NEW;
2322         struct i40e_hw *hw = &vsi->back->hw;
2323         i40e_status aq_ret;
2324
2325         if (f->vlan == I40E_VLAN_ANY) {
2326                 aq_ret = i40e_aq_set_vsi_broadcast(hw,
2327                                                    vsi->seid,
2328                                                    enable,
2329                                                    NULL);
2330         } else {
2331                 aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2332                                                             vsi->seid,
2333                                                             enable,
2334                                                             f->vlan,
2335                                                             NULL);
2336         }
2337
2338         if (aq_ret) {
2339                 set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2340                 dev_warn(&vsi->back->pdev->dev,
2341                          "Error %s, forcing overflow promiscuous on %s\n",
2342                          i40e_aq_str(hw, hw->aq.asq_last_status),
2343                          vsi_name);
2344         }
2345
2346         return aq_ret;
2347 }
2348
2349 /**
2350  * i40e_set_promiscuous - set promiscuous mode
2351  * @pf: board private structure
2352  * @promisc: promisc on or off
2353  *
2354  * There are different ways of setting promiscuous mode on a PF depending on
2355  * what state/environment we're in.  This identifies and sets it appropriately.
2356  * Returns 0 on success.
2357  **/
2358 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2359 {
2360         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2361         struct i40e_hw *hw = &pf->hw;
2362         i40e_status aq_ret;
2363
2364         if (vsi->type == I40E_VSI_MAIN &&
2365             pf->lan_veb != I40E_NO_VEB &&
2366             !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2367                 /* set defport ON for Main VSI instead of true promisc
2368                  * this way we will get all unicast/multicast and VLAN
2369                  * promisc behavior but will not get VF or VMDq traffic
2370                  * replicated on the Main VSI.
2371                  */
2372                 if (promisc)
2373                         aq_ret = i40e_aq_set_default_vsi(hw,
2374                                                          vsi->seid,
2375                                                          NULL);
2376                 else
2377                         aq_ret = i40e_aq_clear_default_vsi(hw,
2378                                                            vsi->seid,
2379                                                            NULL);
2380                 if (aq_ret) {
2381                         dev_info(&pf->pdev->dev,
2382                                  "Set default VSI failed, err %s, aq_err %s\n",
2383                                  i40e_stat_str(hw, aq_ret),
2384                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2385                 }
2386         } else {
2387                 aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2388                                                   hw,
2389                                                   vsi->seid,
2390                                                   promisc, NULL,
2391                                                   true);
2392                 if (aq_ret) {
2393                         dev_info(&pf->pdev->dev,
2394                                  "set unicast promisc failed, err %s, aq_err %s\n",
2395                                  i40e_stat_str(hw, aq_ret),
2396                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2397                 }
2398                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2399                                                   hw,
2400                                                   vsi->seid,
2401                                                   promisc, NULL);
2402                 if (aq_ret) {
2403                         dev_info(&pf->pdev->dev,
2404                                  "set multicast promisc failed, err %s, aq_err %s\n",
2405                                  i40e_stat_str(hw, aq_ret),
2406                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2407                 }
2408         }
2409
2410         if (!aq_ret)
2411                 pf->cur_promisc = promisc;
2412
2413         return aq_ret;
2414 }
2415
2416 /**
2417  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2418  * @vsi: ptr to the VSI
2419  *
2420  * Push any outstanding VSI filter changes through the AdminQ.
2421  *
2422  * Returns 0 or error value
2423  **/
2424 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2425 {
2426         struct hlist_head tmp_add_list, tmp_del_list;
2427         struct i40e_mac_filter *f;
2428         struct i40e_new_mac_filter *new, *add_head = NULL;
2429         struct i40e_hw *hw = &vsi->back->hw;
2430         bool old_overflow, new_overflow;
2431         unsigned int failed_filters = 0;
2432         unsigned int vlan_filters = 0;
2433         char vsi_name[16] = "PF";
2434         int filter_list_len = 0;
2435         i40e_status aq_ret = 0;
2436         u32 changed_flags = 0;
2437         struct hlist_node *h;
2438         struct i40e_pf *pf;
2439         int num_add = 0;
2440         int num_del = 0;
2441         int retval = 0;
2442         u16 cmd_flags;
2443         int list_size;
2444         int bkt;
2445
2446         /* empty array typed pointers, kcalloc later */
2447         struct i40e_aqc_add_macvlan_element_data *add_list;
2448         struct i40e_aqc_remove_macvlan_element_data *del_list;
2449
2450         while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2451                 usleep_range(1000, 2000);
2452         pf = vsi->back;
2453
2454         old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2455
2456         if (vsi->netdev) {
2457                 changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2458                 vsi->current_netdev_flags = vsi->netdev->flags;
2459         }
2460
2461         INIT_HLIST_HEAD(&tmp_add_list);
2462         INIT_HLIST_HEAD(&tmp_del_list);
2463
2464         if (vsi->type == I40E_VSI_SRIOV)
2465                 snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2466         else if (vsi->type != I40E_VSI_MAIN)
2467                 snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2468
2469         if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2470                 vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2471
2472                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2473                 /* Create a list of filters to delete. */
2474                 hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2475                         if (f->state == I40E_FILTER_REMOVE) {
2476                                 /* Move the element into temporary del_list */
2477                                 hash_del(&f->hlist);
2478                                 hlist_add_head(&f->hlist, &tmp_del_list);
2479
2480                                 /* Avoid counting removed filters */
2481                                 continue;
2482                         }
2483                         if (f->state == I40E_FILTER_NEW) {
2484                                 /* Create a temporary i40e_new_mac_filter */
2485                                 new = kzalloc(sizeof(*new), GFP_ATOMIC);
2486                                 if (!new)
2487                                         goto err_no_memory_locked;
2488
2489                                 /* Store pointer to the real filter */
2490                                 new->f = f;
2491                                 new->state = f->state;
2492
2493                                 /* Add it to the hash list */
2494                                 hlist_add_head(&new->hlist, &tmp_add_list);
2495                         }
2496
2497                         /* Count the number of active (current and new) VLAN
2498                          * filters we have now. Does not count filters which
2499                          * are marked for deletion.
2500                          */
2501                         if (f->vlan > 0)
2502                                 vlan_filters++;
2503                 }
2504
2505                 retval = i40e_correct_mac_vlan_filters(vsi,
2506                                                        &tmp_add_list,
2507                                                        &tmp_del_list,
2508                                                        vlan_filters);
2509
2510                 hlist_for_each_entry(new, &tmp_add_list, hlist)
2511                         netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2512
2513                 if (retval)
2514                         goto err_no_memory_locked;
2515
2516                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2517         }
2518
2519         /* Now process 'del_list' outside the lock */
2520         if (!hlist_empty(&tmp_del_list)) {
2521                 filter_list_len = hw->aq.asq_buf_size /
2522                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2523                 list_size = filter_list_len *
2524                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2525                 del_list = kzalloc(list_size, GFP_ATOMIC);
2526                 if (!del_list)
2527                         goto err_no_memory;
2528
2529                 hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2530                         cmd_flags = 0;
2531
2532                         /* handle broadcast filters by updating the broadcast
2533                          * promiscuous flag and release filter list.
2534                          */
2535                         if (is_broadcast_ether_addr(f->macaddr)) {
2536                                 i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2537
2538                                 hlist_del(&f->hlist);
2539                                 kfree(f);
2540                                 continue;
2541                         }
2542
2543                         /* add to delete list */
2544                         ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2545                         if (f->vlan == I40E_VLAN_ANY) {
2546                                 del_list[num_del].vlan_tag = 0;
2547                                 cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2548                         } else {
2549                                 del_list[num_del].vlan_tag =
2550                                         cpu_to_le16((u16)(f->vlan));
2551                         }
2552
2553                         cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2554                         del_list[num_del].flags = cmd_flags;
2555                         num_del++;
2556
2557                         /* flush a full buffer */
2558                         if (num_del == filter_list_len) {
2559                                 i40e_aqc_del_filters(vsi, vsi_name, del_list,
2560                                                      num_del, &retval);
2561                                 memset(del_list, 0, list_size);
2562                                 num_del = 0;
2563                         }
2564                         /* Release memory for MAC filter entries which were
2565                          * synced up with HW.
2566                          */
2567                         hlist_del(&f->hlist);
2568                         kfree(f);
2569                 }
2570
2571                 if (num_del) {
2572                         i40e_aqc_del_filters(vsi, vsi_name, del_list,
2573                                              num_del, &retval);
2574                 }
2575
2576                 kfree(del_list);
2577                 del_list = NULL;
2578         }
2579
2580         if (!hlist_empty(&tmp_add_list)) {
2581                 /* Do all the adds now. */
2582                 filter_list_len = hw->aq.asq_buf_size /
2583                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2584                 list_size = filter_list_len *
2585                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2586                 add_list = kzalloc(list_size, GFP_ATOMIC);
2587                 if (!add_list)
2588                         goto err_no_memory;
2589
2590                 num_add = 0;
2591                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2592                         /* handle broadcast filters by updating the broadcast
2593                          * promiscuous flag instead of adding a MAC filter.
2594                          */
2595                         if (is_broadcast_ether_addr(new->f->macaddr)) {
2596                                 if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2597                                                               new->f))
2598                                         new->state = I40E_FILTER_FAILED;
2599                                 else
2600                                         new->state = I40E_FILTER_ACTIVE;
2601                                 continue;
2602                         }
2603
2604                         /* add to add array */
2605                         if (num_add == 0)
2606                                 add_head = new;
2607                         cmd_flags = 0;
2608                         ether_addr_copy(add_list[num_add].mac_addr,
2609                                         new->f->macaddr);
2610                         if (new->f->vlan == I40E_VLAN_ANY) {
2611                                 add_list[num_add].vlan_tag = 0;
2612                                 cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2613                         } else {
2614                                 add_list[num_add].vlan_tag =
2615                                         cpu_to_le16((u16)(new->f->vlan));
2616                         }
2617                         add_list[num_add].queue_number = 0;
2618                         /* set invalid match method for later detection */
2619                         add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2620                         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2621                         add_list[num_add].flags = cpu_to_le16(cmd_flags);
2622                         num_add++;
2623
2624                         /* flush a full buffer */
2625                         if (num_add == filter_list_len) {
2626                                 i40e_aqc_add_filters(vsi, vsi_name, add_list,
2627                                                      add_head, num_add);
2628                                 memset(add_list, 0, list_size);
2629                                 num_add = 0;
2630                         }
2631                 }
2632                 if (num_add) {
2633                         i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2634                                              num_add);
2635                 }
2636                 /* Now move all of the filters from the temp add list back to
2637                  * the VSI's list.
2638                  */
2639                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2640                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2641                         /* Only update the state if we're still NEW */
2642                         if (new->f->state == I40E_FILTER_NEW)
2643                                 new->f->state = new->state;
2644                         hlist_del(&new->hlist);
2645                         netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2646                         kfree(new);
2647                 }
2648                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2649                 kfree(add_list);
2650                 add_list = NULL;
2651         }
2652
2653         /* Determine the number of active and failed filters. */
2654         spin_lock_bh(&vsi->mac_filter_hash_lock);
2655         vsi->active_filters = 0;
2656         hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2657                 if (f->state == I40E_FILTER_ACTIVE)
2658                         vsi->active_filters++;
2659                 else if (f->state == I40E_FILTER_FAILED)
2660                         failed_filters++;
2661         }
2662         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2663
2664         /* Check if we are able to exit overflow promiscuous mode. We can
2665          * safely exit if we didn't just enter, we no longer have any failed
2666          * filters, and we have reduced filters below the threshold value.
2667          */
2668         if (old_overflow && !failed_filters &&
2669             vsi->active_filters < vsi->promisc_threshold) {
2670                 dev_info(&pf->pdev->dev,
2671                          "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2672                          vsi_name);
2673                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2674                 vsi->promisc_threshold = 0;
2675         }
2676
2677         /* if the VF is not trusted do not do promisc */
2678         if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2679                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2680                 goto out;
2681         }
2682
2683         new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2684
2685         /* If we are entering overflow promiscuous, we need to calculate a new
2686          * threshold for when we are safe to exit
2687          */
2688         if (!old_overflow && new_overflow)
2689                 vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2690
2691         /* check for changes in promiscuous modes */
2692         if (changed_flags & IFF_ALLMULTI) {
2693                 bool cur_multipromisc;
2694
2695                 cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2696                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2697                                                                vsi->seid,
2698                                                                cur_multipromisc,
2699                                                                NULL);
2700                 if (aq_ret) {
2701                         retval = i40e_aq_rc_to_posix(aq_ret,
2702                                                      hw->aq.asq_last_status);
2703                         dev_info(&pf->pdev->dev,
2704                                  "set multi promisc failed on %s, err %s aq_err %s\n",
2705                                  vsi_name,
2706                                  i40e_stat_str(hw, aq_ret),
2707                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2708                 } else {
2709                         dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2710                                  cur_multipromisc ? "entering" : "leaving");
2711                 }
2712         }
2713
2714         if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2715                 bool cur_promisc;
2716
2717                 cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2718                                new_overflow);
2719                 aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2720                 if (aq_ret) {
2721                         retval = i40e_aq_rc_to_posix(aq_ret,
2722                                                      hw->aq.asq_last_status);
2723                         dev_info(&pf->pdev->dev,
2724                                  "Setting promiscuous %s failed on %s, err %s aq_err %s\n",
2725                                  cur_promisc ? "on" : "off",
2726                                  vsi_name,
2727                                  i40e_stat_str(hw, aq_ret),
2728                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2729                 }
2730         }
2731 out:
2732         /* if something went wrong then set the changed flag so we try again */
2733         if (retval)
2734                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2735
2736         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2737         return retval;
2738
2739 err_no_memory:
2740         /* Restore elements on the temporary add and delete lists */
2741         spin_lock_bh(&vsi->mac_filter_hash_lock);
2742 err_no_memory_locked:
2743         i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2744         i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2745         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2746
2747         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2748         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2749         return -ENOMEM;
2750 }
2751
2752 /**
2753  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2754  * @pf: board private structure
2755  **/
2756 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2757 {
2758         int v;
2759
2760         if (!pf)
2761                 return;
2762         if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2763                 return;
2764         if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2765                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2766                 return;
2767         }
2768
2769         for (v = 0; v < pf->num_alloc_vsi; v++) {
2770                 if (pf->vsi[v] &&
2771                     (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2772                     !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2773                         int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2774
2775                         if (ret) {
2776                                 /* come back and try again later */
2777                                 set_bit(__I40E_MACVLAN_SYNC_PENDING,
2778                                         pf->state);
2779                                 break;
2780                         }
2781                 }
2782         }
2783 }
2784
2785 /**
2786  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2787  * @vsi: the vsi
2788  **/
2789 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2790 {
2791         if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2792                 return I40E_RXBUFFER_2048;
2793         else
2794                 return I40E_RXBUFFER_3072;
2795 }
2796
2797 /**
2798  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2799  * @netdev: network interface device structure
2800  * @new_mtu: new value for maximum frame size
2801  *
2802  * Returns 0 on success, negative on failure
2803  **/
2804 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2805 {
2806         struct i40e_netdev_priv *np = netdev_priv(netdev);
2807         struct i40e_vsi *vsi = np->vsi;
2808         struct i40e_pf *pf = vsi->back;
2809
2810         if (i40e_enabled_xdp_vsi(vsi)) {
2811                 int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2812
2813                 if (frame_size > i40e_max_xdp_frame_size(vsi))
2814                         return -EINVAL;
2815         }
2816
2817         netdev_dbg(netdev, "changing MTU from %d to %d\n",
2818                    netdev->mtu, new_mtu);
2819         netdev->mtu = new_mtu;
2820         if (netif_running(netdev))
2821                 i40e_vsi_reinit_locked(vsi);
2822         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2823         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2824         return 0;
2825 }
2826
2827 /**
2828  * i40e_ioctl - Access the hwtstamp interface
2829  * @netdev: network interface device structure
2830  * @ifr: interface request data
2831  * @cmd: ioctl command
2832  **/
2833 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2834 {
2835         struct i40e_netdev_priv *np = netdev_priv(netdev);
2836         struct i40e_pf *pf = np->vsi->back;
2837
2838         switch (cmd) {
2839         case SIOCGHWTSTAMP:
2840                 return i40e_ptp_get_ts_config(pf, ifr);
2841         case SIOCSHWTSTAMP:
2842                 return i40e_ptp_set_ts_config(pf, ifr);
2843         default:
2844                 return -EOPNOTSUPP;
2845         }
2846 }
2847
2848 /**
2849  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2850  * @vsi: the vsi being adjusted
2851  **/
2852 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2853 {
2854         struct i40e_vsi_context ctxt;
2855         i40e_status ret;
2856
2857         /* Don't modify stripping options if a port VLAN is active */
2858         if (vsi->info.pvid)
2859                 return;
2860
2861         if ((vsi->info.valid_sections &
2862              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2863             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2864                 return;  /* already enabled */
2865
2866         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2867         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2868                                     I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2869
2870         ctxt.seid = vsi->seid;
2871         ctxt.info = vsi->info;
2872         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2873         if (ret) {
2874                 dev_info(&vsi->back->pdev->dev,
2875                          "update vlan stripping failed, err %s aq_err %s\n",
2876                          i40e_stat_str(&vsi->back->hw, ret),
2877                          i40e_aq_str(&vsi->back->hw,
2878                                      vsi->back->hw.aq.asq_last_status));
2879         }
2880 }
2881
2882 /**
2883  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2884  * @vsi: the vsi being adjusted
2885  **/
2886 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2887 {
2888         struct i40e_vsi_context ctxt;
2889         i40e_status ret;
2890
2891         /* Don't modify stripping options if a port VLAN is active */
2892         if (vsi->info.pvid)
2893                 return;
2894
2895         if ((vsi->info.valid_sections &
2896              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2897             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
2898              I40E_AQ_VSI_PVLAN_EMOD_MASK))
2899                 return;  /* already disabled */
2900
2901         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2902         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2903                                     I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2904
2905         ctxt.seid = vsi->seid;
2906         ctxt.info = vsi->info;
2907         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2908         if (ret) {
2909                 dev_info(&vsi->back->pdev->dev,
2910                          "update vlan stripping failed, err %s aq_err %s\n",
2911                          i40e_stat_str(&vsi->back->hw, ret),
2912                          i40e_aq_str(&vsi->back->hw,
2913                                      vsi->back->hw.aq.asq_last_status));
2914         }
2915 }
2916
2917 /**
2918  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
2919  * @vsi: the vsi being configured
2920  * @vid: vlan id to be added (0 = untagged only , -1 = any)
2921  *
2922  * This is a helper function for adding a new MAC/VLAN filter with the
2923  * specified VLAN for each existing MAC address already in the hash table.
2924  * This function does *not* perform any accounting to update filters based on
2925  * VLAN mode.
2926  *
2927  * NOTE: this function expects to be called while under the
2928  * mac_filter_hash_lock
2929  **/
2930 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2931 {
2932         struct i40e_mac_filter *f, *add_f;
2933         struct hlist_node *h;
2934         int bkt;
2935
2936         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2937                 if (f->state == I40E_FILTER_REMOVE)
2938                         continue;
2939                 add_f = i40e_add_filter(vsi, f->macaddr, vid);
2940                 if (!add_f) {
2941                         dev_info(&vsi->back->pdev->dev,
2942                                  "Could not add vlan filter %d for %pM\n",
2943                                  vid, f->macaddr);
2944                         return -ENOMEM;
2945                 }
2946         }
2947
2948         return 0;
2949 }
2950
2951 /**
2952  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
2953  * @vsi: the VSI being configured
2954  * @vid: VLAN id to be added
2955  **/
2956 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
2957 {
2958         int err;
2959
2960         if (vsi->info.pvid)
2961                 return -EINVAL;
2962
2963         /* The network stack will attempt to add VID=0, with the intention to
2964          * receive priority tagged packets with a VLAN of 0. Our HW receives
2965          * these packets by default when configured to receive untagged
2966          * packets, so we don't need to add a filter for this case.
2967          * Additionally, HW interprets adding a VID=0 filter as meaning to
2968          * receive *only* tagged traffic and stops receiving untagged traffic.
2969          * Thus, we do not want to actually add a filter for VID=0
2970          */
2971         if (!vid)
2972                 return 0;
2973
2974         /* Locked once because all functions invoked below iterates list*/
2975         spin_lock_bh(&vsi->mac_filter_hash_lock);
2976         err = i40e_add_vlan_all_mac(vsi, vid);
2977         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2978         if (err)
2979                 return err;
2980
2981         /* schedule our worker thread which will take care of
2982          * applying the new filter changes
2983          */
2984         i40e_service_event_schedule(vsi->back);
2985         return 0;
2986 }
2987
2988 /**
2989  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
2990  * @vsi: the vsi being configured
2991  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
2992  *
2993  * This function should be used to remove all VLAN filters which match the
2994  * given VID. It does not schedule the service event and does not take the
2995  * mac_filter_hash_lock so it may be combined with other operations under
2996  * a single invocation of the mac_filter_hash_lock.
2997  *
2998  * NOTE: this function expects to be called while under the
2999  * mac_filter_hash_lock
3000  */
3001 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3002 {
3003         struct i40e_mac_filter *f;
3004         struct hlist_node *h;
3005         int bkt;
3006
3007         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3008                 if (f->vlan == vid)
3009                         __i40e_del_filter(vsi, f);
3010         }
3011 }
3012
3013 /**
3014  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3015  * @vsi: the VSI being configured
3016  * @vid: VLAN id to be removed
3017  **/
3018 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3019 {
3020         if (!vid || vsi->info.pvid)
3021                 return;
3022
3023         spin_lock_bh(&vsi->mac_filter_hash_lock);
3024         i40e_rm_vlan_all_mac(vsi, vid);
3025         spin_unlock_bh(&vsi->mac_filter_hash_lock);
3026
3027         /* schedule our worker thread which will take care of
3028          * applying the new filter changes
3029          */
3030         i40e_service_event_schedule(vsi->back);
3031 }
3032
3033 /**
3034  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3035  * @netdev: network interface to be adjusted
3036  * @proto: unused protocol value
3037  * @vid: vlan id to be added
3038  *
3039  * net_device_ops implementation for adding vlan ids
3040  **/
3041 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3042                                 __always_unused __be16 proto, u16 vid)
3043 {
3044         struct i40e_netdev_priv *np = netdev_priv(netdev);
3045         struct i40e_vsi *vsi = np->vsi;
3046         int ret = 0;
3047
3048         if (vid >= VLAN_N_VID)
3049                 return -EINVAL;
3050
3051         ret = i40e_vsi_add_vlan(vsi, vid);
3052         if (!ret)
3053                 set_bit(vid, vsi->active_vlans);
3054
3055         return ret;
3056 }
3057
3058 /**
3059  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3060  * @netdev: network interface to be adjusted
3061  * @proto: unused protocol value
3062  * @vid: vlan id to be added
3063  **/
3064 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3065                                     __always_unused __be16 proto, u16 vid)
3066 {
3067         struct i40e_netdev_priv *np = netdev_priv(netdev);
3068         struct i40e_vsi *vsi = np->vsi;
3069
3070         if (vid >= VLAN_N_VID)
3071                 return;
3072         set_bit(vid, vsi->active_vlans);
3073 }
3074
3075 /**
3076  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3077  * @netdev: network interface to be adjusted
3078  * @proto: unused protocol value
3079  * @vid: vlan id to be removed
3080  *
3081  * net_device_ops implementation for removing vlan ids
3082  **/
3083 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3084                                  __always_unused __be16 proto, u16 vid)
3085 {
3086         struct i40e_netdev_priv *np = netdev_priv(netdev);
3087         struct i40e_vsi *vsi = np->vsi;
3088
3089         /* return code is ignored as there is nothing a user
3090          * can do about failure to remove and a log message was
3091          * already printed from the other function
3092          */
3093         i40e_vsi_kill_vlan(vsi, vid);
3094
3095         clear_bit(vid, vsi->active_vlans);
3096
3097         return 0;
3098 }
3099
3100 /**
3101  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3102  * @vsi: the vsi being brought back up
3103  **/
3104 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3105 {
3106         u16 vid;
3107
3108         if (!vsi->netdev)
3109                 return;
3110
3111         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3112                 i40e_vlan_stripping_enable(vsi);
3113         else
3114                 i40e_vlan_stripping_disable(vsi);
3115
3116         for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3117                 i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3118                                         vid);
3119 }
3120
3121 /**
3122  * i40e_vsi_add_pvid - Add pvid for the VSI
3123  * @vsi: the vsi being adjusted
3124  * @vid: the vlan id to set as a PVID
3125  **/
3126 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3127 {
3128         struct i40e_vsi_context ctxt;
3129         i40e_status ret;
3130
3131         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3132         vsi->info.pvid = cpu_to_le16(vid);
3133         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3134                                     I40E_AQ_VSI_PVLAN_INSERT_PVID |
3135                                     I40E_AQ_VSI_PVLAN_EMOD_STR;
3136
3137         ctxt.seid = vsi->seid;
3138         ctxt.info = vsi->info;
3139         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3140         if (ret) {
3141                 dev_info(&vsi->back->pdev->dev,
3142                          "add pvid failed, err %s aq_err %s\n",
3143                          i40e_stat_str(&vsi->back->hw, ret),
3144                          i40e_aq_str(&vsi->back->hw,
3145                                      vsi->back->hw.aq.asq_last_status));
3146                 return -ENOENT;
3147         }
3148
3149         return 0;
3150 }
3151
3152 /**
3153  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3154  * @vsi: the vsi being adjusted
3155  *
3156  * Just use the vlan_rx_register() service to put it back to normal
3157  **/
3158 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3159 {
3160         vsi->info.pvid = 0;
3161
3162         i40e_vlan_stripping_disable(vsi);
3163 }
3164
3165 /**
3166  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3167  * @vsi: ptr to the VSI
3168  *
3169  * If this function returns with an error, then it's possible one or
3170  * more of the rings is populated (while the rest are not).  It is the
3171  * callers duty to clean those orphaned rings.
3172  *
3173  * Return 0 on success, negative on failure
3174  **/
3175 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3176 {
3177         int i, err = 0;
3178
3179         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3180                 err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3181
3182         if (!i40e_enabled_xdp_vsi(vsi))
3183                 return err;
3184
3185         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3186                 err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3187
3188         return err;
3189 }
3190
3191 /**
3192  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3193  * @vsi: ptr to the VSI
3194  *
3195  * Free VSI's transmit software resources
3196  **/
3197 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3198 {
3199         int i;
3200
3201         if (vsi->tx_rings) {
3202                 for (i = 0; i < vsi->num_queue_pairs; i++)
3203                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3204                                 i40e_free_tx_resources(vsi->tx_rings[i]);
3205         }
3206
3207         if (vsi->xdp_rings) {
3208                 for (i = 0; i < vsi->num_queue_pairs; i++)
3209                         if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3210                                 i40e_free_tx_resources(vsi->xdp_rings[i]);
3211         }
3212 }
3213
3214 /**
3215  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3216  * @vsi: ptr to the VSI
3217  *
3218  * If this function returns with an error, then it's possible one or
3219  * more of the rings is populated (while the rest are not).  It is the
3220  * callers duty to clean those orphaned rings.
3221  *
3222  * Return 0 on success, negative on failure
3223  **/
3224 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3225 {
3226         int i, err = 0;
3227
3228         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3229                 err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3230         return err;
3231 }
3232
3233 /**
3234  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3235  * @vsi: ptr to the VSI
3236  *
3237  * Free all receive software resources
3238  **/
3239 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3240 {
3241         int i;
3242
3243         if (!vsi->rx_rings)
3244                 return;
3245
3246         for (i = 0; i < vsi->num_queue_pairs; i++)
3247                 if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3248                         i40e_free_rx_resources(vsi->rx_rings[i]);
3249 }
3250
3251 /**
3252  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3253  * @ring: The Tx ring to configure
3254  *
3255  * This enables/disables XPS for a given Tx descriptor ring
3256  * based on the TCs enabled for the VSI that ring belongs to.
3257  **/
3258 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3259 {
3260         int cpu;
3261
3262         if (!ring->q_vector || !ring->netdev || ring->ch)
3263                 return;
3264
3265         /* We only initialize XPS once, so as not to overwrite user settings */
3266         if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3267                 return;
3268
3269         cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3270         netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3271                             ring->queue_index);
3272 }
3273
3274 /**
3275  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3276  * @ring: The Tx or Rx ring
3277  *
3278  * Returns the AF_XDP buffer pool or NULL.
3279  **/
3280 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3281 {
3282         bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3283         int qid = ring->queue_index;
3284
3285         if (ring_is_xdp(ring))
3286                 qid -= ring->vsi->alloc_queue_pairs;
3287
3288         if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3289                 return NULL;
3290
3291         return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3292 }
3293
3294 /**
3295  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3296  * @ring: The Tx ring to configure
3297  *
3298  * Configure the Tx descriptor ring in the HMC context.
3299  **/
3300 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3301 {
3302         struct i40e_vsi *vsi = ring->vsi;
3303         u16 pf_q = vsi->base_queue + ring->queue_index;
3304         struct i40e_hw *hw = &vsi->back->hw;
3305         struct i40e_hmc_obj_txq tx_ctx;
3306         i40e_status err = 0;
3307         u32 qtx_ctl = 0;
3308
3309         if (ring_is_xdp(ring))
3310                 ring->xsk_pool = i40e_xsk_pool(ring);
3311
3312         /* some ATR related tx ring init */
3313         if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3314                 ring->atr_sample_rate = vsi->back->atr_sample_rate;
3315                 ring->atr_count = 0;
3316         } else {
3317                 ring->atr_sample_rate = 0;
3318         }
3319
3320         /* configure XPS */
3321         i40e_config_xps_tx_ring(ring);
3322
3323         /* clear the context structure first */
3324         memset(&tx_ctx, 0, sizeof(tx_ctx));
3325
3326         tx_ctx.new_context = 1;
3327         tx_ctx.base = (ring->dma / 128);
3328         tx_ctx.qlen = ring->count;
3329         tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3330                                                I40E_FLAG_FD_ATR_ENABLED));
3331         tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3332         /* FDIR VSI tx ring can still use RS bit and writebacks */
3333         if (vsi->type != I40E_VSI_FDIR)
3334                 tx_ctx.head_wb_ena = 1;
3335         tx_ctx.head_wb_addr = ring->dma +
3336                               (ring->count * sizeof(struct i40e_tx_desc));
3337
3338         /* As part of VSI creation/update, FW allocates certain
3339          * Tx arbitration queue sets for each TC enabled for
3340          * the VSI. The FW returns the handles to these queue
3341          * sets as part of the response buffer to Add VSI,
3342          * Update VSI, etc. AQ commands. It is expected that
3343          * these queue set handles be associated with the Tx
3344          * queues by the driver as part of the TX queue context
3345          * initialization. This has to be done regardless of
3346          * DCB as by default everything is mapped to TC0.
3347          */
3348
3349         if (ring->ch)
3350                 tx_ctx.rdylist =
3351                         le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3352
3353         else
3354                 tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3355
3356         tx_ctx.rdylist_act = 0;
3357
3358         /* clear the context in the HMC */
3359         err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3360         if (err) {
3361                 dev_info(&vsi->back->pdev->dev,
3362                          "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3363                          ring->queue_index, pf_q, err);
3364                 return -ENOMEM;
3365         }
3366
3367         /* set the context in the HMC */
3368         err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3369         if (err) {
3370                 dev_info(&vsi->back->pdev->dev,
3371                          "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3372                          ring->queue_index, pf_q, err);
3373                 return -ENOMEM;
3374         }
3375
3376         /* Now associate this queue with this PCI function */
3377         if (ring->ch) {
3378                 if (ring->ch->type == I40E_VSI_VMDQ2)
3379                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3380                 else
3381                         return -EINVAL;
3382
3383                 qtx_ctl |= (ring->ch->vsi_number <<
3384                             I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3385                             I40E_QTX_CTL_VFVM_INDX_MASK;
3386         } else {
3387                 if (vsi->type == I40E_VSI_VMDQ2) {
3388                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3389                         qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3390                                     I40E_QTX_CTL_VFVM_INDX_MASK;
3391                 } else {
3392                         qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3393                 }
3394         }
3395
3396         qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3397                     I40E_QTX_CTL_PF_INDX_MASK);
3398         wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3399         i40e_flush(hw);
3400
3401         /* cache tail off for easier writes later */
3402         ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3403
3404         return 0;
3405 }
3406
3407 /**
3408  * i40e_rx_offset - Return expected offset into page to access data
3409  * @rx_ring: Ring we are requesting offset of
3410  *
3411  * Returns the offset value for ring into the data buffer.
3412  */
3413 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3414 {
3415         return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3416 }
3417
3418 /**
3419  * i40e_configure_rx_ring - Configure a receive ring context
3420  * @ring: The Rx ring to configure
3421  *
3422  * Configure the Rx descriptor ring in the HMC context.
3423  **/
3424 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3425 {
3426         struct i40e_vsi *vsi = ring->vsi;
3427         u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3428         u16 pf_q = vsi->base_queue + ring->queue_index;
3429         struct i40e_hw *hw = &vsi->back->hw;
3430         struct i40e_hmc_obj_rxq rx_ctx;
3431         i40e_status err = 0;
3432         bool ok;
3433         int ret;
3434
3435         bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3436
3437         /* clear the context structure first */
3438         memset(&rx_ctx, 0, sizeof(rx_ctx));
3439
3440         if (ring->vsi->type == I40E_VSI_MAIN)
3441                 xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3442
3443         kfree(ring->rx_bi);
3444         ring->xsk_pool = i40e_xsk_pool(ring);
3445         if (ring->xsk_pool) {
3446                 ret = i40e_alloc_rx_bi_zc(ring);
3447                 if (ret)
3448                         return ret;
3449                 ring->rx_buf_len =
3450                   xsk_pool_get_rx_frame_size(ring->xsk_pool);
3451                 /* For AF_XDP ZC, we disallow packets to span on
3452                  * multiple buffers, thus letting us skip that
3453                  * handling in the fast-path.
3454                  */
3455                 chain_len = 1;
3456                 ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3457                                                  MEM_TYPE_XSK_BUFF_POOL,
3458                                                  NULL);
3459                 if (ret)
3460                         return ret;
3461                 dev_info(&vsi->back->pdev->dev,
3462                          "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3463                          ring->queue_index);
3464
3465         } else {
3466                 ret = i40e_alloc_rx_bi(ring);
3467                 if (ret)
3468                         return ret;
3469                 ring->rx_buf_len = vsi->rx_buf_len;
3470                 if (ring->vsi->type == I40E_VSI_MAIN) {
3471                         ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3472                                                          MEM_TYPE_PAGE_SHARED,
3473                                                          NULL);
3474                         if (ret)
3475                                 return ret;
3476                 }
3477         }
3478
3479         rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3480                                     BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3481
3482         rx_ctx.base = (ring->dma / 128);
3483         rx_ctx.qlen = ring->count;
3484
3485         /* use 16 byte descriptors */
3486         rx_ctx.dsize = 0;
3487
3488         /* descriptor type is always zero
3489          * rx_ctx.dtype = 0;
3490          */
3491         rx_ctx.hsplit_0 = 0;
3492
3493         rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3494         if (hw->revision_id == 0)
3495                 rx_ctx.lrxqthresh = 0;
3496         else
3497                 rx_ctx.lrxqthresh = 1;
3498         rx_ctx.crcstrip = 1;
3499         rx_ctx.l2tsel = 1;
3500         /* this controls whether VLAN is stripped from inner headers */
3501         rx_ctx.showiv = 0;
3502         /* set the prefena field to 1 because the manual says to */
3503         rx_ctx.prefena = 1;
3504
3505         /* clear the context in the HMC */
3506         err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3507         if (err) {
3508                 dev_info(&vsi->back->pdev->dev,
3509                          "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3510                          ring->queue_index, pf_q, err);
3511                 return -ENOMEM;
3512         }
3513
3514         /* set the context in the HMC */
3515         err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3516         if (err) {
3517                 dev_info(&vsi->back->pdev->dev,
3518                          "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3519                          ring->queue_index, pf_q, err);
3520                 return -ENOMEM;
3521         }
3522
3523         /* configure Rx buffer alignment */
3524         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3525                 clear_ring_build_skb_enabled(ring);
3526         else
3527                 set_ring_build_skb_enabled(ring);
3528
3529         ring->rx_offset = i40e_rx_offset(ring);
3530
3531         /* cache tail for quicker writes, and clear the reg before use */
3532         ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3533         writel(0, ring->tail);
3534
3535         if (ring->xsk_pool) {
3536                 xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3537                 ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3538         } else {
3539                 ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3540         }
3541         if (!ok) {
3542                 /* Log this in case the user has forgotten to give the kernel
3543                  * any buffers, even later in the application.
3544                  */
3545                 dev_info(&vsi->back->pdev->dev,
3546                          "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3547                          ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3548                          ring->queue_index, pf_q);
3549         }
3550
3551         return 0;
3552 }
3553
3554 /**
3555  * i40e_vsi_configure_tx - Configure the VSI for Tx
3556  * @vsi: VSI structure describing this set of rings and resources
3557  *
3558  * Configure the Tx VSI for operation.
3559  **/
3560 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3561 {
3562         int err = 0;
3563         u16 i;
3564
3565         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3566                 err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3567
3568         if (err || !i40e_enabled_xdp_vsi(vsi))
3569                 return err;
3570
3571         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3572                 err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3573
3574         return err;
3575 }
3576
3577 /**
3578  * i40e_vsi_configure_rx - Configure the VSI for Rx
3579  * @vsi: the VSI being configured
3580  *
3581  * Configure the Rx VSI for operation.
3582  **/
3583 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3584 {
3585         int err = 0;
3586         u16 i;
3587
3588         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3589                 vsi->max_frame = I40E_MAX_RXBUFFER;
3590                 vsi->rx_buf_len = I40E_RXBUFFER_2048;
3591 #if (PAGE_SIZE < 8192)
3592         } else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3593                    (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3594                 vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3595                 vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3596 #endif
3597         } else {
3598                 vsi->max_frame = I40E_MAX_RXBUFFER;
3599                 vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3600                                                        I40E_RXBUFFER_2048;
3601         }
3602
3603         /* set up individual rings */
3604         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3605                 err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3606
3607         return err;
3608 }
3609
3610 /**
3611  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3612  * @vsi: ptr to the VSI
3613  **/
3614 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3615 {
3616         struct i40e_ring *tx_ring, *rx_ring;
3617         u16 qoffset, qcount;
3618         int i, n;
3619
3620         if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3621                 /* Reset the TC information */
3622                 for (i = 0; i < vsi->num_queue_pairs; i++) {
3623                         rx_ring = vsi->rx_rings[i];
3624                         tx_ring = vsi->tx_rings[i];
3625                         rx_ring->dcb_tc = 0;
3626                         tx_ring->dcb_tc = 0;
3627                 }
3628                 return;
3629         }
3630
3631         for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3632                 if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3633                         continue;
3634
3635                 qoffset = vsi->tc_config.tc_info[n].qoffset;
3636                 qcount = vsi->tc_config.tc_info[n].qcount;
3637                 for (i = qoffset; i < (qoffset + qcount); i++) {
3638                         rx_ring = vsi->rx_rings[i];
3639                         tx_ring = vsi->tx_rings[i];
3640                         rx_ring->dcb_tc = n;
3641                         tx_ring->dcb_tc = n;
3642                 }
3643         }
3644 }
3645
3646 /**
3647  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3648  * @vsi: ptr to the VSI
3649  **/
3650 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3651 {
3652         if (vsi->netdev)
3653                 i40e_set_rx_mode(vsi->netdev);
3654 }
3655
3656 /**
3657  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3658  * @pf: Pointer to the targeted PF
3659  *
3660  * Set all flow director counters to 0.
3661  */
3662 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3663 {
3664         pf->fd_tcp4_filter_cnt = 0;
3665         pf->fd_udp4_filter_cnt = 0;
3666         pf->fd_sctp4_filter_cnt = 0;
3667         pf->fd_ip4_filter_cnt = 0;
3668         pf->fd_tcp6_filter_cnt = 0;
3669         pf->fd_udp6_filter_cnt = 0;
3670         pf->fd_sctp6_filter_cnt = 0;
3671         pf->fd_ip6_filter_cnt = 0;
3672 }
3673
3674 /**
3675  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3676  * @vsi: Pointer to the targeted VSI
3677  *
3678  * This function replays the hlist on the hw where all the SB Flow Director
3679  * filters were saved.
3680  **/
3681 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3682 {
3683         struct i40e_fdir_filter *filter;
3684         struct i40e_pf *pf = vsi->back;
3685         struct hlist_node *node;
3686
3687         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3688                 return;
3689
3690         /* Reset FDir counters as we're replaying all existing filters */
3691         i40e_reset_fdir_filter_cnt(pf);
3692
3693         hlist_for_each_entry_safe(filter, node,
3694                                   &pf->fdir_filter_list, fdir_node) {
3695                 i40e_add_del_fdir(vsi, filter, true);
3696         }
3697 }
3698
3699 /**
3700  * i40e_vsi_configure - Set up the VSI for action
3701  * @vsi: the VSI being configured
3702  **/
3703 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3704 {
3705         int err;
3706
3707         i40e_set_vsi_rx_mode(vsi);
3708         i40e_restore_vlan(vsi);
3709         i40e_vsi_config_dcb_rings(vsi);
3710         err = i40e_vsi_configure_tx(vsi);
3711         if (!err)
3712                 err = i40e_vsi_configure_rx(vsi);
3713
3714         return err;
3715 }
3716
3717 /**
3718  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3719  * @vsi: the VSI being configured
3720  **/
3721 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3722 {
3723         bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3724         struct i40e_pf *pf = vsi->back;
3725         struct i40e_hw *hw = &pf->hw;
3726         u16 vector;
3727         int i, q;
3728         u32 qp;
3729
3730         /* The interrupt indexing is offset by 1 in the PFINT_ITRn
3731          * and PFINT_LNKLSTn registers, e.g.:
3732          *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3733          */
3734         qp = vsi->base_queue;
3735         vector = vsi->base_vector;
3736         for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3737                 struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3738
3739                 q_vector->rx.next_update = jiffies + 1;
3740                 q_vector->rx.target_itr =
3741                         ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3742                 wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3743                      q_vector->rx.target_itr >> 1);
3744                 q_vector->rx.current_itr = q_vector->rx.target_itr;
3745
3746                 q_vector->tx.next_update = jiffies + 1;
3747                 q_vector->tx.target_itr =
3748                         ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3749                 wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3750                      q_vector->tx.target_itr >> 1);
3751                 q_vector->tx.current_itr = q_vector->tx.target_itr;
3752
3753                 wr32(hw, I40E_PFINT_RATEN(vector - 1),
3754                      i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3755
3756                 /* Linked list for the queuepairs assigned to this vector */
3757                 wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3758                 for (q = 0; q < q_vector->num_ringpairs; q++) {
3759                         u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3760                         u32 val;
3761
3762                         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3763                               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3764                               (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3765                               (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3766                               (I40E_QUEUE_TYPE_TX <<
3767                                I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3768
3769                         wr32(hw, I40E_QINT_RQCTL(qp), val);
3770
3771                         if (has_xdp) {
3772                                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3773                                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3774                                       (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3775                                       (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3776                                       (I40E_QUEUE_TYPE_TX <<
3777                                        I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3778
3779                                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3780                         }
3781
3782                         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3783                               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3784                               (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3785                               ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3786                               (I40E_QUEUE_TYPE_RX <<
3787                                I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3788
3789                         /* Terminate the linked list */
3790                         if (q == (q_vector->num_ringpairs - 1))
3791                                 val |= (I40E_QUEUE_END_OF_LIST <<
3792                                         I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3793
3794                         wr32(hw, I40E_QINT_TQCTL(qp), val);
3795                         qp++;
3796                 }
3797         }
3798
3799         i40e_flush(hw);
3800 }
3801
3802 /**
3803  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3804  * @pf: pointer to private device data structure
3805  **/
3806 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3807 {
3808         struct i40e_hw *hw = &pf->hw;
3809         u32 val;
3810
3811         /* clear things first */
3812         wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3813         rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3814
3815         val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3816               I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3817               I40E_PFINT_ICR0_ENA_GRST_MASK          |
3818               I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3819               I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3820               I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3821               I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3822               I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3823
3824         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3825                 val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3826
3827         if (pf->flags & I40E_FLAG_PTP)
3828                 val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3829
3830         wr32(hw, I40E_PFINT_ICR0_ENA, val);
3831
3832         /* SW_ITR_IDX = 0, but don't change INTENA */
3833         wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3834                                         I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3835
3836         /* OTHER_ITR_IDX = 0 */
3837         wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3838 }
3839
3840 /**
3841  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3842  * @vsi: the VSI being configured
3843  **/
3844 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3845 {
3846         u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3847         struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3848         struct i40e_pf *pf = vsi->back;
3849         struct i40e_hw *hw = &pf->hw;
3850         u32 val;
3851
3852         /* set the ITR configuration */
3853         q_vector->rx.next_update = jiffies + 1;
3854         q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3855         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
3856         q_vector->rx.current_itr = q_vector->rx.target_itr;
3857         q_vector->tx.next_update = jiffies + 1;
3858         q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3859         wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
3860         q_vector->tx.current_itr = q_vector->tx.target_itr;
3861
3862         i40e_enable_misc_int_causes(pf);
3863
3864         /* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3865         wr32(hw, I40E_PFINT_LNKLST0, 0);
3866
3867         /* Associate the queue pair to the vector and enable the queue int */
3868         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK                   |
3869               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3870               (nextqp      << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3871               (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3872
3873         wr32(hw, I40E_QINT_RQCTL(0), val);
3874
3875         if (i40e_enabled_xdp_vsi(vsi)) {
3876                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                 |
3877                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
3878                       (I40E_QUEUE_TYPE_TX
3879                        << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3880
3881                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3882         }
3883
3884         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                  |
3885               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3886               (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3887
3888         wr32(hw, I40E_QINT_TQCTL(0), val);
3889         i40e_flush(hw);
3890 }
3891
3892 /**
3893  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
3894  * @pf: board private structure
3895  **/
3896 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
3897 {
3898         struct i40e_hw *hw = &pf->hw;
3899
3900         wr32(hw, I40E_PFINT_DYN_CTL0,
3901              I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
3902         i40e_flush(hw);
3903 }
3904
3905 /**
3906  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
3907  * @pf: board private structure
3908  **/
3909 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
3910 {
3911         struct i40e_hw *hw = &pf->hw;
3912         u32 val;
3913
3914         val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
3915               I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
3916               (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
3917
3918         wr32(hw, I40E_PFINT_DYN_CTL0, val);
3919         i40e_flush(hw);
3920 }
3921
3922 /**
3923  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
3924  * @irq: interrupt number
3925  * @data: pointer to a q_vector
3926  **/
3927 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
3928 {
3929         struct i40e_q_vector *q_vector = data;
3930
3931         if (!q_vector->tx.ring && !q_vector->rx.ring)
3932                 return IRQ_HANDLED;
3933
3934         napi_schedule_irqoff(&q_vector->napi);
3935
3936         return IRQ_HANDLED;
3937 }
3938
3939 /**
3940  * i40e_irq_affinity_notify - Callback for affinity changes
3941  * @notify: context as to what irq was changed
3942  * @mask: the new affinity mask
3943  *
3944  * This is a callback function used by the irq_set_affinity_notifier function
3945  * so that we may register to receive changes to the irq affinity masks.
3946  **/
3947 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
3948                                      const cpumask_t *mask)
3949 {
3950         struct i40e_q_vector *q_vector =
3951                 container_of(notify, struct i40e_q_vector, affinity_notify);
3952
3953         cpumask_copy(&q_vector->affinity_mask, mask);
3954 }
3955
3956 /**
3957  * i40e_irq_affinity_release - Callback for affinity notifier release
3958  * @ref: internal core kernel usage
3959  *
3960  * This is a callback function used by the irq_set_affinity_notifier function
3961  * to inform the current notification subscriber that they will no longer
3962  * receive notifications.
3963  **/
3964 static void i40e_irq_affinity_release(struct kref *ref) {}
3965
3966 /**
3967  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
3968  * @vsi: the VSI being configured
3969  * @basename: name for the vector
3970  *
3971  * Allocates MSI-X vectors and requests interrupts from the kernel.
3972  **/
3973 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
3974 {
3975         int q_vectors = vsi->num_q_vectors;
3976         struct i40e_pf *pf = vsi->back;
3977         int base = vsi->base_vector;
3978         int rx_int_idx = 0;
3979         int tx_int_idx = 0;
3980         int vector, err;
3981         int irq_num;
3982         int cpu;
3983
3984         for (vector = 0; vector < q_vectors; vector++) {
3985                 struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
3986
3987                 irq_num = pf->msix_entries[base + vector].vector;
3988
3989                 if (q_vector->tx.ring && q_vector->rx.ring) {
3990                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3991                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
3992                         tx_int_idx++;
3993                 } else if (q_vector->rx.ring) {
3994                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3995                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
3996                 } else if (q_vector->tx.ring) {
3997                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3998                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
3999                 } else {
4000                         /* skip this unused q_vector */
4001                         continue;
4002                 }
4003                 err = request_irq(irq_num,
4004                                   vsi->irq_handler,
4005                                   0,
4006                                   q_vector->name,
4007                                   q_vector);
4008                 if (err) {
4009                         dev_info(&pf->pdev->dev,
4010                                  "MSIX request_irq failed, error: %d\n", err);
4011                         goto free_queue_irqs;
4012                 }
4013
4014                 /* register for affinity change notifications */
4015                 q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4016                 q_vector->affinity_notify.release = i40e_irq_affinity_release;
4017                 irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4018                 /* Spread affinity hints out across online CPUs.
4019                  *
4020                  * get_cpu_mask returns a static constant mask with
4021                  * a permanent lifetime so it's ok to pass to
4022                  * irq_update_affinity_hint without making a copy.
4023                  */
4024                 cpu = cpumask_local_spread(q_vector->v_idx, -1);
4025                 irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4026         }
4027
4028         vsi->irqs_ready = true;
4029         return 0;
4030
4031 free_queue_irqs:
4032         while (vector) {
4033                 vector--;
4034                 irq_num = pf->msix_entries[base + vector].vector;
4035                 irq_set_affinity_notifier(irq_num, NULL);
4036                 irq_update_affinity_hint(irq_num, NULL);
4037                 free_irq(irq_num, &vsi->q_vectors[vector]);
4038         }
4039         return err;
4040 }
4041
4042 /**
4043  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4044  * @vsi: the VSI being un-configured
4045  **/
4046 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4047 {
4048         struct i40e_pf *pf = vsi->back;
4049         struct i40e_hw *hw = &pf->hw;
4050         int base = vsi->base_vector;
4051         int i;
4052
4053         /* disable interrupt causation from each queue */
4054         for (i = 0; i < vsi->num_queue_pairs; i++) {
4055                 u32 val;
4056
4057                 val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4058                 val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4059                 wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4060
4061                 val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4062                 val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4063                 wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4064
4065                 if (!i40e_enabled_xdp_vsi(vsi))
4066                         continue;
4067                 wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4068         }
4069
4070         /* disable each interrupt */
4071         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4072                 for (i = vsi->base_vector;
4073                      i < (vsi->num_q_vectors + vsi->base_vector); i++)
4074                         wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4075
4076                 i40e_flush(hw);
4077                 for (i = 0; i < vsi->num_q_vectors; i++)
4078                         synchronize_irq(pf->msix_entries[i + base].vector);
4079         } else {
4080                 /* Legacy and MSI mode - this stops all interrupt handling */
4081                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4082                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4083                 i40e_flush(hw);
4084                 synchronize_irq(pf->pdev->irq);
4085         }
4086 }
4087
4088 /**
4089  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4090  * @vsi: the VSI being configured
4091  **/
4092 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4093 {
4094         struct i40e_pf *pf = vsi->back;
4095         int i;
4096
4097         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4098                 for (i = 0; i < vsi->num_q_vectors; i++)
4099                         i40e_irq_dynamic_enable(vsi, i);
4100         } else {
4101                 i40e_irq_dynamic_enable_icr0(pf);
4102         }
4103
4104         i40e_flush(&pf->hw);
4105         return 0;
4106 }
4107
4108 /**
4109  * i40e_free_misc_vector - Free the vector that handles non-queue events
4110  * @pf: board private structure
4111  **/
4112 static void i40e_free_misc_vector(struct i40e_pf *pf)
4113 {
4114         /* Disable ICR 0 */
4115         wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4116         i40e_flush(&pf->hw);
4117
4118         if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4119                 synchronize_irq(pf->msix_entries[0].vector);
4120                 free_irq(pf->msix_entries[0].vector, pf);
4121                 clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4122         }
4123 }
4124
4125 /**
4126  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4127  * @irq: interrupt number
4128  * @data: pointer to a q_vector
4129  *
4130  * This is the handler used for all MSI/Legacy interrupts, and deals
4131  * with both queue and non-queue interrupts.  This is also used in
4132  * MSIX mode to handle the non-queue interrupts.
4133  **/
4134 static irqreturn_t i40e_intr(int irq, void *data)
4135 {
4136         struct i40e_pf *pf = (struct i40e_pf *)data;
4137         struct i40e_hw *hw = &pf->hw;
4138         irqreturn_t ret = IRQ_NONE;
4139         u32 icr0, icr0_remaining;
4140         u32 val, ena_mask;
4141
4142         icr0 = rd32(hw, I40E_PFINT_ICR0);
4143         ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4144
4145         /* if sharing a legacy IRQ, we might get called w/o an intr pending */
4146         if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4147                 goto enable_intr;
4148
4149         /* if interrupt but no bits showing, must be SWINT */
4150         if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4151             (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4152                 pf->sw_int_count++;
4153
4154         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4155             (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4156                 ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4157                 dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4158                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4159         }
4160
4161         /* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4162         if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4163                 struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4164                 struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4165
4166                 /* We do not have a way to disarm Queue causes while leaving
4167                  * interrupt enabled for all other causes, ideally
4168                  * interrupt should be disabled while we are in NAPI but
4169                  * this is not a performance path and napi_schedule()
4170                  * can deal with rescheduling.
4171                  */
4172                 if (!test_bit(__I40E_DOWN, pf->state))
4173                         napi_schedule_irqoff(&q_vector->napi);
4174         }
4175
4176         if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4177                 ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4178                 set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4179                 i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4180         }
4181
4182         if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4183                 ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4184                 set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4185         }
4186
4187         if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4188                 /* disable any further VFLR event notifications */
4189                 if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4190                         u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4191
4192                         reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4193                         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4194                 } else {
4195                         ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4196                         set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4197                 }
4198         }
4199
4200         if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4201                 if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4202                         set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4203                 ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4204                 val = rd32(hw, I40E_GLGEN_RSTAT);
4205                 val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4206                        >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4207                 if (val == I40E_RESET_CORER) {
4208                         pf->corer_count++;
4209                 } else if (val == I40E_RESET_GLOBR) {
4210                         pf->globr_count++;
4211                 } else if (val == I40E_RESET_EMPR) {
4212                         pf->empr_count++;
4213                         set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4214                 }
4215         }
4216
4217         if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4218                 icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4219                 dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4220                 dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4221                          rd32(hw, I40E_PFHMC_ERRORINFO),
4222                          rd32(hw, I40E_PFHMC_ERRORDATA));
4223         }
4224
4225         if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4226                 u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4227
4228                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4229                         schedule_work(&pf->ptp_extts0_work);
4230
4231                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4232                         i40e_ptp_tx_hwtstamp(pf);
4233
4234                 icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4235         }
4236
4237         /* If a critical error is pending we have no choice but to reset the
4238          * device.
4239          * Report and mask out any remaining unexpected interrupts.
4240          */
4241         icr0_remaining = icr0 & ena_mask;
4242         if (icr0_remaining) {
4243                 dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4244                          icr0_remaining);
4245                 if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4246                     (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4247                     (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4248                         dev_info(&pf->pdev->dev, "device will be reset\n");
4249                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4250                         i40e_service_event_schedule(pf);
4251                 }
4252                 ena_mask &= ~icr0_remaining;
4253         }
4254         ret = IRQ_HANDLED;
4255
4256 enable_intr:
4257         /* re-enable interrupt causes */
4258         wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4259         if (!test_bit(__I40E_DOWN, pf->state) ||
4260             test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4261                 i40e_service_event_schedule(pf);
4262                 i40e_irq_dynamic_enable_icr0(pf);
4263         }
4264
4265         return ret;
4266 }
4267
4268 /**
4269  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4270  * @tx_ring:  tx ring to clean
4271  * @budget:   how many cleans we're allowed
4272  *
4273  * Returns true if there's any budget left (e.g. the clean is finished)
4274  **/
4275 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4276 {
4277         struct i40e_vsi *vsi = tx_ring->vsi;
4278         u16 i = tx_ring->next_to_clean;
4279         struct i40e_tx_buffer *tx_buf;
4280         struct i40e_tx_desc *tx_desc;
4281
4282         tx_buf = &tx_ring->tx_bi[i];
4283         tx_desc = I40E_TX_DESC(tx_ring, i);
4284         i -= tx_ring->count;
4285
4286         do {
4287                 struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4288
4289                 /* if next_to_watch is not set then there is no work pending */
4290                 if (!eop_desc)
4291                         break;
4292
4293                 /* prevent any other reads prior to eop_desc */
4294                 smp_rmb();
4295
4296                 /* if the descriptor isn't done, no work yet to do */
4297                 if (!(eop_desc->cmd_type_offset_bsz &
4298                       cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4299                         break;
4300
4301                 /* clear next_to_watch to prevent false hangs */
4302                 tx_buf->next_to_watch = NULL;
4303
4304                 tx_desc->buffer_addr = 0;
4305                 tx_desc->cmd_type_offset_bsz = 0;
4306                 /* move past filter desc */
4307                 tx_buf++;
4308                 tx_desc++;
4309                 i++;
4310                 if (unlikely(!i)) {
4311                         i -= tx_ring->count;
4312                         tx_buf = tx_ring->tx_bi;
4313                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4314                 }
4315                 /* unmap skb header data */
4316                 dma_unmap_single(tx_ring->dev,
4317                                  dma_unmap_addr(tx_buf, dma),
4318                                  dma_unmap_len(tx_buf, len),
4319                                  DMA_TO_DEVICE);
4320                 if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4321                         kfree(tx_buf->raw_buf);
4322
4323                 tx_buf->raw_buf = NULL;
4324                 tx_buf->tx_flags = 0;
4325                 tx_buf->next_to_watch = NULL;
4326                 dma_unmap_len_set(tx_buf, len, 0);
4327                 tx_desc->buffer_addr = 0;
4328                 tx_desc->cmd_type_offset_bsz = 0;
4329
4330                 /* move us past the eop_desc for start of next FD desc */
4331                 tx_buf++;
4332                 tx_desc++;
4333                 i++;
4334                 if (unlikely(!i)) {
4335                         i -= tx_ring->count;
4336                         tx_buf = tx_ring->tx_bi;
4337                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4338                 }
4339
4340                 /* update budget accounting */
4341                 budget--;
4342         } while (likely(budget));
4343
4344         i += tx_ring->count;
4345         tx_ring->next_to_clean = i;
4346
4347         if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4348                 i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4349
4350         return budget > 0;
4351 }
4352
4353 /**
4354  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4355  * @irq: interrupt number
4356  * @data: pointer to a q_vector
4357  **/
4358 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4359 {
4360         struct i40e_q_vector *q_vector = data;
4361         struct i40e_vsi *vsi;
4362
4363         if (!q_vector->tx.ring)
4364                 return IRQ_HANDLED;
4365
4366         vsi = q_vector->tx.ring->vsi;
4367         i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4368
4369         return IRQ_HANDLED;
4370 }
4371
4372 /**
4373  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4374  * @vsi: the VSI being configured
4375  * @v_idx: vector index
4376  * @qp_idx: queue pair index
4377  **/
4378 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4379 {
4380         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4381         struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4382         struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4383
4384         tx_ring->q_vector = q_vector;
4385         tx_ring->next = q_vector->tx.ring;
4386         q_vector->tx.ring = tx_ring;
4387         q_vector->tx.count++;
4388
4389         /* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4390         if (i40e_enabled_xdp_vsi(vsi)) {
4391                 struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4392
4393                 xdp_ring->q_vector = q_vector;
4394                 xdp_ring->next = q_vector->tx.ring;
4395                 q_vector->tx.ring = xdp_ring;
4396                 q_vector->tx.count++;
4397         }
4398
4399         rx_ring->q_vector = q_vector;
4400         rx_ring->next = q_vector->rx.ring;
4401         q_vector->rx.ring = rx_ring;
4402         q_vector->rx.count++;
4403 }
4404
4405 /**
4406  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4407  * @vsi: the VSI being configured
4408  *
4409  * This function maps descriptor rings to the queue-specific vectors
4410  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4411  * one vector per queue pair, but on a constrained vector budget, we
4412  * group the queue pairs as "efficiently" as possible.
4413  **/
4414 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4415 {
4416         int qp_remaining = vsi->num_queue_pairs;
4417         int q_vectors = vsi->num_q_vectors;
4418         int num_ringpairs;
4419         int v_start = 0;
4420         int qp_idx = 0;
4421
4422         /* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4423          * group them so there are multiple queues per vector.
4424          * It is also important to go through all the vectors available to be
4425          * sure that if we don't use all the vectors, that the remaining vectors
4426          * are cleared. This is especially important when decreasing the
4427          * number of queues in use.
4428          */
4429         for (; v_start < q_vectors; v_start++) {
4430                 struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4431
4432                 num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4433
4434                 q_vector->num_ringpairs = num_ringpairs;
4435                 q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4436
4437                 q_vector->rx.count = 0;
4438                 q_vector->tx.count = 0;
4439                 q_vector->rx.ring = NULL;
4440                 q_vector->tx.ring = NULL;
4441
4442                 while (num_ringpairs--) {
4443                         i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4444                         qp_idx++;
4445                         qp_remaining--;
4446                 }
4447         }
4448 }
4449
4450 /**
4451  * i40e_vsi_request_irq - Request IRQ from the OS
4452  * @vsi: the VSI being configured
4453  * @basename: name for the vector
4454  **/
4455 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4456 {
4457         struct i40e_pf *pf = vsi->back;
4458         int err;
4459
4460         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4461                 err = i40e_vsi_request_irq_msix(vsi, basename);
4462         else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4463                 err = request_irq(pf->pdev->irq, i40e_intr, 0,
4464                                   pf->int_name, pf);
4465         else
4466                 err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4467                                   pf->int_name, pf);
4468
4469         if (err)
4470                 dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4471
4472         return err;
4473 }
4474
4475 #ifdef CONFIG_NET_POLL_CONTROLLER
4476 /**
4477  * i40e_netpoll - A Polling 'interrupt' handler
4478  * @netdev: network interface device structure
4479  *
4480  * This is used by netconsole to send skbs without having to re-enable
4481  * interrupts.  It's not called while the normal interrupt routine is executing.
4482  **/
4483 static void i40e_netpoll(struct net_device *netdev)
4484 {
4485         struct i40e_netdev_priv *np = netdev_priv(netdev);
4486         struct i40e_vsi *vsi = np->vsi;
4487         struct i40e_pf *pf = vsi->back;
4488         int i;
4489
4490         /* if interface is down do nothing */
4491         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4492                 return;
4493
4494         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4495                 for (i = 0; i < vsi->num_q_vectors; i++)
4496                         i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4497         } else {
4498                 i40e_intr(pf->pdev->irq, netdev);
4499         }
4500 }
4501 #endif
4502
4503 #define I40E_QTX_ENA_WAIT_COUNT 50
4504
4505 /**
4506  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4507  * @pf: the PF being configured
4508  * @pf_q: the PF queue
4509  * @enable: enable or disable state of the queue
4510  *
4511  * This routine will wait for the given Tx queue of the PF to reach the
4512  * enabled or disabled state.
4513  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4514  * multiple retries; else will return 0 in case of success.
4515  **/
4516 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4517 {
4518         int i;
4519         u32 tx_reg;
4520
4521         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4522                 tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4523                 if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4524                         break;
4525
4526                 usleep_range(10, 20);
4527         }
4528         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4529                 return -ETIMEDOUT;
4530
4531         return 0;
4532 }
4533
4534 /**
4535  * i40e_control_tx_q - Start or stop a particular Tx queue
4536  * @pf: the PF structure
4537  * @pf_q: the PF queue to configure
4538  * @enable: start or stop the queue
4539  *
4540  * This function enables or disables a single queue. Note that any delay
4541  * required after the operation is expected to be handled by the caller of
4542  * this function.
4543  **/
4544 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4545 {
4546         struct i40e_hw *hw = &pf->hw;
4547         u32 tx_reg;
4548         int i;
4549
4550         /* warn the TX unit of coming changes */
4551         i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4552         if (!enable)
4553                 usleep_range(10, 20);
4554
4555         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4556                 tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4557                 if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4558                     ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4559                         break;
4560                 usleep_range(1000, 2000);
4561         }
4562
4563         /* Skip if the queue is already in the requested state */
4564         if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4565                 return;
4566
4567         /* turn on/off the queue */
4568         if (enable) {
4569                 wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4570                 tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4571         } else {
4572                 tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4573         }
4574
4575         wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4576 }
4577
4578 /**
4579  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4580  * @seid: VSI SEID
4581  * @pf: the PF structure
4582  * @pf_q: the PF queue to configure
4583  * @is_xdp: true if the queue is used for XDP
4584  * @enable: start or stop the queue
4585  **/
4586 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4587                            bool is_xdp, bool enable)
4588 {
4589         int ret;
4590
4591         i40e_control_tx_q(pf, pf_q, enable);
4592
4593         /* wait for the change to finish */
4594         ret = i40e_pf_txq_wait(pf, pf_q, enable);
4595         if (ret) {
4596                 dev_info(&pf->pdev->dev,
4597                          "VSI seid %d %sTx ring %d %sable timeout\n",
4598                          seid, (is_xdp ? "XDP " : ""), pf_q,
4599                          (enable ? "en" : "dis"));
4600         }
4601
4602         return ret;
4603 }
4604
4605 /**
4606  * i40e_vsi_enable_tx - Start a VSI's rings
4607  * @vsi: the VSI being configured
4608  **/
4609 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4610 {
4611         struct i40e_pf *pf = vsi->back;
4612         int i, pf_q, ret = 0;
4613
4614         pf_q = vsi->base_queue;
4615         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4616                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4617                                              pf_q,
4618                                              false /*is xdp*/, true);
4619                 if (ret)
4620                         break;
4621
4622                 if (!i40e_enabled_xdp_vsi(vsi))
4623                         continue;
4624
4625                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4626                                              pf_q + vsi->alloc_queue_pairs,
4627                                              true /*is xdp*/, true);
4628                 if (ret)
4629                         break;
4630         }
4631         return ret;
4632 }
4633
4634 /**
4635  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4636  * @pf: the PF being configured
4637  * @pf_q: the PF queue
4638  * @enable: enable or disable state of the queue
4639  *
4640  * This routine will wait for the given Rx queue of the PF to reach the
4641  * enabled or disabled state.
4642  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4643  * multiple retries; else will return 0 in case of success.
4644  **/
4645 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4646 {
4647         int i;
4648         u32 rx_reg;
4649
4650         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4651                 rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4652                 if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4653                         break;
4654
4655                 usleep_range(10, 20);
4656         }
4657         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4658                 return -ETIMEDOUT;
4659
4660         return 0;
4661 }
4662
4663 /**
4664  * i40e_control_rx_q - Start or stop a particular Rx queue
4665  * @pf: the PF structure
4666  * @pf_q: the PF queue to configure
4667  * @enable: start or stop the queue
4668  *
4669  * This function enables or disables a single queue. Note that
4670  * any delay required after the operation is expected to be
4671  * handled by the caller of this function.
4672  **/
4673 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4674 {
4675         struct i40e_hw *hw = &pf->hw;
4676         u32 rx_reg;
4677         int i;
4678
4679         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4680                 rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4681                 if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4682                     ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4683                         break;
4684                 usleep_range(1000, 2000);
4685         }
4686
4687         /* Skip if the queue is already in the requested state */
4688         if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4689                 return;
4690
4691         /* turn on/off the queue */
4692         if (enable)
4693                 rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4694         else
4695                 rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4696
4697         wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4698 }
4699
4700 /**
4701  * i40e_control_wait_rx_q
4702  * @pf: the PF structure
4703  * @pf_q: queue being configured
4704  * @enable: start or stop the rings
4705  *
4706  * This function enables or disables a single queue along with waiting
4707  * for the change to finish. The caller of this function should handle
4708  * the delays needed in the case of disabling queues.
4709  **/
4710 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4711 {
4712         int ret = 0;
4713
4714         i40e_control_rx_q(pf, pf_q, enable);
4715
4716         /* wait for the change to finish */
4717         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4718         if (ret)
4719                 return ret;
4720
4721         return ret;
4722 }
4723
4724 /**
4725  * i40e_vsi_enable_rx - Start a VSI's rings
4726  * @vsi: the VSI being configured
4727  **/
4728 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4729 {
4730         struct i40e_pf *pf = vsi->back;
4731         int i, pf_q, ret = 0;
4732
4733         pf_q = vsi->base_queue;
4734         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4735                 ret = i40e_control_wait_rx_q(pf, pf_q, true);
4736                 if (ret) {
4737                         dev_info(&pf->pdev->dev,
4738                                  "VSI seid %d Rx ring %d enable timeout\n",
4739                                  vsi->seid, pf_q);
4740                         break;
4741                 }
4742         }
4743
4744         return ret;
4745 }
4746
4747 /**
4748  * i40e_vsi_start_rings - Start a VSI's rings
4749  * @vsi: the VSI being configured
4750  **/
4751 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4752 {
4753         int ret = 0;
4754
4755         /* do rx first for enable and last for disable */
4756         ret = i40e_vsi_enable_rx(vsi);
4757         if (ret)
4758                 return ret;
4759         ret = i40e_vsi_enable_tx(vsi);
4760
4761         return ret;
4762 }
4763
4764 #define I40E_DISABLE_TX_GAP_MSEC        50
4765
4766 /**
4767  * i40e_vsi_stop_rings - Stop a VSI's rings
4768  * @vsi: the VSI being configured
4769  **/
4770 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4771 {
4772         struct i40e_pf *pf = vsi->back;
4773         int pf_q, err, q_end;
4774
4775         /* When port TX is suspended, don't wait */
4776         if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4777                 return i40e_vsi_stop_rings_no_wait(vsi);
4778
4779         q_end = vsi->base_queue + vsi->num_queue_pairs;
4780         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4781                 i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4782
4783         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4784                 err = i40e_control_wait_rx_q(pf, pf_q, false);
4785                 if (err)
4786                         dev_info(&pf->pdev->dev,
4787                                  "VSI seid %d Rx ring %d disable timeout\n",
4788                                  vsi->seid, pf_q);
4789         }
4790
4791         msleep(I40E_DISABLE_TX_GAP_MSEC);
4792         pf_q = vsi->base_queue;
4793         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4794                 wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4795
4796         i40e_vsi_wait_queues_disabled(vsi);
4797 }
4798
4799 /**
4800  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4801  * @vsi: the VSI being shutdown
4802  *
4803  * This function stops all the rings for a VSI but does not delay to verify
4804  * that rings have been disabled. It is expected that the caller is shutting
4805  * down multiple VSIs at once and will delay together for all the VSIs after
4806  * initiating the shutdown. This is particularly useful for shutting down lots
4807  * of VFs together. Otherwise, a large delay can be incurred while configuring
4808  * each VSI in serial.
4809  **/
4810 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4811 {
4812         struct i40e_pf *pf = vsi->back;
4813         int i, pf_q;
4814
4815         pf_q = vsi->base_queue;
4816         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4817                 i40e_control_tx_q(pf, pf_q, false);
4818                 i40e_control_rx_q(pf, pf_q, false);
4819         }
4820 }
4821
4822 /**
4823  * i40e_vsi_free_irq - Free the irq association with the OS
4824  * @vsi: the VSI being configured
4825  **/
4826 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4827 {
4828         struct i40e_pf *pf = vsi->back;
4829         struct i40e_hw *hw = &pf->hw;
4830         int base = vsi->base_vector;
4831         u32 val, qp;
4832         int i;
4833
4834         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4835                 if (!vsi->q_vectors)
4836                         return;
4837
4838                 if (!vsi->irqs_ready)
4839                         return;
4840
4841                 vsi->irqs_ready = false;
4842                 for (i = 0; i < vsi->num_q_vectors; i++) {
4843                         int irq_num;
4844                         u16 vector;
4845
4846                         vector = i + base;
4847                         irq_num = pf->msix_entries[vector].vector;
4848
4849                         /* free only the irqs that were actually requested */
4850                         if (!vsi->q_vectors[i] ||
4851                             !vsi->q_vectors[i]->num_ringpairs)
4852                                 continue;
4853
4854                         /* clear the affinity notifier in the IRQ descriptor */
4855                         irq_set_affinity_notifier(irq_num, NULL);
4856                         /* remove our suggested affinity mask for this IRQ */
4857                         irq_update_affinity_hint(irq_num, NULL);
4858                         synchronize_irq(irq_num);
4859                         free_irq(irq_num, vsi->q_vectors[i]);
4860
4861                         /* Tear down the interrupt queue link list
4862                          *
4863                          * We know that they come in pairs and always
4864                          * the Rx first, then the Tx.  To clear the
4865                          * link list, stick the EOL value into the
4866                          * next_q field of the registers.
4867                          */
4868                         val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4869                         qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4870                                 >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4871                         val |= I40E_QUEUE_END_OF_LIST
4872                                 << I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4873                         wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4874
4875                         while (qp != I40E_QUEUE_END_OF_LIST) {
4876                                 u32 next;
4877
4878                                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4879
4880                                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4881                                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4882                                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4883                                          I40E_QINT_RQCTL_INTEVENT_MASK);
4884
4885                                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4886                                          I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4887
4888                                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4889
4890                                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4891
4892                                 next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
4893                                         >> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
4894
4895                                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4896                                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4897                                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4898                                          I40E_QINT_TQCTL_INTEVENT_MASK);
4899
4900                                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4901                                          I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4902
4903                                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4904                                 qp = next;
4905                         }
4906                 }
4907         } else {
4908                 free_irq(pf->pdev->irq, pf);
4909
4910                 val = rd32(hw, I40E_PFINT_LNKLST0);
4911                 qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4912                         >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4913                 val |= I40E_QUEUE_END_OF_LIST
4914                         << I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
4915                 wr32(hw, I40E_PFINT_LNKLST0, val);
4916
4917                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4918                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4919                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4920                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4921                          I40E_QINT_RQCTL_INTEVENT_MASK);
4922
4923                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4924                         I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4925
4926                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4927
4928                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4929
4930                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4931                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4932                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4933                          I40E_QINT_TQCTL_INTEVENT_MASK);
4934
4935                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4936                         I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4937
4938                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4939         }
4940 }
4941
4942 /**
4943  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
4944  * @vsi: the VSI being configured
4945  * @v_idx: Index of vector to be freed
4946  *
4947  * This function frees the memory allocated to the q_vector.  In addition if
4948  * NAPI is enabled it will delete any references to the NAPI struct prior
4949  * to freeing the q_vector.
4950  **/
4951 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
4952 {
4953         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4954         struct i40e_ring *ring;
4955
4956         if (!q_vector)
4957                 return;
4958
4959         /* disassociate q_vector from rings */
4960         i40e_for_each_ring(ring, q_vector->tx)
4961                 ring->q_vector = NULL;
4962
4963         i40e_for_each_ring(ring, q_vector->rx)
4964                 ring->q_vector = NULL;
4965
4966         /* only VSI w/ an associated netdev is set up w/ NAPI */
4967         if (vsi->netdev)
4968                 netif_napi_del(&q_vector->napi);
4969
4970         vsi->q_vectors[v_idx] = NULL;
4971
4972         kfree_rcu(q_vector, rcu);
4973 }
4974
4975 /**
4976  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
4977  * @vsi: the VSI being un-configured
4978  *
4979  * This frees the memory allocated to the q_vectors and
4980  * deletes references to the NAPI struct.
4981  **/
4982 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
4983 {
4984         int v_idx;
4985
4986         for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
4987                 i40e_free_q_vector(vsi, v_idx);
4988 }
4989
4990 /**
4991  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
4992  * @pf: board private structure
4993  **/
4994 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
4995 {
4996         /* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
4997         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4998                 pci_disable_msix(pf->pdev);
4999                 kfree(pf->msix_entries);
5000                 pf->msix_entries = NULL;
5001                 kfree(pf->irq_pile);
5002                 pf->irq_pile = NULL;
5003         } else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
5004                 pci_disable_msi(pf->pdev);
5005         }
5006         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
5007 }
5008
5009 /**
5010  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5011  * @pf: board private structure
5012  *
5013  * We go through and clear interrupt specific resources and reset the structure
5014  * to pre-load conditions
5015  **/
5016 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5017 {
5018         int i;
5019
5020         if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5021                 i40e_free_misc_vector(pf);
5022
5023         i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5024                       I40E_IWARP_IRQ_PILE_ID);
5025
5026         i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5027         for (i = 0; i < pf->num_alloc_vsi; i++)
5028                 if (pf->vsi[i])
5029                         i40e_vsi_free_q_vectors(pf->vsi[i]);
5030         i40e_reset_interrupt_capability(pf);
5031 }
5032
5033 /**
5034  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5035  * @vsi: the VSI being configured
5036  **/
5037 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5038 {
5039         int q_idx;
5040
5041         if (!vsi->netdev)
5042                 return;
5043
5044         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5045                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5046
5047                 if (q_vector->rx.ring || q_vector->tx.ring)
5048                         napi_enable(&q_vector->napi);
5049         }
5050 }
5051
5052 /**
5053  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5054  * @vsi: the VSI being configured
5055  **/
5056 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5057 {
5058         int q_idx;
5059
5060         if (!vsi->netdev)
5061                 return;
5062
5063         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5064                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5065
5066                 if (q_vector->rx.ring || q_vector->tx.ring)
5067                         napi_disable(&q_vector->napi);
5068         }
5069 }
5070
5071 /**
5072  * i40e_vsi_close - Shut down a VSI
5073  * @vsi: the vsi to be quelled
5074  **/
5075 static void i40e_vsi_close(struct i40e_vsi *vsi)
5076 {
5077         struct i40e_pf *pf = vsi->back;
5078         if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5079                 i40e_down(vsi);
5080         i40e_vsi_free_irq(vsi);
5081         i40e_vsi_free_tx_resources(vsi);
5082         i40e_vsi_free_rx_resources(vsi);
5083         vsi->current_netdev_flags = 0;
5084         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5085         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5086                 set_bit(__I40E_CLIENT_RESET, pf->state);
5087 }
5088
5089 /**
5090  * i40e_quiesce_vsi - Pause a given VSI
5091  * @vsi: the VSI being paused
5092  **/
5093 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5094 {
5095         if (test_bit(__I40E_VSI_DOWN, vsi->state))
5096                 return;
5097
5098         set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5099         if (vsi->netdev && netif_running(vsi->netdev))
5100                 vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5101         else
5102                 i40e_vsi_close(vsi);
5103 }
5104
5105 /**
5106  * i40e_unquiesce_vsi - Resume a given VSI
5107  * @vsi: the VSI being resumed
5108  **/
5109 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5110 {
5111         if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5112                 return;
5113
5114         if (vsi->netdev && netif_running(vsi->netdev))
5115                 vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5116         else
5117                 i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5118 }
5119
5120 /**
5121  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5122  * @pf: the PF
5123  **/
5124 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5125 {
5126         int v;
5127
5128         for (v = 0; v < pf->num_alloc_vsi; v++) {
5129                 if (pf->vsi[v])
5130                         i40e_quiesce_vsi(pf->vsi[v]);
5131         }
5132 }
5133
5134 /**
5135  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5136  * @pf: the PF
5137  **/
5138 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5139 {
5140         int v;
5141
5142         for (v = 0; v < pf->num_alloc_vsi; v++) {
5143                 if (pf->vsi[v])
5144                         i40e_unquiesce_vsi(pf->vsi[v]);
5145         }
5146 }
5147
5148 /**
5149  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5150  * @vsi: the VSI being configured
5151  *
5152  * Wait until all queues on a given VSI have been disabled.
5153  **/
5154 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5155 {
5156         struct i40e_pf *pf = vsi->back;
5157         int i, pf_q, ret;
5158
5159         pf_q = vsi->base_queue;
5160         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5161                 /* Check and wait for the Tx queue */
5162                 ret = i40e_pf_txq_wait(pf, pf_q, false);
5163                 if (ret) {
5164                         dev_info(&pf->pdev->dev,
5165                                  "VSI seid %d Tx ring %d disable timeout\n",
5166                                  vsi->seid, pf_q);
5167                         return ret;
5168                 }
5169
5170                 if (!i40e_enabled_xdp_vsi(vsi))
5171                         goto wait_rx;
5172
5173                 /* Check and wait for the XDP Tx queue */
5174                 ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5175                                        false);
5176                 if (ret) {
5177                         dev_info(&pf->pdev->dev,
5178                                  "VSI seid %d XDP Tx ring %d disable timeout\n",
5179                                  vsi->seid, pf_q);
5180                         return ret;
5181                 }
5182 wait_rx:
5183                 /* Check and wait for the Rx queue */
5184                 ret = i40e_pf_rxq_wait(pf, pf_q, false);
5185                 if (ret) {
5186                         dev_info(&pf->pdev->dev,
5187                                  "VSI seid %d Rx ring %d disable timeout\n",
5188                                  vsi->seid, pf_q);
5189                         return ret;
5190                 }
5191         }
5192
5193         return 0;
5194 }
5195
5196 #ifdef CONFIG_I40E_DCB
5197 /**
5198  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5199  * @pf: the PF
5200  *
5201  * This function waits for the queues to be in disabled state for all the
5202  * VSIs that are managed by this PF.
5203  **/
5204 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5205 {
5206         int v, ret = 0;
5207
5208         for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5209                 if (pf->vsi[v]) {
5210                         ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5211                         if (ret)
5212                                 break;
5213                 }
5214         }
5215
5216         return ret;
5217 }
5218
5219 #endif
5220
5221 /**
5222  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5223  * @pf: pointer to PF
5224  *
5225  * Get TC map for ISCSI PF type that will include iSCSI TC
5226  * and LAN TC.
5227  **/
5228 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5229 {
5230         struct i40e_dcb_app_priority_table app;
5231         struct i40e_hw *hw = &pf->hw;
5232         u8 enabled_tc = 1; /* TC0 is always enabled */
5233         u8 tc, i;
5234         /* Get the iSCSI APP TLV */
5235         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5236
5237         for (i = 0; i < dcbcfg->numapps; i++) {
5238                 app = dcbcfg->app[i];
5239                 if (app.selector == I40E_APP_SEL_TCPIP &&
5240                     app.protocolid == I40E_APP_PROTOID_ISCSI) {
5241                         tc = dcbcfg->etscfg.prioritytable[app.priority];
5242                         enabled_tc |= BIT(tc);
5243                         break;
5244                 }
5245         }
5246
5247         return enabled_tc;
5248 }
5249
5250 /**
5251  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5252  * @dcbcfg: the corresponding DCBx configuration structure
5253  *
5254  * Return the number of TCs from given DCBx configuration
5255  **/
5256 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5257 {
5258         int i, tc_unused = 0;
5259         u8 num_tc = 0;
5260         u8 ret = 0;
5261
5262         /* Scan the ETS Config Priority Table to find
5263          * traffic class enabled for a given priority
5264          * and create a bitmask of enabled TCs
5265          */
5266         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5267                 num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5268
5269         /* Now scan the bitmask to check for
5270          * contiguous TCs starting with TC0
5271          */
5272         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5273                 if (num_tc & BIT(i)) {
5274                         if (!tc_unused) {
5275                                 ret++;
5276                         } else {
5277                                 pr_err("Non-contiguous TC - Disabling DCB\n");
5278                                 return 1;
5279                         }
5280                 } else {
5281                         tc_unused = 1;
5282                 }
5283         }
5284
5285         /* There is always at least TC0 */
5286         if (!ret)
5287                 ret = 1;
5288
5289         return ret;
5290 }
5291
5292 /**
5293  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5294  * @dcbcfg: the corresponding DCBx configuration structure
5295  *
5296  * Query the current DCB configuration and return the number of
5297  * traffic classes enabled from the given DCBX config
5298  **/
5299 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5300 {
5301         u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5302         u8 enabled_tc = 1;
5303         u8 i;
5304
5305         for (i = 0; i < num_tc; i++)
5306                 enabled_tc |= BIT(i);
5307
5308         return enabled_tc;
5309 }
5310
5311 /**
5312  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5313  * @pf: PF being queried
5314  *
5315  * Query the current MQPRIO configuration and return the number of
5316  * traffic classes enabled.
5317  **/
5318 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5319 {
5320         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5321         u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5322         u8 enabled_tc = 1, i;
5323
5324         for (i = 1; i < num_tc; i++)
5325                 enabled_tc |= BIT(i);
5326         return enabled_tc;
5327 }
5328
5329 /**
5330  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5331  * @pf: PF being queried
5332  *
5333  * Return number of traffic classes enabled for the given PF
5334  **/
5335 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5336 {
5337         struct i40e_hw *hw = &pf->hw;
5338         u8 i, enabled_tc = 1;
5339         u8 num_tc = 0;
5340         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5341
5342         if (i40e_is_tc_mqprio_enabled(pf))
5343                 return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5344
5345         /* If neither MQPRIO nor DCB is enabled, then always use single TC */
5346         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5347                 return 1;
5348
5349         /* SFP mode will be enabled for all TCs on port */
5350         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5351                 return i40e_dcb_get_num_tc(dcbcfg);
5352
5353         /* MFP mode return count of enabled TCs for this PF */
5354         if (pf->hw.func_caps.iscsi)
5355                 enabled_tc =  i40e_get_iscsi_tc_map(pf);
5356         else
5357                 return 1; /* Only TC0 */
5358
5359         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5360                 if (enabled_tc & BIT(i))
5361                         num_tc++;
5362         }
5363         return num_tc;
5364 }
5365
5366 /**
5367  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5368  * @pf: PF being queried
5369  *
5370  * Return a bitmap for enabled traffic classes for this PF.
5371  **/
5372 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5373 {
5374         if (i40e_is_tc_mqprio_enabled(pf))
5375                 return i40e_mqprio_get_enabled_tc(pf);
5376
5377         /* If neither MQPRIO nor DCB is enabled for this PF then just return
5378          * default TC
5379          */
5380         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5381                 return I40E_DEFAULT_TRAFFIC_CLASS;
5382
5383         /* SFP mode we want PF to be enabled for all TCs */
5384         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5385                 return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5386
5387         /* MFP enabled and iSCSI PF type */
5388         if (pf->hw.func_caps.iscsi)
5389                 return i40e_get_iscsi_tc_map(pf);
5390         else
5391                 return I40E_DEFAULT_TRAFFIC_CLASS;
5392 }
5393
5394 /**
5395  * i40e_vsi_get_bw_info - Query VSI BW Information
5396  * @vsi: the VSI being queried
5397  *
5398  * Returns 0 on success, negative value on failure
5399  **/
5400 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5401 {
5402         struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5403         struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5404         struct i40e_pf *pf = vsi->back;
5405         struct i40e_hw *hw = &pf->hw;
5406         i40e_status ret;
5407         u32 tc_bw_max;
5408         int i;
5409
5410         /* Get the VSI level BW configuration */
5411         ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5412         if (ret) {
5413                 dev_info(&pf->pdev->dev,
5414                          "couldn't get PF vsi bw config, err %s aq_err %s\n",
5415                          i40e_stat_str(&pf->hw, ret),
5416                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5417                 return -EINVAL;
5418         }
5419
5420         /* Get the VSI level BW configuration per TC */
5421         ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5422                                                NULL);
5423         if (ret) {
5424                 dev_info(&pf->pdev->dev,
5425                          "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
5426                          i40e_stat_str(&pf->hw, ret),
5427                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5428                 return -EINVAL;
5429         }
5430
5431         if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5432                 dev_info(&pf->pdev->dev,
5433                          "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5434                          bw_config.tc_valid_bits,
5435                          bw_ets_config.tc_valid_bits);
5436                 /* Still continuing */
5437         }
5438
5439         vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5440         vsi->bw_max_quanta = bw_config.max_bw;
5441         tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5442                     (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5443         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5444                 vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5445                 vsi->bw_ets_limit_credits[i] =
5446                                         le16_to_cpu(bw_ets_config.credits[i]);
5447                 /* 3 bits out of 4 for each TC */
5448                 vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5449         }
5450
5451         return 0;
5452 }
5453
5454 /**
5455  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5456  * @vsi: the VSI being configured
5457  * @enabled_tc: TC bitmap
5458  * @bw_share: BW shared credits per TC
5459  *
5460  * Returns 0 on success, negative value on failure
5461  **/
5462 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5463                                        u8 *bw_share)
5464 {
5465         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5466         struct i40e_pf *pf = vsi->back;
5467         i40e_status ret;
5468         int i;
5469
5470         /* There is no need to reset BW when mqprio mode is on.  */
5471         if (i40e_is_tc_mqprio_enabled(pf))
5472                 return 0;
5473         if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5474                 ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5475                 if (ret)
5476                         dev_info(&pf->pdev->dev,
5477                                  "Failed to reset tx rate for vsi->seid %u\n",
5478                                  vsi->seid);
5479                 return ret;
5480         }
5481         memset(&bw_data, 0, sizeof(bw_data));
5482         bw_data.tc_valid_bits = enabled_tc;
5483         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5484                 bw_data.tc_bw_credits[i] = bw_share[i];
5485
5486         ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5487         if (ret) {
5488                 dev_info(&pf->pdev->dev,
5489                          "AQ command Config VSI BW allocation per TC failed = %d\n",
5490                          pf->hw.aq.asq_last_status);
5491                 return -EINVAL;
5492         }
5493
5494         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5495                 vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5496
5497         return 0;
5498 }
5499
5500 /**
5501  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5502  * @vsi: the VSI being configured
5503  * @enabled_tc: TC map to be enabled
5504  *
5505  **/
5506 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5507 {
5508         struct net_device *netdev = vsi->netdev;
5509         struct i40e_pf *pf = vsi->back;
5510         struct i40e_hw *hw = &pf->hw;
5511         u8 netdev_tc = 0;
5512         int i;
5513         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5514
5515         if (!netdev)
5516                 return;
5517
5518         if (!enabled_tc) {
5519                 netdev_reset_tc(netdev);
5520                 return;
5521         }
5522
5523         /* Set up actual enabled TCs on the VSI */
5524         if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5525                 return;
5526
5527         /* set per TC queues for the VSI */
5528         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5529                 /* Only set TC queues for enabled tcs
5530                  *
5531                  * e.g. For a VSI that has TC0 and TC3 enabled the
5532                  * enabled_tc bitmap would be 0x00001001; the driver
5533                  * will set the numtc for netdev as 2 that will be
5534                  * referenced by the netdev layer as TC 0 and 1.
5535                  */
5536                 if (vsi->tc_config.enabled_tc & BIT(i))
5537                         netdev_set_tc_queue(netdev,
5538                                         vsi->tc_config.tc_info[i].netdev_tc,
5539                                         vsi->tc_config.tc_info[i].qcount,
5540                                         vsi->tc_config.tc_info[i].qoffset);
5541         }
5542
5543         if (i40e_is_tc_mqprio_enabled(pf))
5544                 return;
5545
5546         /* Assign UP2TC map for the VSI */
5547         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5548                 /* Get the actual TC# for the UP */
5549                 u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5550                 /* Get the mapped netdev TC# for the UP */
5551                 netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5552                 netdev_set_prio_tc_map(netdev, i, netdev_tc);
5553         }
5554 }
5555
5556 /**
5557  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5558  * @vsi: the VSI being configured
5559  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5560  **/
5561 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5562                                       struct i40e_vsi_context *ctxt)
5563 {
5564         /* copy just the sections touched not the entire info
5565          * since not all sections are valid as returned by
5566          * update vsi params
5567          */
5568         vsi->info.mapping_flags = ctxt->info.mapping_flags;
5569         memcpy(&vsi->info.queue_mapping,
5570                &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5571         memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5572                sizeof(vsi->info.tc_mapping));
5573 }
5574
5575 /**
5576  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5577  * @vsi: the VSI being reconfigured
5578  * @vsi_offset: offset from main VF VSI
5579  */
5580 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5581 {
5582         struct i40e_vsi_context ctxt = {};
5583         struct i40e_pf *pf;
5584         struct i40e_hw *hw;
5585         int ret;
5586
5587         if (!vsi)
5588                 return I40E_ERR_PARAM;
5589         pf = vsi->back;
5590         hw = &pf->hw;
5591
5592         ctxt.seid = vsi->seid;
5593         ctxt.pf_num = hw->pf_id;
5594         ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5595         ctxt.uplink_seid = vsi->uplink_seid;
5596         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5597         ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5598         ctxt.info = vsi->info;
5599
5600         i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5601                                  false);
5602         if (vsi->reconfig_rss) {
5603                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
5604                                       vsi->num_queue_pairs);
5605                 ret = i40e_vsi_config_rss(vsi);
5606                 if (ret) {
5607                         dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5608                         return ret;
5609                 }
5610                 vsi->reconfig_rss = false;
5611         }
5612
5613         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5614         if (ret) {
5615                 dev_info(&pf->pdev->dev, "Update vsi config failed, err %s aq_err %s\n",
5616                          i40e_stat_str(hw, ret),
5617                          i40e_aq_str(hw, hw->aq.asq_last_status));
5618                 return ret;
5619         }
5620         /* update the local VSI info with updated queue map */
5621         i40e_vsi_update_queue_map(vsi, &ctxt);
5622         vsi->info.valid_sections = 0;
5623
5624         return ret;
5625 }
5626
5627 /**
5628  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5629  * @vsi: VSI to be configured
5630  * @enabled_tc: TC bitmap
5631  *
5632  * This configures a particular VSI for TCs that are mapped to the
5633  * given TC bitmap. It uses default bandwidth share for TCs across
5634  * VSIs to configure TC for a particular VSI.
5635  *
5636  * NOTE:
5637  * It is expected that the VSI queues have been quisced before calling
5638  * this function.
5639  **/
5640 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5641 {
5642         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5643         struct i40e_pf *pf = vsi->back;
5644         struct i40e_hw *hw = &pf->hw;
5645         struct i40e_vsi_context ctxt;
5646         int ret = 0;
5647         int i;
5648
5649         /* Check if enabled_tc is same as existing or new TCs */
5650         if (vsi->tc_config.enabled_tc == enabled_tc &&
5651             vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5652                 return ret;
5653
5654         /* Enable ETS TCs with equal BW Share for now across all VSIs */
5655         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5656                 if (enabled_tc & BIT(i))
5657                         bw_share[i] = 1;
5658         }
5659
5660         ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5661         if (ret) {
5662                 struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5663
5664                 dev_info(&pf->pdev->dev,
5665                          "Failed configuring TC map %d for VSI %d\n",
5666                          enabled_tc, vsi->seid);
5667                 ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5668                                                   &bw_config, NULL);
5669                 if (ret) {
5670                         dev_info(&pf->pdev->dev,
5671                                  "Failed querying vsi bw info, err %s aq_err %s\n",
5672                                  i40e_stat_str(hw, ret),
5673                                  i40e_aq_str(hw, hw->aq.asq_last_status));
5674                         goto out;
5675                 }
5676                 if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5677                         u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5678
5679                         if (!valid_tc)
5680                                 valid_tc = bw_config.tc_valid_bits;
5681                         /* Always enable TC0, no matter what */
5682                         valid_tc |= 1;
5683                         dev_info(&pf->pdev->dev,
5684                                  "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5685                                  enabled_tc, bw_config.tc_valid_bits, valid_tc);
5686                         enabled_tc = valid_tc;
5687                 }
5688
5689                 ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5690                 if (ret) {
5691                         dev_err(&pf->pdev->dev,
5692                                 "Unable to  configure TC map %d for VSI %d\n",
5693                                 enabled_tc, vsi->seid);
5694                         goto out;
5695                 }
5696         }
5697
5698         /* Update Queue Pairs Mapping for currently enabled UPs */
5699         ctxt.seid = vsi->seid;
5700         ctxt.pf_num = vsi->back->hw.pf_id;
5701         ctxt.vf_num = 0;
5702         ctxt.uplink_seid = vsi->uplink_seid;
5703         ctxt.info = vsi->info;
5704         if (i40e_is_tc_mqprio_enabled(pf)) {
5705                 ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5706                 if (ret)
5707                         goto out;
5708         } else {
5709                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5710         }
5711
5712         /* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5713          * queues changed.
5714          */
5715         if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5716                 vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5717                                       vsi->num_queue_pairs);
5718                 ret = i40e_vsi_config_rss(vsi);
5719                 if (ret) {
5720                         dev_info(&vsi->back->pdev->dev,
5721                                  "Failed to reconfig rss for num_queues\n");
5722                         return ret;
5723                 }
5724                 vsi->reconfig_rss = false;
5725         }
5726         if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5727                 ctxt.info.valid_sections |=
5728                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5729                 ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5730         }
5731
5732         /* Update the VSI after updating the VSI queue-mapping
5733          * information
5734          */
5735         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5736         if (ret) {
5737                 dev_info(&pf->pdev->dev,
5738                          "Update vsi tc config failed, err %s aq_err %s\n",
5739                          i40e_stat_str(hw, ret),
5740                          i40e_aq_str(hw, hw->aq.asq_last_status));
5741                 goto out;
5742         }
5743         /* update the local VSI info with updated queue map */
5744         i40e_vsi_update_queue_map(vsi, &ctxt);
5745         vsi->info.valid_sections = 0;
5746
5747         /* Update current VSI BW information */
5748         ret = i40e_vsi_get_bw_info(vsi);
5749         if (ret) {
5750                 dev_info(&pf->pdev->dev,
5751                          "Failed updating vsi bw info, err %s aq_err %s\n",
5752                          i40e_stat_str(hw, ret),
5753                          i40e_aq_str(hw, hw->aq.asq_last_status));
5754                 goto out;
5755         }
5756
5757         /* Update the netdev TC setup */
5758         i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5759 out:
5760         return ret;
5761 }
5762
5763 /**
5764  * i40e_get_link_speed - Returns link speed for the interface
5765  * @vsi: VSI to be configured
5766  *
5767  **/
5768 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5769 {
5770         struct i40e_pf *pf = vsi->back;
5771
5772         switch (pf->hw.phy.link_info.link_speed) {
5773         case I40E_LINK_SPEED_40GB:
5774                 return 40000;
5775         case I40E_LINK_SPEED_25GB:
5776                 return 25000;
5777         case I40E_LINK_SPEED_20GB:
5778                 return 20000;
5779         case I40E_LINK_SPEED_10GB:
5780                 return 10000;
5781         case I40E_LINK_SPEED_1GB:
5782                 return 1000;
5783         default:
5784                 return -EINVAL;
5785         }
5786 }
5787
5788 /**
5789  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5790  * @vsi: Pointer to vsi structure
5791  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5792  *
5793  * Helper function to convert units before send to set BW limit
5794  **/
5795 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5796 {
5797         if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5798                 dev_warn(&vsi->back->pdev->dev,
5799                          "Setting max tx rate to minimum usable value of 50Mbps.\n");
5800                 max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5801         } else {
5802                 do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5803         }
5804
5805         return max_tx_rate;
5806 }
5807
5808 /**
5809  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5810  * @vsi: VSI to be configured
5811  * @seid: seid of the channel/VSI
5812  * @max_tx_rate: max TX rate to be configured as BW limit
5813  *
5814  * Helper function to set BW limit for a given VSI
5815  **/
5816 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5817 {
5818         struct i40e_pf *pf = vsi->back;
5819         u64 credits = 0;
5820         int speed = 0;
5821         int ret = 0;
5822
5823         speed = i40e_get_link_speed(vsi);
5824         if (max_tx_rate > speed) {
5825                 dev_err(&pf->pdev->dev,
5826                         "Invalid max tx rate %llu specified for VSI seid %d.",
5827                         max_tx_rate, seid);
5828                 return -EINVAL;
5829         }
5830         if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
5831                 dev_warn(&pf->pdev->dev,
5832                          "Setting max tx rate to minimum usable value of 50Mbps.\n");
5833                 max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5834         }
5835
5836         /* Tx rate credits are in values of 50Mbps, 0 is disabled */
5837         credits = max_tx_rate;
5838         do_div(credits, I40E_BW_CREDIT_DIVISOR);
5839         ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5840                                           I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5841         if (ret)
5842                 dev_err(&pf->pdev->dev,
5843                         "Failed set tx rate (%llu Mbps) for vsi->seid %u, err %s aq_err %s\n",
5844                         max_tx_rate, seid, i40e_stat_str(&pf->hw, ret),
5845                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5846         return ret;
5847 }
5848
5849 /**
5850  * i40e_remove_queue_channels - Remove queue channels for the TCs
5851  * @vsi: VSI to be configured
5852  *
5853  * Remove queue channels for the TCs
5854  **/
5855 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5856 {
5857         enum i40e_admin_queue_err last_aq_status;
5858         struct i40e_cloud_filter *cfilter;
5859         struct i40e_channel *ch, *ch_tmp;
5860         struct i40e_pf *pf = vsi->back;
5861         struct hlist_node *node;
5862         int ret, i;
5863
5864         /* Reset rss size that was stored when reconfiguring rss for
5865          * channel VSIs with non-power-of-2 queue count.
5866          */
5867         vsi->current_rss_size = 0;
5868
5869         /* perform cleanup for channels if they exist */
5870         if (list_empty(&vsi->ch_list))
5871                 return;
5872
5873         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5874                 struct i40e_vsi *p_vsi;
5875
5876                 list_del(&ch->list);
5877                 p_vsi = ch->parent_vsi;
5878                 if (!p_vsi || !ch->initialized) {
5879                         kfree(ch);
5880                         continue;
5881                 }
5882                 /* Reset queue contexts */
5883                 for (i = 0; i < ch->num_queue_pairs; i++) {
5884                         struct i40e_ring *tx_ring, *rx_ring;
5885                         u16 pf_q;
5886
5887                         pf_q = ch->base_queue + i;
5888                         tx_ring = vsi->tx_rings[pf_q];
5889                         tx_ring->ch = NULL;
5890
5891                         rx_ring = vsi->rx_rings[pf_q];
5892                         rx_ring->ch = NULL;
5893                 }
5894
5895                 /* Reset BW configured for this VSI via mqprio */
5896                 ret = i40e_set_bw_limit(vsi, ch->seid, 0);
5897                 if (ret)
5898                         dev_info(&vsi->back->pdev->dev,
5899                                  "Failed to reset tx rate for ch->seid %u\n",
5900                                  ch->seid);
5901
5902                 /* delete cloud filters associated with this channel */
5903                 hlist_for_each_entry_safe(cfilter, node,
5904                                           &pf->cloud_filter_list, cloud_node) {
5905                         if (cfilter->seid != ch->seid)
5906                                 continue;
5907
5908                         hash_del(&cfilter->cloud_node);
5909                         if (cfilter->dst_port)
5910                                 ret = i40e_add_del_cloud_filter_big_buf(vsi,
5911                                                                         cfilter,
5912                                                                         false);
5913                         else
5914                                 ret = i40e_add_del_cloud_filter(vsi, cfilter,
5915                                                                 false);
5916                         last_aq_status = pf->hw.aq.asq_last_status;
5917                         if (ret)
5918                                 dev_info(&pf->pdev->dev,
5919                                          "Failed to delete cloud filter, err %s aq_err %s\n",
5920                                          i40e_stat_str(&pf->hw, ret),
5921                                          i40e_aq_str(&pf->hw, last_aq_status));
5922                         kfree(cfilter);
5923                 }
5924
5925                 /* delete VSI from FW */
5926                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
5927                                              NULL);
5928                 if (ret)
5929                         dev_err(&vsi->back->pdev->dev,
5930                                 "unable to remove channel (%d) for parent VSI(%d)\n",
5931                                 ch->seid, p_vsi->seid);
5932                 kfree(ch);
5933         }
5934         INIT_LIST_HEAD(&vsi->ch_list);
5935 }
5936
5937 /**
5938  * i40e_get_max_queues_for_channel
5939  * @vsi: ptr to VSI to which channels are associated with
5940  *
5941  * Helper function which returns max value among the queue counts set on the
5942  * channels/TCs created.
5943  **/
5944 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
5945 {
5946         struct i40e_channel *ch, *ch_tmp;
5947         int max = 0;
5948
5949         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5950                 if (!ch->initialized)
5951                         continue;
5952                 if (ch->num_queue_pairs > max)
5953                         max = ch->num_queue_pairs;
5954         }
5955
5956         return max;
5957 }
5958
5959 /**
5960  * i40e_validate_num_queues - validate num_queues w.r.t channel
5961  * @pf: ptr to PF device
5962  * @num_queues: number of queues
5963  * @vsi: the parent VSI
5964  * @reconfig_rss: indicates should the RSS be reconfigured or not
5965  *
5966  * This function validates number of queues in the context of new channel
5967  * which is being established and determines if RSS should be reconfigured
5968  * or not for parent VSI.
5969  **/
5970 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
5971                                     struct i40e_vsi *vsi, bool *reconfig_rss)
5972 {
5973         int max_ch_queues;
5974
5975         if (!reconfig_rss)
5976                 return -EINVAL;
5977
5978         *reconfig_rss = false;
5979         if (vsi->current_rss_size) {
5980                 if (num_queues > vsi->current_rss_size) {
5981                         dev_dbg(&pf->pdev->dev,
5982                                 "Error: num_queues (%d) > vsi's current_size(%d)\n",
5983                                 num_queues, vsi->current_rss_size);
5984                         return -EINVAL;
5985                 } else if ((num_queues < vsi->current_rss_size) &&
5986                            (!is_power_of_2(num_queues))) {
5987                         dev_dbg(&pf->pdev->dev,
5988                                 "Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
5989                                 num_queues, vsi->current_rss_size);
5990                         return -EINVAL;
5991                 }
5992         }
5993
5994         if (!is_power_of_2(num_queues)) {
5995                 /* Find the max num_queues configured for channel if channel
5996                  * exist.
5997                  * if channel exist, then enforce 'num_queues' to be more than
5998                  * max ever queues configured for channel.
5999                  */
6000                 max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6001                 if (num_queues < max_ch_queues) {
6002                         dev_dbg(&pf->pdev->dev,
6003                                 "Error: num_queues (%d) < max queues configured for channel(%d)\n",
6004                                 num_queues, max_ch_queues);
6005                         return -EINVAL;
6006                 }
6007                 *reconfig_rss = true;
6008         }
6009
6010         return 0;
6011 }
6012
6013 /**
6014  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6015  * @vsi: the VSI being setup
6016  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6017  *
6018  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6019  **/
6020 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6021 {
6022         struct i40e_pf *pf = vsi->back;
6023         u8 seed[I40E_HKEY_ARRAY_SIZE];
6024         struct i40e_hw *hw = &pf->hw;
6025         int local_rss_size;
6026         u8 *lut;
6027         int ret;
6028
6029         if (!vsi->rss_size)
6030                 return -EINVAL;
6031
6032         if (rss_size > vsi->rss_size)
6033                 return -EINVAL;
6034
6035         local_rss_size = min_t(int, vsi->rss_size, rss_size);
6036         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6037         if (!lut)
6038                 return -ENOMEM;
6039
6040         /* Ignoring user configured lut if there is one */
6041         i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6042
6043         /* Use user configured hash key if there is one, otherwise
6044          * use default.
6045          */
6046         if (vsi->rss_hkey_user)
6047                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6048         else
6049                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6050
6051         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6052         if (ret) {
6053                 dev_info(&pf->pdev->dev,
6054                          "Cannot set RSS lut, err %s aq_err %s\n",
6055                          i40e_stat_str(hw, ret),
6056                          i40e_aq_str(hw, hw->aq.asq_last_status));
6057                 kfree(lut);
6058                 return ret;
6059         }
6060         kfree(lut);
6061
6062         /* Do the update w.r.t. storing rss_size */
6063         if (!vsi->orig_rss_size)
6064                 vsi->orig_rss_size = vsi->rss_size;
6065         vsi->current_rss_size = local_rss_size;
6066
6067         return ret;
6068 }
6069
6070 /**
6071  * i40e_channel_setup_queue_map - Setup a channel queue map
6072  * @pf: ptr to PF device
6073  * @ctxt: VSI context structure
6074  * @ch: ptr to channel structure
6075  *
6076  * Setup queue map for a specific channel
6077  **/
6078 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6079                                          struct i40e_vsi_context *ctxt,
6080                                          struct i40e_channel *ch)
6081 {
6082         u16 qcount, qmap, sections = 0;
6083         u8 offset = 0;
6084         int pow;
6085
6086         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6087         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6088
6089         qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6090         ch->num_queue_pairs = qcount;
6091
6092         /* find the next higher power-of-2 of num queue pairs */
6093         pow = ilog2(qcount);
6094         if (!is_power_of_2(qcount))
6095                 pow++;
6096
6097         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6098                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6099
6100         /* Setup queue TC[0].qmap for given VSI context */
6101         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6102
6103         ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6104         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6105         ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6106         ctxt->info.valid_sections |= cpu_to_le16(sections);
6107 }
6108
6109 /**
6110  * i40e_add_channel - add a channel by adding VSI
6111  * @pf: ptr to PF device
6112  * @uplink_seid: underlying HW switching element (VEB) ID
6113  * @ch: ptr to channel structure
6114  *
6115  * Add a channel (VSI) using add_vsi and queue_map
6116  **/
6117 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6118                             struct i40e_channel *ch)
6119 {
6120         struct i40e_hw *hw = &pf->hw;
6121         struct i40e_vsi_context ctxt;
6122         u8 enabled_tc = 0x1; /* TC0 enabled */
6123         int ret;
6124
6125         if (ch->type != I40E_VSI_VMDQ2) {
6126                 dev_info(&pf->pdev->dev,
6127                          "add new vsi failed, ch->type %d\n", ch->type);
6128                 return -EINVAL;
6129         }
6130
6131         memset(&ctxt, 0, sizeof(ctxt));
6132         ctxt.pf_num = hw->pf_id;
6133         ctxt.vf_num = 0;
6134         ctxt.uplink_seid = uplink_seid;
6135         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6136         if (ch->type == I40E_VSI_VMDQ2)
6137                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6138
6139         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
6140                 ctxt.info.valid_sections |=
6141                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6142                 ctxt.info.switch_id =
6143                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6144         }
6145
6146         /* Set queue map for a given VSI context */
6147         i40e_channel_setup_queue_map(pf, &ctxt, ch);
6148
6149         /* Now time to create VSI */
6150         ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6151         if (ret) {
6152                 dev_info(&pf->pdev->dev,
6153                          "add new vsi failed, err %s aq_err %s\n",
6154                          i40e_stat_str(&pf->hw, ret),
6155                          i40e_aq_str(&pf->hw,
6156                                      pf->hw.aq.asq_last_status));
6157                 return -ENOENT;
6158         }
6159
6160         /* Success, update channel, set enabled_tc only if the channel
6161          * is not a macvlan
6162          */
6163         ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6164         ch->seid = ctxt.seid;
6165         ch->vsi_number = ctxt.vsi_number;
6166         ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6167
6168         /* copy just the sections touched not the entire info
6169          * since not all sections are valid as returned by
6170          * update vsi params
6171          */
6172         ch->info.mapping_flags = ctxt.info.mapping_flags;
6173         memcpy(&ch->info.queue_mapping,
6174                &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6175         memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6176                sizeof(ctxt.info.tc_mapping));
6177
6178         return 0;
6179 }
6180
6181 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6182                                   u8 *bw_share)
6183 {
6184         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6185         i40e_status ret;
6186         int i;
6187
6188         memset(&bw_data, 0, sizeof(bw_data));
6189         bw_data.tc_valid_bits = ch->enabled_tc;
6190         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6191                 bw_data.tc_bw_credits[i] = bw_share[i];
6192
6193         ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6194                                        &bw_data, NULL);
6195         if (ret) {
6196                 dev_info(&vsi->back->pdev->dev,
6197                          "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6198                          vsi->back->hw.aq.asq_last_status, ch->seid);
6199                 return -EINVAL;
6200         }
6201
6202         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6203                 ch->info.qs_handle[i] = bw_data.qs_handles[i];
6204
6205         return 0;
6206 }
6207
6208 /**
6209  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6210  * @pf: ptr to PF device
6211  * @vsi: the VSI being setup
6212  * @ch: ptr to channel structure
6213  *
6214  * Configure TX rings associated with channel (VSI) since queues are being
6215  * from parent VSI.
6216  **/
6217 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6218                                        struct i40e_vsi *vsi,
6219                                        struct i40e_channel *ch)
6220 {
6221         i40e_status ret;
6222         int i;
6223         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6224
6225         /* Enable ETS TCs with equal BW Share for now across all VSIs */
6226         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6227                 if (ch->enabled_tc & BIT(i))
6228                         bw_share[i] = 1;
6229         }
6230
6231         /* configure BW for new VSI */
6232         ret = i40e_channel_config_bw(vsi, ch, bw_share);
6233         if (ret) {
6234                 dev_info(&vsi->back->pdev->dev,
6235                          "Failed configuring TC map %d for channel (seid %u)\n",
6236                          ch->enabled_tc, ch->seid);
6237                 return ret;
6238         }
6239
6240         for (i = 0; i < ch->num_queue_pairs; i++) {
6241                 struct i40e_ring *tx_ring, *rx_ring;
6242                 u16 pf_q;
6243
6244                 pf_q = ch->base_queue + i;
6245
6246                 /* Get to TX ring ptr of main VSI, for re-setup TX queue
6247                  * context
6248                  */
6249                 tx_ring = vsi->tx_rings[pf_q];
6250                 tx_ring->ch = ch;
6251
6252                 /* Get the RX ring ptr */
6253                 rx_ring = vsi->rx_rings[pf_q];
6254                 rx_ring->ch = ch;
6255         }
6256
6257         return 0;
6258 }
6259
6260 /**
6261  * i40e_setup_hw_channel - setup new channel
6262  * @pf: ptr to PF device
6263  * @vsi: the VSI being setup
6264  * @ch: ptr to channel structure
6265  * @uplink_seid: underlying HW switching element (VEB) ID
6266  * @type: type of channel to be created (VMDq2/VF)
6267  *
6268  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6269  * and configures TX rings accordingly
6270  **/
6271 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6272                                         struct i40e_vsi *vsi,
6273                                         struct i40e_channel *ch,
6274                                         u16 uplink_seid, u8 type)
6275 {
6276         int ret;
6277
6278         ch->initialized = false;
6279         ch->base_queue = vsi->next_base_queue;
6280         ch->type = type;
6281
6282         /* Proceed with creation of channel (VMDq2) VSI */
6283         ret = i40e_add_channel(pf, uplink_seid, ch);
6284         if (ret) {
6285                 dev_info(&pf->pdev->dev,
6286                          "failed to add_channel using uplink_seid %u\n",
6287                          uplink_seid);
6288                 return ret;
6289         }
6290
6291         /* Mark the successful creation of channel */
6292         ch->initialized = true;
6293
6294         /* Reconfigure TX queues using QTX_CTL register */
6295         ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6296         if (ret) {
6297                 dev_info(&pf->pdev->dev,
6298                          "failed to configure TX rings for channel %u\n",
6299                          ch->seid);
6300                 return ret;
6301         }
6302
6303         /* update 'next_base_queue' */
6304         vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6305         dev_dbg(&pf->pdev->dev,
6306                 "Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6307                 ch->seid, ch->vsi_number, ch->stat_counter_idx,
6308                 ch->num_queue_pairs,
6309                 vsi->next_base_queue);
6310         return ret;
6311 }
6312
6313 /**
6314  * i40e_setup_channel - setup new channel using uplink element
6315  * @pf: ptr to PF device
6316  * @vsi: pointer to the VSI to set up the channel within
6317  * @ch: ptr to channel structure
6318  *
6319  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6320  * and uplink switching element (uplink_seid)
6321  **/
6322 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6323                                struct i40e_channel *ch)
6324 {
6325         u8 vsi_type;
6326         u16 seid;
6327         int ret;
6328
6329         if (vsi->type == I40E_VSI_MAIN) {
6330                 vsi_type = I40E_VSI_VMDQ2;
6331         } else {
6332                 dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6333                         vsi->type);
6334                 return false;
6335         }
6336
6337         /* underlying switching element */
6338         seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6339
6340         /* create channel (VSI), configure TX rings */
6341         ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6342         if (ret) {
6343                 dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6344                 return false;
6345         }
6346
6347         return ch->initialized ? true : false;
6348 }
6349
6350 /**
6351  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6352  * @vsi: ptr to VSI which has PF backing
6353  *
6354  * Sets up switch mode correctly if it needs to be changed and perform
6355  * what are allowed modes.
6356  **/
6357 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6358 {
6359         u8 mode;
6360         struct i40e_pf *pf = vsi->back;
6361         struct i40e_hw *hw = &pf->hw;
6362         int ret;
6363
6364         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6365         if (ret)
6366                 return -EINVAL;
6367
6368         if (hw->dev_caps.switch_mode) {
6369                 /* if switch mode is set, support mode2 (non-tunneled for
6370                  * cloud filter) for now
6371                  */
6372                 u32 switch_mode = hw->dev_caps.switch_mode &
6373                                   I40E_SWITCH_MODE_MASK;
6374                 if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6375                         if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6376                                 return 0;
6377                         dev_err(&pf->pdev->dev,
6378                                 "Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6379                                 hw->dev_caps.switch_mode);
6380                         return -EINVAL;
6381                 }
6382         }
6383
6384         /* Set Bit 7 to be valid */
6385         mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6386
6387         /* Set L4type for TCP support */
6388         mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6389
6390         /* Set cloud filter mode */
6391         mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6392
6393         /* Prep mode field for set_switch_config */
6394         ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6395                                         pf->last_sw_conf_valid_flags,
6396                                         mode, NULL);
6397         if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6398                 dev_err(&pf->pdev->dev,
6399                         "couldn't set switch config bits, err %s aq_err %s\n",
6400                         i40e_stat_str(hw, ret),
6401                         i40e_aq_str(hw,
6402                                     hw->aq.asq_last_status));
6403
6404         return ret;
6405 }
6406
6407 /**
6408  * i40e_create_queue_channel - function to create channel
6409  * @vsi: VSI to be configured
6410  * @ch: ptr to channel (it contains channel specific params)
6411  *
6412  * This function creates channel (VSI) using num_queues specified by user,
6413  * reconfigs RSS if needed.
6414  **/
6415 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6416                               struct i40e_channel *ch)
6417 {
6418         struct i40e_pf *pf = vsi->back;
6419         bool reconfig_rss;
6420         int err;
6421
6422         if (!ch)
6423                 return -EINVAL;
6424
6425         if (!ch->num_queue_pairs) {
6426                 dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6427                         ch->num_queue_pairs);
6428                 return -EINVAL;
6429         }
6430
6431         /* validate user requested num_queues for channel */
6432         err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6433                                        &reconfig_rss);
6434         if (err) {
6435                 dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6436                          ch->num_queue_pairs);
6437                 return -EINVAL;
6438         }
6439
6440         /* By default we are in VEPA mode, if this is the first VF/VMDq
6441          * VSI to be added switch to VEB mode.
6442          */
6443
6444         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6445                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6446
6447                 if (vsi->type == I40E_VSI_MAIN) {
6448                         if (i40e_is_tc_mqprio_enabled(pf))
6449                                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6450                         else
6451                                 i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6452                 }
6453                 /* now onwards for main VSI, number of queues will be value
6454                  * of TC0's queue count
6455                  */
6456         }
6457
6458         /* By this time, vsi->cnt_q_avail shall be set to non-zero and
6459          * it should be more than num_queues
6460          */
6461         if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6462                 dev_dbg(&pf->pdev->dev,
6463                         "Error: cnt_q_avail (%u) less than num_queues %d\n",
6464                         vsi->cnt_q_avail, ch->num_queue_pairs);
6465                 return -EINVAL;
6466         }
6467
6468         /* reconfig_rss only if vsi type is MAIN_VSI */
6469         if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6470                 err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6471                 if (err) {
6472                         dev_info(&pf->pdev->dev,
6473                                  "Error: unable to reconfig rss for num_queues (%u)\n",
6474                                  ch->num_queue_pairs);
6475                         return -EINVAL;
6476                 }
6477         }
6478
6479         if (!i40e_setup_channel(pf, vsi, ch)) {
6480                 dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6481                 return -EINVAL;
6482         }
6483
6484         dev_info(&pf->pdev->dev,
6485                  "Setup channel (id:%u) utilizing num_queues %d\n",
6486                  ch->seid, ch->num_queue_pairs);
6487
6488         /* configure VSI for BW limit */
6489         if (ch->max_tx_rate) {
6490                 u64 credits = ch->max_tx_rate;
6491
6492                 if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6493                         return -EINVAL;
6494
6495                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
6496                 dev_dbg(&pf->pdev->dev,
6497                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6498                         ch->max_tx_rate,
6499                         credits,
6500                         ch->seid);
6501         }
6502
6503         /* in case of VF, this will be main SRIOV VSI */
6504         ch->parent_vsi = vsi;
6505
6506         /* and update main_vsi's count for queue_available to use */
6507         vsi->cnt_q_avail -= ch->num_queue_pairs;
6508
6509         return 0;
6510 }
6511
6512 /**
6513  * i40e_configure_queue_channels - Add queue channel for the given TCs
6514  * @vsi: VSI to be configured
6515  *
6516  * Configures queue channel mapping to the given TCs
6517  **/
6518 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6519 {
6520         struct i40e_channel *ch;
6521         u64 max_rate = 0;
6522         int ret = 0, i;
6523
6524         /* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6525         vsi->tc_seid_map[0] = vsi->seid;
6526         for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6527                 if (vsi->tc_config.enabled_tc & BIT(i)) {
6528                         ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6529                         if (!ch) {
6530                                 ret = -ENOMEM;
6531                                 goto err_free;
6532                         }
6533
6534                         INIT_LIST_HEAD(&ch->list);
6535                         ch->num_queue_pairs =
6536                                 vsi->tc_config.tc_info[i].qcount;
6537                         ch->base_queue =
6538                                 vsi->tc_config.tc_info[i].qoffset;
6539
6540                         /* Bandwidth limit through tc interface is in bytes/s,
6541                          * change to Mbit/s
6542                          */
6543                         max_rate = vsi->mqprio_qopt.max_rate[i];
6544                         do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6545                         ch->max_tx_rate = max_rate;
6546
6547                         list_add_tail(&ch->list, &vsi->ch_list);
6548
6549                         ret = i40e_create_queue_channel(vsi, ch);
6550                         if (ret) {
6551                                 dev_err(&vsi->back->pdev->dev,
6552                                         "Failed creating queue channel with TC%d: queues %d\n",
6553                                         i, ch->num_queue_pairs);
6554                                 goto err_free;
6555                         }
6556                         vsi->tc_seid_map[i] = ch->seid;
6557                 }
6558         }
6559
6560         /* reset to reconfigure TX queue contexts */
6561         i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6562         return ret;
6563
6564 err_free:
6565         i40e_remove_queue_channels(vsi);
6566         return ret;
6567 }
6568
6569 /**
6570  * i40e_veb_config_tc - Configure TCs for given VEB
6571  * @veb: given VEB
6572  * @enabled_tc: TC bitmap
6573  *
6574  * Configures given TC bitmap for VEB (switching) element
6575  **/
6576 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6577 {
6578         struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6579         struct i40e_pf *pf = veb->pf;
6580         int ret = 0;
6581         int i;
6582
6583         /* No TCs or already enabled TCs just return */
6584         if (!enabled_tc || veb->enabled_tc == enabled_tc)
6585                 return ret;
6586
6587         bw_data.tc_valid_bits = enabled_tc;
6588         /* bw_data.absolute_credits is not set (relative) */
6589
6590         /* Enable ETS TCs with equal BW Share for now */
6591         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6592                 if (enabled_tc & BIT(i))
6593                         bw_data.tc_bw_share_credits[i] = 1;
6594         }
6595
6596         ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6597                                                    &bw_data, NULL);
6598         if (ret) {
6599                 dev_info(&pf->pdev->dev,
6600                          "VEB bw config failed, err %s aq_err %s\n",
6601                          i40e_stat_str(&pf->hw, ret),
6602                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6603                 goto out;
6604         }
6605
6606         /* Update the BW information */
6607         ret = i40e_veb_get_bw_info(veb);
6608         if (ret) {
6609                 dev_info(&pf->pdev->dev,
6610                          "Failed getting veb bw config, err %s aq_err %s\n",
6611                          i40e_stat_str(&pf->hw, ret),
6612                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6613         }
6614
6615 out:
6616         return ret;
6617 }
6618
6619 #ifdef CONFIG_I40E_DCB
6620 /**
6621  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6622  * @pf: PF struct
6623  *
6624  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6625  * the caller would've quiesce all the VSIs before calling
6626  * this function
6627  **/
6628 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6629 {
6630         u8 tc_map = 0;
6631         int ret;
6632         u8 v;
6633
6634         /* Enable the TCs available on PF to all VEBs */
6635         tc_map = i40e_pf_get_tc_map(pf);
6636         if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6637                 return;
6638
6639         for (v = 0; v < I40E_MAX_VEB; v++) {
6640                 if (!pf->veb[v])
6641                         continue;
6642                 ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6643                 if (ret) {
6644                         dev_info(&pf->pdev->dev,
6645                                  "Failed configuring TC for VEB seid=%d\n",
6646                                  pf->veb[v]->seid);
6647                         /* Will try to configure as many components */
6648                 }
6649         }
6650
6651         /* Update each VSI */
6652         for (v = 0; v < pf->num_alloc_vsi; v++) {
6653                 if (!pf->vsi[v])
6654                         continue;
6655
6656                 /* - Enable all TCs for the LAN VSI
6657                  * - For all others keep them at TC0 for now
6658                  */
6659                 if (v == pf->lan_vsi)
6660                         tc_map = i40e_pf_get_tc_map(pf);
6661                 else
6662                         tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6663
6664                 ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6665                 if (ret) {
6666                         dev_info(&pf->pdev->dev,
6667                                  "Failed configuring TC for VSI seid=%d\n",
6668                                  pf->vsi[v]->seid);
6669                         /* Will try to configure as many components */
6670                 } else {
6671                         /* Re-configure VSI vectors based on updated TC map */
6672                         i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6673                         if (pf->vsi[v]->netdev)
6674                                 i40e_dcbnl_set_all(pf->vsi[v]);
6675                 }
6676         }
6677 }
6678
6679 /**
6680  * i40e_resume_port_tx - Resume port Tx
6681  * @pf: PF struct
6682  *
6683  * Resume a port's Tx and issue a PF reset in case of failure to
6684  * resume.
6685  **/
6686 static int i40e_resume_port_tx(struct i40e_pf *pf)
6687 {
6688         struct i40e_hw *hw = &pf->hw;
6689         int ret;
6690
6691         ret = i40e_aq_resume_port_tx(hw, NULL);
6692         if (ret) {
6693                 dev_info(&pf->pdev->dev,
6694                          "Resume Port Tx failed, err %s aq_err %s\n",
6695                           i40e_stat_str(&pf->hw, ret),
6696                           i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6697                 /* Schedule PF reset to recover */
6698                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6699                 i40e_service_event_schedule(pf);
6700         }
6701
6702         return ret;
6703 }
6704
6705 /**
6706  * i40e_suspend_port_tx - Suspend port Tx
6707  * @pf: PF struct
6708  *
6709  * Suspend a port's Tx and issue a PF reset in case of failure.
6710  **/
6711 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6712 {
6713         struct i40e_hw *hw = &pf->hw;
6714         int ret;
6715
6716         ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6717         if (ret) {
6718                 dev_info(&pf->pdev->dev,
6719                          "Suspend Port Tx failed, err %s aq_err %s\n",
6720                          i40e_stat_str(&pf->hw, ret),
6721                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6722                 /* Schedule PF reset to recover */
6723                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6724                 i40e_service_event_schedule(pf);
6725         }
6726
6727         return ret;
6728 }
6729
6730 /**
6731  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6732  * @pf: PF being configured
6733  * @new_cfg: New DCBX configuration
6734  *
6735  * Program DCB settings into HW and reconfigure VEB/VSIs on
6736  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6737  **/
6738 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6739                                   struct i40e_dcbx_config *new_cfg)
6740 {
6741         struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6742         int ret;
6743
6744         /* Check if need reconfiguration */
6745         if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6746                 dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6747                 return 0;
6748         }
6749
6750         /* Config change disable all VSIs */
6751         i40e_pf_quiesce_all_vsi(pf);
6752
6753         /* Copy the new config to the current config */
6754         *old_cfg = *new_cfg;
6755         old_cfg->etsrec = old_cfg->etscfg;
6756         ret = i40e_set_dcb_config(&pf->hw);
6757         if (ret) {
6758                 dev_info(&pf->pdev->dev,
6759                          "Set DCB Config failed, err %s aq_err %s\n",
6760                          i40e_stat_str(&pf->hw, ret),
6761                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6762                 goto out;
6763         }
6764
6765         /* Changes in configuration update VEB/VSI */
6766         i40e_dcb_reconfigure(pf);
6767 out:
6768         /* In case of reset do not try to resume anything */
6769         if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6770                 /* Re-start the VSIs if disabled */
6771                 ret = i40e_resume_port_tx(pf);
6772                 /* In case of error no point in resuming VSIs */
6773                 if (ret)
6774                         goto err;
6775                 i40e_pf_unquiesce_all_vsi(pf);
6776         }
6777 err:
6778         return ret;
6779 }
6780
6781 /**
6782  * i40e_hw_dcb_config - Program new DCBX settings into HW
6783  * @pf: PF being configured
6784  * @new_cfg: New DCBX configuration
6785  *
6786  * Program DCB settings into HW and reconfigure VEB/VSIs on
6787  * given PF
6788  **/
6789 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6790 {
6791         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6792         u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6793         u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6794         struct i40e_dcbx_config *old_cfg;
6795         u8 mode[I40E_MAX_TRAFFIC_CLASS];
6796         struct i40e_rx_pb_config pb_cfg;
6797         struct i40e_hw *hw = &pf->hw;
6798         u8 num_ports = hw->num_ports;
6799         bool need_reconfig;
6800         int ret = -EINVAL;
6801         u8 lltc_map = 0;
6802         u8 tc_map = 0;
6803         u8 new_numtc;
6804         u8 i;
6805
6806         dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6807         /* Un-pack information to Program ETS HW via shared API
6808          * numtc, tcmap
6809          * LLTC map
6810          * ETS/NON-ETS arbiter mode
6811          * max exponent (credit refills)
6812          * Total number of ports
6813          * PFC priority bit-map
6814          * Priority Table
6815          * BW % per TC
6816          * Arbiter mode between UPs sharing same TC
6817          * TSA table (ETS or non-ETS)
6818          * EEE enabled or not
6819          * MFS TC table
6820          */
6821
6822         new_numtc = i40e_dcb_get_num_tc(new_cfg);
6823
6824         memset(&ets_data, 0, sizeof(ets_data));
6825         for (i = 0; i < new_numtc; i++) {
6826                 tc_map |= BIT(i);
6827                 switch (new_cfg->etscfg.tsatable[i]) {
6828                 case I40E_IEEE_TSA_ETS:
6829                         prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6830                         ets_data.tc_bw_share_credits[i] =
6831                                         new_cfg->etscfg.tcbwtable[i];
6832                         break;
6833                 case I40E_IEEE_TSA_STRICT:
6834                         prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6835                         lltc_map |= BIT(i);
6836                         ets_data.tc_bw_share_credits[i] =
6837                                         I40E_DCB_STRICT_PRIO_CREDITS;
6838                         break;
6839                 default:
6840                         /* Invalid TSA type */
6841                         need_reconfig = false;
6842                         goto out;
6843                 }
6844         }
6845
6846         old_cfg = &hw->local_dcbx_config;
6847         /* Check if need reconfiguration */
6848         need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6849
6850         /* If needed, enable/disable frame tagging, disable all VSIs
6851          * and suspend port tx
6852          */
6853         if (need_reconfig) {
6854                 /* Enable DCB tagging only when more than one TC */
6855                 if (new_numtc > 1)
6856                         pf->flags |= I40E_FLAG_DCB_ENABLED;
6857                 else
6858                         pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6859
6860                 set_bit(__I40E_PORT_SUSPENDED, pf->state);
6861                 /* Reconfiguration needed quiesce all VSIs */
6862                 i40e_pf_quiesce_all_vsi(pf);
6863                 ret = i40e_suspend_port_tx(pf);
6864                 if (ret)
6865                         goto err;
6866         }
6867
6868         /* Configure Port ETS Tx Scheduler */
6869         ets_data.tc_valid_bits = tc_map;
6870         ets_data.tc_strict_priority_flags = lltc_map;
6871         ret = i40e_aq_config_switch_comp_ets
6872                 (hw, pf->mac_seid, &ets_data,
6873                  i40e_aqc_opc_modify_switching_comp_ets, NULL);
6874         if (ret) {
6875                 dev_info(&pf->pdev->dev,
6876                          "Modify Port ETS failed, err %s aq_err %s\n",
6877                          i40e_stat_str(&pf->hw, ret),
6878                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6879                 goto out;
6880         }
6881
6882         /* Configure Rx ETS HW */
6883         memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
6884         i40e_dcb_hw_set_num_tc(hw, new_numtc);
6885         i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
6886                                    I40E_DCB_ARB_MODE_STRICT_PRIORITY,
6887                                    I40E_DCB_DEFAULT_MAX_EXPONENT,
6888                                    lltc_map);
6889         i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
6890         i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
6891                                      prio_type);
6892         i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
6893                                new_cfg->etscfg.prioritytable);
6894         i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
6895
6896         /* Configure Rx Packet Buffers in HW */
6897         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6898                 mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
6899                 mfs_tc[i] += I40E_PACKET_HDR_PAD;
6900         }
6901
6902         i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
6903                                          false, new_cfg->pfc.pfcenable,
6904                                          mfs_tc, &pb_cfg);
6905         i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
6906
6907         /* Update the local Rx Packet buffer config */
6908         pf->pb_cfg = pb_cfg;
6909
6910         /* Inform the FW about changes to DCB configuration */
6911         ret = i40e_aq_dcb_updated(&pf->hw, NULL);
6912         if (ret) {
6913                 dev_info(&pf->pdev->dev,
6914                          "DCB Updated failed, err %s aq_err %s\n",
6915                          i40e_stat_str(&pf->hw, ret),
6916                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6917                 goto out;
6918         }
6919
6920         /* Update the port DCBx configuration */
6921         *old_cfg = *new_cfg;
6922
6923         /* Changes in configuration update VEB/VSI */
6924         i40e_dcb_reconfigure(pf);
6925 out:
6926         /* Re-start the VSIs if disabled */
6927         if (need_reconfig) {
6928                 ret = i40e_resume_port_tx(pf);
6929
6930                 clear_bit(__I40E_PORT_SUSPENDED, pf->state);
6931                 /* In case of error no point in resuming VSIs */
6932                 if (ret)
6933                         goto err;
6934
6935                 /* Wait for the PF's queues to be disabled */
6936                 ret = i40e_pf_wait_queues_disabled(pf);
6937                 if (ret) {
6938                         /* Schedule PF reset to recover */
6939                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6940                         i40e_service_event_schedule(pf);
6941                         goto err;
6942                 } else {
6943                         i40e_pf_unquiesce_all_vsi(pf);
6944                         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
6945                         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
6946                 }
6947                 /* registers are set, lets apply */
6948                 if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
6949                         ret = i40e_hw_set_dcb_config(pf, new_cfg);
6950         }
6951
6952 err:
6953         return ret;
6954 }
6955
6956 /**
6957  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
6958  * @pf: PF being queried
6959  *
6960  * Set default DCB configuration in case DCB is to be done in SW.
6961  **/
6962 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
6963 {
6964         struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
6965         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6966         struct i40e_hw *hw = &pf->hw;
6967         int err;
6968
6969         if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
6970                 /* Update the local cached instance with TC0 ETS */
6971                 memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
6972                 pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
6973                 pf->tmp_cfg.etscfg.maxtcs = 0;
6974                 pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
6975                 pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
6976                 pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
6977                 pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
6978                 /* FW needs one App to configure HW */
6979                 pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
6980                 pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
6981                 pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
6982                 pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
6983
6984                 return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
6985         }
6986
6987         memset(&ets_data, 0, sizeof(ets_data));
6988         ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
6989         ets_data.tc_strict_priority_flags = 0; /* ETS */
6990         ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
6991
6992         /* Enable ETS on the Physical port */
6993         err = i40e_aq_config_switch_comp_ets
6994                 (hw, pf->mac_seid, &ets_data,
6995                  i40e_aqc_opc_enable_switching_comp_ets, NULL);
6996         if (err) {
6997                 dev_info(&pf->pdev->dev,
6998                          "Enable Port ETS failed, err %s aq_err %s\n",
6999                          i40e_stat_str(&pf->hw, err),
7000                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7001                 err = -ENOENT;
7002                 goto out;
7003         }
7004
7005         /* Update the local cached instance with TC0 ETS */
7006         dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7007         dcb_cfg->etscfg.cbs = 0;
7008         dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7009         dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7010
7011 out:
7012         return err;
7013 }
7014
7015 /**
7016  * i40e_init_pf_dcb - Initialize DCB configuration
7017  * @pf: PF being configured
7018  *
7019  * Query the current DCB configuration and cache it
7020  * in the hardware structure
7021  **/
7022 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7023 {
7024         struct i40e_hw *hw = &pf->hw;
7025         int err;
7026
7027         /* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7028          * Also do not enable DCBx if FW LLDP agent is disabled
7029          */
7030         if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
7031                 dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7032                 err = I40E_NOT_SUPPORTED;
7033                 goto out;
7034         }
7035         if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
7036                 dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7037                 err = i40e_dcb_sw_default_config(pf);
7038                 if (err) {
7039                         dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7040                         goto out;
7041                 }
7042                 dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7043                 pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7044                                DCB_CAP_DCBX_VER_IEEE;
7045                 /* at init capable but disabled */
7046                 pf->flags |= I40E_FLAG_DCB_CAPABLE;
7047                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7048                 goto out;
7049         }
7050         err = i40e_init_dcb(hw, true);
7051         if (!err) {
7052                 /* Device/Function is not DCBX capable */
7053                 if ((!hw->func_caps.dcb) ||
7054                     (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7055                         dev_info(&pf->pdev->dev,
7056                                  "DCBX offload is not supported or is disabled for this PF.\n");
7057                 } else {
7058                         /* When status is not DISABLED then DCBX in FW */
7059                         pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7060                                        DCB_CAP_DCBX_VER_IEEE;
7061
7062                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
7063                         /* Enable DCB tagging only when more than one TC
7064                          * or explicitly disable if only one TC
7065                          */
7066                         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7067                                 pf->flags |= I40E_FLAG_DCB_ENABLED;
7068                         else
7069                                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7070                         dev_dbg(&pf->pdev->dev,
7071                                 "DCBX offload is supported for this PF.\n");
7072                 }
7073         } else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7074                 dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7075                 pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
7076         } else {
7077                 dev_info(&pf->pdev->dev,
7078                          "Query for DCB configuration failed, err %s aq_err %s\n",
7079                          i40e_stat_str(&pf->hw, err),
7080                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7081         }
7082
7083 out:
7084         return err;
7085 }
7086 #endif /* CONFIG_I40E_DCB */
7087
7088 /**
7089  * i40e_print_link_message - print link up or down
7090  * @vsi: the VSI for which link needs a message
7091  * @isup: true of link is up, false otherwise
7092  */
7093 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7094 {
7095         enum i40e_aq_link_speed new_speed;
7096         struct i40e_pf *pf = vsi->back;
7097         char *speed = "Unknown";
7098         char *fc = "Unknown";
7099         char *fec = "";
7100         char *req_fec = "";
7101         char *an = "";
7102
7103         if (isup)
7104                 new_speed = pf->hw.phy.link_info.link_speed;
7105         else
7106                 new_speed = I40E_LINK_SPEED_UNKNOWN;
7107
7108         if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7109                 return;
7110         vsi->current_isup = isup;
7111         vsi->current_speed = new_speed;
7112         if (!isup) {
7113                 netdev_info(vsi->netdev, "NIC Link is Down\n");
7114                 return;
7115         }
7116
7117         /* Warn user if link speed on NPAR enabled partition is not at
7118          * least 10GB
7119          */
7120         if (pf->hw.func_caps.npar_enable &&
7121             (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7122              pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7123                 netdev_warn(vsi->netdev,
7124                             "The partition detected link speed that is less than 10Gbps\n");
7125
7126         switch (pf->hw.phy.link_info.link_speed) {
7127         case I40E_LINK_SPEED_40GB:
7128                 speed = "40 G";
7129                 break;
7130         case I40E_LINK_SPEED_20GB:
7131                 speed = "20 G";
7132                 break;
7133         case I40E_LINK_SPEED_25GB:
7134                 speed = "25 G";
7135                 break;
7136         case I40E_LINK_SPEED_10GB:
7137                 speed = "10 G";
7138                 break;
7139         case I40E_LINK_SPEED_5GB:
7140                 speed = "5 G";
7141                 break;
7142         case I40E_LINK_SPEED_2_5GB:
7143                 speed = "2.5 G";
7144                 break;
7145         case I40E_LINK_SPEED_1GB:
7146                 speed = "1000 M";
7147                 break;
7148         case I40E_LINK_SPEED_100MB:
7149                 speed = "100 M";
7150                 break;
7151         default:
7152                 break;
7153         }
7154
7155         switch (pf->hw.fc.current_mode) {
7156         case I40E_FC_FULL:
7157                 fc = "RX/TX";
7158                 break;
7159         case I40E_FC_TX_PAUSE:
7160                 fc = "TX";
7161                 break;
7162         case I40E_FC_RX_PAUSE:
7163                 fc = "RX";
7164                 break;
7165         default:
7166                 fc = "None";
7167                 break;
7168         }
7169
7170         if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7171                 req_fec = "None";
7172                 fec = "None";
7173                 an = "False";
7174
7175                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7176                         an = "True";
7177
7178                 if (pf->hw.phy.link_info.fec_info &
7179                     I40E_AQ_CONFIG_FEC_KR_ENA)
7180                         fec = "CL74 FC-FEC/BASE-R";
7181                 else if (pf->hw.phy.link_info.fec_info &
7182                          I40E_AQ_CONFIG_FEC_RS_ENA)
7183                         fec = "CL108 RS-FEC";
7184
7185                 /* 'CL108 RS-FEC' should be displayed when RS is requested, or
7186                  * both RS and FC are requested
7187                  */
7188                 if (vsi->back->hw.phy.link_info.req_fec_info &
7189                     (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7190                         if (vsi->back->hw.phy.link_info.req_fec_info &
7191                             I40E_AQ_REQUEST_FEC_RS)
7192                                 req_fec = "CL108 RS-FEC";
7193                         else
7194                                 req_fec = "CL74 FC-FEC/BASE-R";
7195                 }
7196                 netdev_info(vsi->netdev,
7197                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7198                             speed, req_fec, fec, an, fc);
7199         } else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7200                 req_fec = "None";
7201                 fec = "None";
7202                 an = "False";
7203
7204                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7205                         an = "True";
7206
7207                 if (pf->hw.phy.link_info.fec_info &
7208                     I40E_AQ_CONFIG_FEC_KR_ENA)
7209                         fec = "CL74 FC-FEC/BASE-R";
7210
7211                 if (pf->hw.phy.link_info.req_fec_info &
7212                     I40E_AQ_REQUEST_FEC_KR)
7213                         req_fec = "CL74 FC-FEC/BASE-R";
7214
7215                 netdev_info(vsi->netdev,
7216                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7217                             speed, req_fec, fec, an, fc);
7218         } else {
7219                 netdev_info(vsi->netdev,
7220                             "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7221                             speed, fc);
7222         }
7223
7224 }
7225
7226 /**
7227  * i40e_up_complete - Finish the last steps of bringing up a connection
7228  * @vsi: the VSI being configured
7229  **/
7230 static int i40e_up_complete(struct i40e_vsi *vsi)
7231 {
7232         struct i40e_pf *pf = vsi->back;
7233         int err;
7234
7235         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7236                 i40e_vsi_configure_msix(vsi);
7237         else
7238                 i40e_configure_msi_and_legacy(vsi);
7239
7240         /* start rings */
7241         err = i40e_vsi_start_rings(vsi);
7242         if (err)
7243                 return err;
7244
7245         clear_bit(__I40E_VSI_DOWN, vsi->state);
7246         i40e_napi_enable_all(vsi);
7247         i40e_vsi_enable_irq(vsi);
7248
7249         if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7250             (vsi->netdev)) {
7251                 i40e_print_link_message(vsi, true);
7252                 netif_tx_start_all_queues(vsi->netdev);
7253                 netif_carrier_on(vsi->netdev);
7254         }
7255
7256         /* replay FDIR SB filters */
7257         if (vsi->type == I40E_VSI_FDIR) {
7258                 /* reset fd counters */
7259                 pf->fd_add_err = 0;
7260                 pf->fd_atr_cnt = 0;
7261                 i40e_fdir_filter_restore(vsi);
7262         }
7263
7264         /* On the next run of the service_task, notify any clients of the new
7265          * opened netdev
7266          */
7267         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7268         i40e_service_event_schedule(pf);
7269
7270         return 0;
7271 }
7272
7273 /**
7274  * i40e_vsi_reinit_locked - Reset the VSI
7275  * @vsi: the VSI being configured
7276  *
7277  * Rebuild the ring structs after some configuration
7278  * has changed, e.g. MTU size.
7279  **/
7280 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7281 {
7282         struct i40e_pf *pf = vsi->back;
7283
7284         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7285                 usleep_range(1000, 2000);
7286         i40e_down(vsi);
7287
7288         i40e_up(vsi);
7289         clear_bit(__I40E_CONFIG_BUSY, pf->state);
7290 }
7291
7292 /**
7293  * i40e_force_link_state - Force the link status
7294  * @pf: board private structure
7295  * @is_up: whether the link state should be forced up or down
7296  **/
7297 static i40e_status i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7298 {
7299         struct i40e_aq_get_phy_abilities_resp abilities;
7300         struct i40e_aq_set_phy_config config = {0};
7301         bool non_zero_phy_type = is_up;
7302         struct i40e_hw *hw = &pf->hw;
7303         i40e_status err;
7304         u64 mask;
7305         u8 speed;
7306
7307         /* Card might've been put in an unstable state by other drivers
7308          * and applications, which causes incorrect speed values being
7309          * set on startup. In order to clear speed registers, we call
7310          * get_phy_capabilities twice, once to get initial state of
7311          * available speeds, and once to get current PHY config.
7312          */
7313         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7314                                            NULL);
7315         if (err) {
7316                 dev_err(&pf->pdev->dev,
7317                         "failed to get phy cap., ret =  %s last_status =  %s\n",
7318                         i40e_stat_str(hw, err),
7319                         i40e_aq_str(hw, hw->aq.asq_last_status));
7320                 return err;
7321         }
7322         speed = abilities.link_speed;
7323
7324         /* Get the current phy config */
7325         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7326                                            NULL);
7327         if (err) {
7328                 dev_err(&pf->pdev->dev,
7329                         "failed to get phy cap., ret =  %s last_status =  %s\n",
7330                         i40e_stat_str(hw, err),
7331                         i40e_aq_str(hw, hw->aq.asq_last_status));
7332                 return err;
7333         }
7334
7335         /* If link needs to go up, but was not forced to go down,
7336          * and its speed values are OK, no need for a flap
7337          * if non_zero_phy_type was set, still need to force up
7338          */
7339         if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7340                 non_zero_phy_type = true;
7341         else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7342                 return I40E_SUCCESS;
7343
7344         /* To force link we need to set bits for all supported PHY types,
7345          * but there are now more than 32, so we need to split the bitmap
7346          * across two fields.
7347          */
7348         mask = I40E_PHY_TYPES_BITMASK;
7349         config.phy_type =
7350                 non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7351         config.phy_type_ext =
7352                 non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7353         /* Copy the old settings, except of phy_type */
7354         config.abilities = abilities.abilities;
7355         if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7356                 if (is_up)
7357                         config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7358                 else
7359                         config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7360         }
7361         if (abilities.link_speed != 0)
7362                 config.link_speed = abilities.link_speed;
7363         else
7364                 config.link_speed = speed;
7365         config.eee_capability = abilities.eee_capability;
7366         config.eeer = abilities.eeer_val;
7367         config.low_power_ctrl = abilities.d3_lpan;
7368         config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7369                             I40E_AQ_PHY_FEC_CONFIG_MASK;
7370         err = i40e_aq_set_phy_config(hw, &config, NULL);
7371
7372         if (err) {
7373                 dev_err(&pf->pdev->dev,
7374                         "set phy config ret =  %s last_status =  %s\n",
7375                         i40e_stat_str(&pf->hw, err),
7376                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7377                 return err;
7378         }
7379
7380         /* Update the link info */
7381         err = i40e_update_link_info(hw);
7382         if (err) {
7383                 /* Wait a little bit (on 40G cards it sometimes takes a really
7384                  * long time for link to come back from the atomic reset)
7385                  * and try once more
7386                  */
7387                 msleep(1000);
7388                 i40e_update_link_info(hw);
7389         }
7390
7391         i40e_aq_set_link_restart_an(hw, is_up, NULL);
7392
7393         return I40E_SUCCESS;
7394 }
7395
7396 /**
7397  * i40e_up - Bring the connection back up after being down
7398  * @vsi: the VSI being configured
7399  **/
7400 int i40e_up(struct i40e_vsi *vsi)
7401 {
7402         int err;
7403
7404         if (vsi->type == I40E_VSI_MAIN &&
7405             (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7406              vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7407                 i40e_force_link_state(vsi->back, true);
7408
7409         err = i40e_vsi_configure(vsi);
7410         if (!err)
7411                 err = i40e_up_complete(vsi);
7412
7413         return err;
7414 }
7415
7416 /**
7417  * i40e_down - Shutdown the connection processing
7418  * @vsi: the VSI being stopped
7419  **/
7420 void i40e_down(struct i40e_vsi *vsi)
7421 {
7422         int i;
7423
7424         /* It is assumed that the caller of this function
7425          * sets the vsi->state __I40E_VSI_DOWN bit.
7426          */
7427         if (vsi->netdev) {
7428                 netif_carrier_off(vsi->netdev);
7429                 netif_tx_disable(vsi->netdev);
7430         }
7431         i40e_vsi_disable_irq(vsi);
7432         i40e_vsi_stop_rings(vsi);
7433         if (vsi->type == I40E_VSI_MAIN &&
7434            (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7435             vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7436                 i40e_force_link_state(vsi->back, false);
7437         i40e_napi_disable_all(vsi);
7438
7439         for (i = 0; i < vsi->num_queue_pairs; i++) {
7440                 i40e_clean_tx_ring(vsi->tx_rings[i]);
7441                 if (i40e_enabled_xdp_vsi(vsi)) {
7442                         /* Make sure that in-progress ndo_xdp_xmit and
7443                          * ndo_xsk_wakeup calls are completed.
7444                          */
7445                         synchronize_rcu();
7446                         i40e_clean_tx_ring(vsi->xdp_rings[i]);
7447                 }
7448                 i40e_clean_rx_ring(vsi->rx_rings[i]);
7449         }
7450
7451 }
7452
7453 /**
7454  * i40e_validate_mqprio_qopt- validate queue mapping info
7455  * @vsi: the VSI being configured
7456  * @mqprio_qopt: queue parametrs
7457  **/
7458 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7459                                      struct tc_mqprio_qopt_offload *mqprio_qopt)
7460 {
7461         u64 sum_max_rate = 0;
7462         u64 max_rate = 0;
7463         int i;
7464
7465         if (mqprio_qopt->qopt.offset[0] != 0 ||
7466             mqprio_qopt->qopt.num_tc < 1 ||
7467             mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7468                 return -EINVAL;
7469         for (i = 0; ; i++) {
7470                 if (!mqprio_qopt->qopt.count[i])
7471                         return -EINVAL;
7472                 if (mqprio_qopt->min_rate[i]) {
7473                         dev_err(&vsi->back->pdev->dev,
7474                                 "Invalid min tx rate (greater than 0) specified\n");
7475                         return -EINVAL;
7476                 }
7477                 max_rate = mqprio_qopt->max_rate[i];
7478                 do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7479                 sum_max_rate += max_rate;
7480
7481                 if (i >= mqprio_qopt->qopt.num_tc - 1)
7482                         break;
7483                 if (mqprio_qopt->qopt.offset[i + 1] !=
7484                     (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7485                         return -EINVAL;
7486         }
7487         if (vsi->num_queue_pairs <
7488             (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7489                 dev_err(&vsi->back->pdev->dev,
7490                         "Failed to create traffic channel, insufficient number of queues.\n");
7491                 return -EINVAL;
7492         }
7493         if (sum_max_rate > i40e_get_link_speed(vsi)) {
7494                 dev_err(&vsi->back->pdev->dev,
7495                         "Invalid max tx rate specified\n");
7496                 return -EINVAL;
7497         }
7498         return 0;
7499 }
7500
7501 /**
7502  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7503  * @vsi: the VSI being configured
7504  **/
7505 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7506 {
7507         u16 qcount;
7508         int i;
7509
7510         /* Only TC0 is enabled */
7511         vsi->tc_config.numtc = 1;
7512         vsi->tc_config.enabled_tc = 1;
7513         qcount = min_t(int, vsi->alloc_queue_pairs,
7514                        i40e_pf_get_max_q_per_tc(vsi->back));
7515         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7516                 /* For the TC that is not enabled set the offset to default
7517                  * queue and allocate one queue for the given TC.
7518                  */
7519                 vsi->tc_config.tc_info[i].qoffset = 0;
7520                 if (i == 0)
7521                         vsi->tc_config.tc_info[i].qcount = qcount;
7522                 else
7523                         vsi->tc_config.tc_info[i].qcount = 1;
7524                 vsi->tc_config.tc_info[i].netdev_tc = 0;
7525         }
7526 }
7527
7528 /**
7529  * i40e_del_macvlan_filter
7530  * @hw: pointer to the HW structure
7531  * @seid: seid of the channel VSI
7532  * @macaddr: the mac address to apply as a filter
7533  * @aq_err: store the admin Q error
7534  *
7535  * This function deletes a mac filter on the channel VSI which serves as the
7536  * macvlan. Returns 0 on success.
7537  **/
7538 static i40e_status i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7539                                            const u8 *macaddr, int *aq_err)
7540 {
7541         struct i40e_aqc_remove_macvlan_element_data element;
7542         i40e_status status;
7543
7544         memset(&element, 0, sizeof(element));
7545         ether_addr_copy(element.mac_addr, macaddr);
7546         element.vlan_tag = 0;
7547         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7548         status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7549         *aq_err = hw->aq.asq_last_status;
7550
7551         return status;
7552 }
7553
7554 /**
7555  * i40e_add_macvlan_filter
7556  * @hw: pointer to the HW structure
7557  * @seid: seid of the channel VSI
7558  * @macaddr: the mac address to apply as a filter
7559  * @aq_err: store the admin Q error
7560  *
7561  * This function adds a mac filter on the channel VSI which serves as the
7562  * macvlan. Returns 0 on success.
7563  **/
7564 static i40e_status i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7565                                            const u8 *macaddr, int *aq_err)
7566 {
7567         struct i40e_aqc_add_macvlan_element_data element;
7568         i40e_status status;
7569         u16 cmd_flags = 0;
7570
7571         ether_addr_copy(element.mac_addr, macaddr);
7572         element.vlan_tag = 0;
7573         element.queue_number = 0;
7574         element.match_method = I40E_AQC_MM_ERR_NO_RES;
7575         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7576         element.flags = cpu_to_le16(cmd_flags);
7577         status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7578         *aq_err = hw->aq.asq_last_status;
7579
7580         return status;
7581 }
7582
7583 /**
7584  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7585  * @vsi: the VSI we want to access
7586  * @ch: the channel we want to access
7587  */
7588 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7589 {
7590         struct i40e_ring *tx_ring, *rx_ring;
7591         u16 pf_q;
7592         int i;
7593
7594         for (i = 0; i < ch->num_queue_pairs; i++) {
7595                 pf_q = ch->base_queue + i;
7596                 tx_ring = vsi->tx_rings[pf_q];
7597                 tx_ring->ch = NULL;
7598                 rx_ring = vsi->rx_rings[pf_q];
7599                 rx_ring->ch = NULL;
7600         }
7601 }
7602
7603 /**
7604  * i40e_free_macvlan_channels
7605  * @vsi: the VSI we want to access
7606  *
7607  * This function frees the Qs of the channel VSI from
7608  * the stack and also deletes the channel VSIs which
7609  * serve as macvlans.
7610  */
7611 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7612 {
7613         struct i40e_channel *ch, *ch_tmp;
7614         int ret;
7615
7616         if (list_empty(&vsi->macvlan_list))
7617                 return;
7618
7619         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7620                 struct i40e_vsi *parent_vsi;
7621
7622                 if (i40e_is_channel_macvlan(ch)) {
7623                         i40e_reset_ch_rings(vsi, ch);
7624                         clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7625                         netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7626                         netdev_set_sb_channel(ch->fwd->netdev, 0);
7627                         kfree(ch->fwd);
7628                         ch->fwd = NULL;
7629                 }
7630
7631                 list_del(&ch->list);
7632                 parent_vsi = ch->parent_vsi;
7633                 if (!parent_vsi || !ch->initialized) {
7634                         kfree(ch);
7635                         continue;
7636                 }
7637
7638                 /* remove the VSI */
7639                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7640                                              NULL);
7641                 if (ret)
7642                         dev_err(&vsi->back->pdev->dev,
7643                                 "unable to remove channel (%d) for parent VSI(%d)\n",
7644                                 ch->seid, parent_vsi->seid);
7645                 kfree(ch);
7646         }
7647         vsi->macvlan_cnt = 0;
7648 }
7649
7650 /**
7651  * i40e_fwd_ring_up - bring the macvlan device up
7652  * @vsi: the VSI we want to access
7653  * @vdev: macvlan netdevice
7654  * @fwd: the private fwd structure
7655  */
7656 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7657                             struct i40e_fwd_adapter *fwd)
7658 {
7659         struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7660         int ret = 0, num_tc = 1,  i, aq_err;
7661         struct i40e_pf *pf = vsi->back;
7662         struct i40e_hw *hw = &pf->hw;
7663
7664         /* Go through the list and find an available channel */
7665         list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7666                 if (!i40e_is_channel_macvlan(iter)) {
7667                         iter->fwd = fwd;
7668                         /* record configuration for macvlan interface in vdev */
7669                         for (i = 0; i < num_tc; i++)
7670                                 netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7671                                                              i,
7672                                                              iter->num_queue_pairs,
7673                                                              iter->base_queue);
7674                         for (i = 0; i < iter->num_queue_pairs; i++) {
7675                                 struct i40e_ring *tx_ring, *rx_ring;
7676                                 u16 pf_q;
7677
7678                                 pf_q = iter->base_queue + i;
7679
7680                                 /* Get to TX ring ptr */
7681                                 tx_ring = vsi->tx_rings[pf_q];
7682                                 tx_ring->ch = iter;
7683
7684                                 /* Get the RX ring ptr */
7685                                 rx_ring = vsi->rx_rings[pf_q];
7686                                 rx_ring->ch = iter;
7687                         }
7688                         ch = iter;
7689                         break;
7690                 }
7691         }
7692
7693         if (!ch)
7694                 return -EINVAL;
7695
7696         /* Guarantee all rings are updated before we update the
7697          * MAC address filter.
7698          */
7699         wmb();
7700
7701         /* Add a mac filter */
7702         ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7703         if (ret) {
7704                 /* if we cannot add the MAC rule then disable the offload */
7705                 macvlan_release_l2fw_offload(vdev);
7706                 for (i = 0; i < ch->num_queue_pairs; i++) {
7707                         struct i40e_ring *rx_ring;
7708                         u16 pf_q;
7709
7710                         pf_q = ch->base_queue + i;
7711                         rx_ring = vsi->rx_rings[pf_q];
7712                         rx_ring->netdev = NULL;
7713                 }
7714                 dev_info(&pf->pdev->dev,
7715                          "Error adding mac filter on macvlan err %s, aq_err %s\n",
7716                           i40e_stat_str(hw, ret),
7717                           i40e_aq_str(hw, aq_err));
7718                 netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7719         }
7720
7721         return ret;
7722 }
7723
7724 /**
7725  * i40e_setup_macvlans - create the channels which will be macvlans
7726  * @vsi: the VSI we want to access
7727  * @macvlan_cnt: no. of macvlans to be setup
7728  * @qcnt: no. of Qs per macvlan
7729  * @vdev: macvlan netdevice
7730  */
7731 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7732                                struct net_device *vdev)
7733 {
7734         struct i40e_pf *pf = vsi->back;
7735         struct i40e_hw *hw = &pf->hw;
7736         struct i40e_vsi_context ctxt;
7737         u16 sections, qmap, num_qps;
7738         struct i40e_channel *ch;
7739         int i, pow, ret = 0;
7740         u8 offset = 0;
7741
7742         if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7743                 return -EINVAL;
7744
7745         num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7746
7747         /* find the next higher power-of-2 of num queue pairs */
7748         pow = fls(roundup_pow_of_two(num_qps) - 1);
7749
7750         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7751                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7752
7753         /* Setup context bits for the main VSI */
7754         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7755         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7756         memset(&ctxt, 0, sizeof(ctxt));
7757         ctxt.seid = vsi->seid;
7758         ctxt.pf_num = vsi->back->hw.pf_id;
7759         ctxt.vf_num = 0;
7760         ctxt.uplink_seid = vsi->uplink_seid;
7761         ctxt.info = vsi->info;
7762         ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7763         ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7764         ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7765         ctxt.info.valid_sections |= cpu_to_le16(sections);
7766
7767         /* Reconfigure RSS for main VSI with new max queue count */
7768         vsi->rss_size = max_t(u16, num_qps, qcnt);
7769         ret = i40e_vsi_config_rss(vsi);
7770         if (ret) {
7771                 dev_info(&pf->pdev->dev,
7772                          "Failed to reconfig RSS for num_queues (%u)\n",
7773                          vsi->rss_size);
7774                 return ret;
7775         }
7776         vsi->reconfig_rss = true;
7777         dev_dbg(&vsi->back->pdev->dev,
7778                 "Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7779         vsi->next_base_queue = num_qps;
7780         vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7781
7782         /* Update the VSI after updating the VSI queue-mapping
7783          * information
7784          */
7785         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7786         if (ret) {
7787                 dev_info(&pf->pdev->dev,
7788                          "Update vsi tc config failed, err %s aq_err %s\n",
7789                          i40e_stat_str(hw, ret),
7790                          i40e_aq_str(hw, hw->aq.asq_last_status));
7791                 return ret;
7792         }
7793         /* update the local VSI info with updated queue map */
7794         i40e_vsi_update_queue_map(vsi, &ctxt);
7795         vsi->info.valid_sections = 0;
7796
7797         /* Create channels for macvlans */
7798         INIT_LIST_HEAD(&vsi->macvlan_list);
7799         for (i = 0; i < macvlan_cnt; i++) {
7800                 ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7801                 if (!ch) {
7802                         ret = -ENOMEM;
7803                         goto err_free;
7804                 }
7805                 INIT_LIST_HEAD(&ch->list);
7806                 ch->num_queue_pairs = qcnt;
7807                 if (!i40e_setup_channel(pf, vsi, ch)) {
7808                         ret = -EINVAL;
7809                         kfree(ch);
7810                         goto err_free;
7811                 }
7812                 ch->parent_vsi = vsi;
7813                 vsi->cnt_q_avail -= ch->num_queue_pairs;
7814                 vsi->macvlan_cnt++;
7815                 list_add_tail(&ch->list, &vsi->macvlan_list);
7816         }
7817
7818         return ret;
7819
7820 err_free:
7821         dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7822         i40e_free_macvlan_channels(vsi);
7823
7824         return ret;
7825 }
7826
7827 /**
7828  * i40e_fwd_add - configure macvlans
7829  * @netdev: net device to configure
7830  * @vdev: macvlan netdevice
7831  **/
7832 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7833 {
7834         struct i40e_netdev_priv *np = netdev_priv(netdev);
7835         u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7836         struct i40e_vsi *vsi = np->vsi;
7837         struct i40e_pf *pf = vsi->back;
7838         struct i40e_fwd_adapter *fwd;
7839         int avail_macvlan, ret;
7840
7841         if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7842                 netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7843                 return ERR_PTR(-EINVAL);
7844         }
7845         if (i40e_is_tc_mqprio_enabled(pf)) {
7846                 netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7847                 return ERR_PTR(-EINVAL);
7848         }
7849         if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7850                 netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7851                 return ERR_PTR(-EINVAL);
7852         }
7853
7854         /* The macvlan device has to be a single Q device so that the
7855          * tc_to_txq field can be reused to pick the tx queue.
7856          */
7857         if (netif_is_multiqueue(vdev))
7858                 return ERR_PTR(-ERANGE);
7859
7860         if (!vsi->macvlan_cnt) {
7861                 /* reserve bit 0 for the pf device */
7862                 set_bit(0, vsi->fwd_bitmask);
7863
7864                 /* Try to reserve as many queues as possible for macvlans. First
7865                  * reserve 3/4th of max vectors, then half, then quarter and
7866                  * calculate Qs per macvlan as you go
7867                  */
7868                 vectors = pf->num_lan_msix;
7869                 if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7870                         /* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7871                         q_per_macvlan = 4;
7872                         macvlan_cnt = (vectors - 32) / 4;
7873                 } else if (vectors <= 64 && vectors > 32) {
7874                         /* allocate 2 Qs per macvlan and 16 Qs to the PF*/
7875                         q_per_macvlan = 2;
7876                         macvlan_cnt = (vectors - 16) / 2;
7877                 } else if (vectors <= 32 && vectors > 16) {
7878                         /* allocate 1 Q per macvlan and 16 Qs to the PF*/
7879                         q_per_macvlan = 1;
7880                         macvlan_cnt = vectors - 16;
7881                 } else if (vectors <= 16 && vectors > 8) {
7882                         /* allocate 1 Q per macvlan and 8 Qs to the PF */
7883                         q_per_macvlan = 1;
7884                         macvlan_cnt = vectors - 8;
7885                 } else {
7886                         /* allocate 1 Q per macvlan and 1 Q to the PF */
7887                         q_per_macvlan = 1;
7888                         macvlan_cnt = vectors - 1;
7889                 }
7890
7891                 if (macvlan_cnt == 0)
7892                         return ERR_PTR(-EBUSY);
7893
7894                 /* Quiesce VSI queues */
7895                 i40e_quiesce_vsi(vsi);
7896
7897                 /* sets up the macvlans but does not "enable" them */
7898                 ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
7899                                           vdev);
7900                 if (ret)
7901                         return ERR_PTR(ret);
7902
7903                 /* Unquiesce VSI */
7904                 i40e_unquiesce_vsi(vsi);
7905         }
7906         avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
7907                                             vsi->macvlan_cnt);
7908         if (avail_macvlan >= I40E_MAX_MACVLANS)
7909                 return ERR_PTR(-EBUSY);
7910
7911         /* create the fwd struct */
7912         fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
7913         if (!fwd)
7914                 return ERR_PTR(-ENOMEM);
7915
7916         set_bit(avail_macvlan, vsi->fwd_bitmask);
7917         fwd->bit_no = avail_macvlan;
7918         netdev_set_sb_channel(vdev, avail_macvlan);
7919         fwd->netdev = vdev;
7920
7921         if (!netif_running(netdev))
7922                 return fwd;
7923
7924         /* Set fwd ring up */
7925         ret = i40e_fwd_ring_up(vsi, vdev, fwd);
7926         if (ret) {
7927                 /* unbind the queues and drop the subordinate channel config */
7928                 netdev_unbind_sb_channel(netdev, vdev);
7929                 netdev_set_sb_channel(vdev, 0);
7930
7931                 kfree(fwd);
7932                 return ERR_PTR(-EINVAL);
7933         }
7934
7935         return fwd;
7936 }
7937
7938 /**
7939  * i40e_del_all_macvlans - Delete all the mac filters on the channels
7940  * @vsi: the VSI we want to access
7941  */
7942 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
7943 {
7944         struct i40e_channel *ch, *ch_tmp;
7945         struct i40e_pf *pf = vsi->back;
7946         struct i40e_hw *hw = &pf->hw;
7947         int aq_err, ret = 0;
7948
7949         if (list_empty(&vsi->macvlan_list))
7950                 return;
7951
7952         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7953                 if (i40e_is_channel_macvlan(ch)) {
7954                         ret = i40e_del_macvlan_filter(hw, ch->seid,
7955                                                       i40e_channel_mac(ch),
7956                                                       &aq_err);
7957                         if (!ret) {
7958                                 /* Reset queue contexts */
7959                                 i40e_reset_ch_rings(vsi, ch);
7960                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7961                                 netdev_unbind_sb_channel(vsi->netdev,
7962                                                          ch->fwd->netdev);
7963                                 netdev_set_sb_channel(ch->fwd->netdev, 0);
7964                                 kfree(ch->fwd);
7965                                 ch->fwd = NULL;
7966                         }
7967                 }
7968         }
7969 }
7970
7971 /**
7972  * i40e_fwd_del - delete macvlan interfaces
7973  * @netdev: net device to configure
7974  * @vdev: macvlan netdevice
7975  */
7976 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
7977 {
7978         struct i40e_netdev_priv *np = netdev_priv(netdev);
7979         struct i40e_fwd_adapter *fwd = vdev;
7980         struct i40e_channel *ch, *ch_tmp;
7981         struct i40e_vsi *vsi = np->vsi;
7982         struct i40e_pf *pf = vsi->back;
7983         struct i40e_hw *hw = &pf->hw;
7984         int aq_err, ret = 0;
7985
7986         /* Find the channel associated with the macvlan and del mac filter */
7987         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7988                 if (i40e_is_channel_macvlan(ch) &&
7989                     ether_addr_equal(i40e_channel_mac(ch),
7990                                      fwd->netdev->dev_addr)) {
7991                         ret = i40e_del_macvlan_filter(hw, ch->seid,
7992                                                       i40e_channel_mac(ch),
7993                                                       &aq_err);
7994                         if (!ret) {
7995                                 /* Reset queue contexts */
7996                                 i40e_reset_ch_rings(vsi, ch);
7997                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7998                                 netdev_unbind_sb_channel(netdev, fwd->netdev);
7999                                 netdev_set_sb_channel(fwd->netdev, 0);
8000                                 kfree(ch->fwd);
8001                                 ch->fwd = NULL;
8002                         } else {
8003                                 dev_info(&pf->pdev->dev,
8004                                          "Error deleting mac filter on macvlan err %s, aq_err %s\n",
8005                                           i40e_stat_str(hw, ret),
8006                                           i40e_aq_str(hw, aq_err));
8007                         }
8008                         break;
8009                 }
8010         }
8011 }
8012
8013 /**
8014  * i40e_setup_tc - configure multiple traffic classes
8015  * @netdev: net device to configure
8016  * @type_data: tc offload data
8017  **/
8018 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8019 {
8020         struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8021         struct i40e_netdev_priv *np = netdev_priv(netdev);
8022         struct i40e_vsi *vsi = np->vsi;
8023         struct i40e_pf *pf = vsi->back;
8024         u8 enabled_tc = 0, num_tc, hw;
8025         bool need_reset = false;
8026         int old_queue_pairs;
8027         int ret = -EINVAL;
8028         u16 mode;
8029         int i;
8030
8031         old_queue_pairs = vsi->num_queue_pairs;
8032         num_tc = mqprio_qopt->qopt.num_tc;
8033         hw = mqprio_qopt->qopt.hw;
8034         mode = mqprio_qopt->mode;
8035         if (!hw) {
8036                 pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8037                 memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8038                 goto config_tc;
8039         }
8040
8041         /* Check if MFP enabled */
8042         if (pf->flags & I40E_FLAG_MFP_ENABLED) {
8043                 netdev_info(netdev,
8044                             "Configuring TC not supported in MFP mode\n");
8045                 return ret;
8046         }
8047         switch (mode) {
8048         case TC_MQPRIO_MODE_DCB:
8049                 pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8050
8051                 /* Check if DCB enabled to continue */
8052                 if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
8053                         netdev_info(netdev,
8054                                     "DCB is not enabled for adapter\n");
8055                         return ret;
8056                 }
8057
8058                 /* Check whether tc count is within enabled limit */
8059                 if (num_tc > i40e_pf_get_num_tc(pf)) {
8060                         netdev_info(netdev,
8061                                     "TC count greater than enabled on link for adapter\n");
8062                         return ret;
8063                 }
8064                 break;
8065         case TC_MQPRIO_MODE_CHANNEL:
8066                 if (pf->flags & I40E_FLAG_DCB_ENABLED) {
8067                         netdev_info(netdev,
8068                                     "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8069                         return ret;
8070                 }
8071                 if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8072                         return ret;
8073                 ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8074                 if (ret)
8075                         return ret;
8076                 memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8077                        sizeof(*mqprio_qopt));
8078                 pf->flags |= I40E_FLAG_TC_MQPRIO;
8079                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8080                 break;
8081         default:
8082                 return -EINVAL;
8083         }
8084
8085 config_tc:
8086         /* Generate TC map for number of tc requested */
8087         for (i = 0; i < num_tc; i++)
8088                 enabled_tc |= BIT(i);
8089
8090         /* Requesting same TC configuration as already enabled */
8091         if (enabled_tc == vsi->tc_config.enabled_tc &&
8092             mode != TC_MQPRIO_MODE_CHANNEL)
8093                 return 0;
8094
8095         /* Quiesce VSI queues */
8096         i40e_quiesce_vsi(vsi);
8097
8098         if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8099                 i40e_remove_queue_channels(vsi);
8100
8101         /* Configure VSI for enabled TCs */
8102         ret = i40e_vsi_config_tc(vsi, enabled_tc);
8103         if (ret) {
8104                 netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8105                             vsi->seid);
8106                 need_reset = true;
8107                 goto exit;
8108         } else if (enabled_tc &&
8109                    (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8110                 netdev_info(netdev,
8111                             "Failed to create channel. Override queues (%u) not power of 2\n",
8112                             vsi->tc_config.tc_info[0].qcount);
8113                 ret = -EINVAL;
8114                 need_reset = true;
8115                 goto exit;
8116         }
8117
8118         dev_info(&vsi->back->pdev->dev,
8119                  "Setup channel (id:%u) utilizing num_queues %d\n",
8120                  vsi->seid, vsi->tc_config.tc_info[0].qcount);
8121
8122         if (i40e_is_tc_mqprio_enabled(pf)) {
8123                 if (vsi->mqprio_qopt.max_rate[0]) {
8124                         u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8125                                                   vsi->mqprio_qopt.max_rate[0]);
8126
8127                         ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8128                         if (!ret) {
8129                                 u64 credits = max_tx_rate;
8130
8131                                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
8132                                 dev_dbg(&vsi->back->pdev->dev,
8133                                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8134                                         max_tx_rate,
8135                                         credits,
8136                                         vsi->seid);
8137                         } else {
8138                                 need_reset = true;
8139                                 goto exit;
8140                         }
8141                 }
8142                 ret = i40e_configure_queue_channels(vsi);
8143                 if (ret) {
8144                         vsi->num_queue_pairs = old_queue_pairs;
8145                         netdev_info(netdev,
8146                                     "Failed configuring queue channels\n");
8147                         need_reset = true;
8148                         goto exit;
8149                 }
8150         }
8151
8152 exit:
8153         /* Reset the configuration data to defaults, only TC0 is enabled */
8154         if (need_reset) {
8155                 i40e_vsi_set_default_tc_config(vsi);
8156                 need_reset = false;
8157         }
8158
8159         /* Unquiesce VSI */
8160         i40e_unquiesce_vsi(vsi);
8161         return ret;
8162 }
8163
8164 /**
8165  * i40e_set_cld_element - sets cloud filter element data
8166  * @filter: cloud filter rule
8167  * @cld: ptr to cloud filter element data
8168  *
8169  * This is helper function to copy data into cloud filter element
8170  **/
8171 static inline void
8172 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8173                      struct i40e_aqc_cloud_filters_element_data *cld)
8174 {
8175         u32 ipa;
8176         int i;
8177
8178         memset(cld, 0, sizeof(*cld));
8179         ether_addr_copy(cld->outer_mac, filter->dst_mac);
8180         ether_addr_copy(cld->inner_mac, filter->src_mac);
8181
8182         if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8183                 return;
8184
8185         if (filter->n_proto == ETH_P_IPV6) {
8186 #define IPV6_MAX_INDEX  (ARRAY_SIZE(filter->dst_ipv6) - 1)
8187                 for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8188                         ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8189
8190                         *(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8191                 }
8192         } else {
8193                 ipa = be32_to_cpu(filter->dst_ipv4);
8194
8195                 memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8196         }
8197
8198         cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8199
8200         /* tenant_id is not supported by FW now, once the support is enabled
8201          * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8202          */
8203         if (filter->tenant_id)
8204                 return;
8205 }
8206
8207 /**
8208  * i40e_add_del_cloud_filter - Add/del cloud filter
8209  * @vsi: pointer to VSI
8210  * @filter: cloud filter rule
8211  * @add: if true, add, if false, delete
8212  *
8213  * Add or delete a cloud filter for a specific flow spec.
8214  * Returns 0 if the filter were successfully added.
8215  **/
8216 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8217                               struct i40e_cloud_filter *filter, bool add)
8218 {
8219         struct i40e_aqc_cloud_filters_element_data cld_filter;
8220         struct i40e_pf *pf = vsi->back;
8221         int ret;
8222         static const u16 flag_table[128] = {
8223                 [I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8224                         I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8225                 [I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8226                         I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8227                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8228                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8229                 [I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8230                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8231                 [I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8232                         I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8233                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8234                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8235                 [I40E_CLOUD_FILTER_FLAGS_IIP] =
8236                         I40E_AQC_ADD_CLOUD_FILTER_IIP,
8237         };
8238
8239         if (filter->flags >= ARRAY_SIZE(flag_table))
8240                 return I40E_ERR_CONFIG;
8241
8242         memset(&cld_filter, 0, sizeof(cld_filter));
8243
8244         /* copy element needed to add cloud filter from filter */
8245         i40e_set_cld_element(filter, &cld_filter);
8246
8247         if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8248                 cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8249                                              I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8250
8251         if (filter->n_proto == ETH_P_IPV6)
8252                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8253                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8254         else
8255                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8256                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8257
8258         if (add)
8259                 ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8260                                                 &cld_filter, 1);
8261         else
8262                 ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8263                                                 &cld_filter, 1);
8264         if (ret)
8265                 dev_dbg(&pf->pdev->dev,
8266                         "Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8267                         add ? "add" : "delete", filter->dst_port, ret,
8268                         pf->hw.aq.asq_last_status);
8269         else
8270                 dev_info(&pf->pdev->dev,
8271                          "%s cloud filter for VSI: %d\n",
8272                          add ? "Added" : "Deleted", filter->seid);
8273         return ret;
8274 }
8275
8276 /**
8277  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8278  * @vsi: pointer to VSI
8279  * @filter: cloud filter rule
8280  * @add: if true, add, if false, delete
8281  *
8282  * Add or delete a cloud filter for a specific flow spec using big buffer.
8283  * Returns 0 if the filter were successfully added.
8284  **/
8285 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8286                                       struct i40e_cloud_filter *filter,
8287                                       bool add)
8288 {
8289         struct i40e_aqc_cloud_filters_element_bb cld_filter;
8290         struct i40e_pf *pf = vsi->back;
8291         int ret;
8292
8293         /* Both (src/dst) valid mac_addr are not supported */
8294         if ((is_valid_ether_addr(filter->dst_mac) &&
8295              is_valid_ether_addr(filter->src_mac)) ||
8296             (is_multicast_ether_addr(filter->dst_mac) &&
8297              is_multicast_ether_addr(filter->src_mac)))
8298                 return -EOPNOTSUPP;
8299
8300         /* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8301          * ports are not supported via big buffer now.
8302          */
8303         if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8304                 return -EOPNOTSUPP;
8305
8306         /* adding filter using src_port/src_ip is not supported at this stage */
8307         if (filter->src_port ||
8308             (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8309             !ipv6_addr_any(&filter->ip.v6.src_ip6))
8310                 return -EOPNOTSUPP;
8311
8312         memset(&cld_filter, 0, sizeof(cld_filter));
8313
8314         /* copy element needed to add cloud filter from filter */
8315         i40e_set_cld_element(filter, &cld_filter.element);
8316
8317         if (is_valid_ether_addr(filter->dst_mac) ||
8318             is_valid_ether_addr(filter->src_mac) ||
8319             is_multicast_ether_addr(filter->dst_mac) ||
8320             is_multicast_ether_addr(filter->src_mac)) {
8321                 /* MAC + IP : unsupported mode */
8322                 if (filter->dst_ipv4)
8323                         return -EOPNOTSUPP;
8324
8325                 /* since we validated that L4 port must be valid before
8326                  * we get here, start with respective "flags" value
8327                  * and update if vlan is present or not
8328                  */
8329                 cld_filter.element.flags =
8330                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8331
8332                 if (filter->vlan_id) {
8333                         cld_filter.element.flags =
8334                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8335                 }
8336
8337         } else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8338                    !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8339                 cld_filter.element.flags =
8340                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8341                 if (filter->n_proto == ETH_P_IPV6)
8342                         cld_filter.element.flags |=
8343                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8344                 else
8345                         cld_filter.element.flags |=
8346                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8347         } else {
8348                 dev_err(&pf->pdev->dev,
8349                         "either mac or ip has to be valid for cloud filter\n");
8350                 return -EINVAL;
8351         }
8352
8353         /* Now copy L4 port in Byte 6..7 in general fields */
8354         cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8355                                                 be16_to_cpu(filter->dst_port);
8356
8357         if (add) {
8358                 /* Validate current device switch mode, change if necessary */
8359                 ret = i40e_validate_and_set_switch_mode(vsi);
8360                 if (ret) {
8361                         dev_err(&pf->pdev->dev,
8362                                 "failed to set switch mode, ret %d\n",
8363                                 ret);
8364                         return ret;
8365                 }
8366
8367                 ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8368                                                    &cld_filter, 1);
8369         } else {
8370                 ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8371                                                    &cld_filter, 1);
8372         }
8373
8374         if (ret)
8375                 dev_dbg(&pf->pdev->dev,
8376                         "Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8377                         add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8378         else
8379                 dev_info(&pf->pdev->dev,
8380                          "%s cloud filter for VSI: %d, L4 port: %d\n",
8381                          add ? "add" : "delete", filter->seid,
8382                          ntohs(filter->dst_port));
8383         return ret;
8384 }
8385
8386 /**
8387  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8388  * @vsi: Pointer to VSI
8389  * @f: Pointer to struct flow_cls_offload
8390  * @filter: Pointer to cloud filter structure
8391  *
8392  **/
8393 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8394                                  struct flow_cls_offload *f,
8395                                  struct i40e_cloud_filter *filter)
8396 {
8397         struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8398         struct flow_dissector *dissector = rule->match.dissector;
8399         u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8400         struct i40e_pf *pf = vsi->back;
8401         u8 field_flags = 0;
8402
8403         if (dissector->used_keys &
8404             ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
8405               BIT(FLOW_DISSECTOR_KEY_BASIC) |
8406               BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8407               BIT(FLOW_DISSECTOR_KEY_VLAN) |
8408               BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8409               BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8410               BIT(FLOW_DISSECTOR_KEY_PORTS) |
8411               BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8412                 dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
8413                         dissector->used_keys);
8414                 return -EOPNOTSUPP;
8415         }
8416
8417         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8418                 struct flow_match_enc_keyid match;
8419
8420                 flow_rule_match_enc_keyid(rule, &match);
8421                 if (match.mask->keyid != 0)
8422                         field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8423
8424                 filter->tenant_id = be32_to_cpu(match.key->keyid);
8425         }
8426
8427         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8428                 struct flow_match_basic match;
8429
8430                 flow_rule_match_basic(rule, &match);
8431                 n_proto_key = ntohs(match.key->n_proto);
8432                 n_proto_mask = ntohs(match.mask->n_proto);
8433
8434                 if (n_proto_key == ETH_P_ALL) {
8435                         n_proto_key = 0;
8436                         n_proto_mask = 0;
8437                 }
8438                 filter->n_proto = n_proto_key & n_proto_mask;
8439                 filter->ip_proto = match.key->ip_proto;
8440         }
8441
8442         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8443                 struct flow_match_eth_addrs match;
8444
8445                 flow_rule_match_eth_addrs(rule, &match);
8446
8447                 /* use is_broadcast and is_zero to check for all 0xf or 0 */
8448                 if (!is_zero_ether_addr(match.mask->dst)) {
8449                         if (is_broadcast_ether_addr(match.mask->dst)) {
8450                                 field_flags |= I40E_CLOUD_FIELD_OMAC;
8451                         } else {
8452                                 dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8453                                         match.mask->dst);
8454                                 return I40E_ERR_CONFIG;
8455                         }
8456                 }
8457
8458                 if (!is_zero_ether_addr(match.mask->src)) {
8459                         if (is_broadcast_ether_addr(match.mask->src)) {
8460                                 field_flags |= I40E_CLOUD_FIELD_IMAC;
8461                         } else {
8462                                 dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8463                                         match.mask->src);
8464                                 return I40E_ERR_CONFIG;
8465                         }
8466                 }
8467                 ether_addr_copy(filter->dst_mac, match.key->dst);
8468                 ether_addr_copy(filter->src_mac, match.key->src);
8469         }
8470
8471         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8472                 struct flow_match_vlan match;
8473
8474                 flow_rule_match_vlan(rule, &match);
8475                 if (match.mask->vlan_id) {
8476                         if (match.mask->vlan_id == VLAN_VID_MASK) {
8477                                 field_flags |= I40E_CLOUD_FIELD_IVLAN;
8478
8479                         } else {
8480                                 dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8481                                         match.mask->vlan_id);
8482                                 return I40E_ERR_CONFIG;
8483                         }
8484                 }
8485
8486                 filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8487         }
8488
8489         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8490                 struct flow_match_control match;
8491
8492                 flow_rule_match_control(rule, &match);
8493                 addr_type = match.key->addr_type;
8494         }
8495
8496         if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8497                 struct flow_match_ipv4_addrs match;
8498
8499                 flow_rule_match_ipv4_addrs(rule, &match);
8500                 if (match.mask->dst) {
8501                         if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8502                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8503                         } else {
8504                                 dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8505                                         &match.mask->dst);
8506                                 return I40E_ERR_CONFIG;
8507                         }
8508                 }
8509
8510                 if (match.mask->src) {
8511                         if (match.mask->src == cpu_to_be32(0xffffffff)) {
8512                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8513                         } else {
8514                                 dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8515                                         &match.mask->src);
8516                                 return I40E_ERR_CONFIG;
8517                         }
8518                 }
8519
8520                 if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8521                         dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8522                         return I40E_ERR_CONFIG;
8523                 }
8524                 filter->dst_ipv4 = match.key->dst;
8525                 filter->src_ipv4 = match.key->src;
8526         }
8527
8528         if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8529                 struct flow_match_ipv6_addrs match;
8530
8531                 flow_rule_match_ipv6_addrs(rule, &match);
8532
8533                 /* src and dest IPV6 address should not be LOOPBACK
8534                  * (0:0:0:0:0:0:0:1), which can be represented as ::1
8535                  */
8536                 if (ipv6_addr_loopback(&match.key->dst) ||
8537                     ipv6_addr_loopback(&match.key->src)) {
8538                         dev_err(&pf->pdev->dev,
8539                                 "Bad ipv6, addr is LOOPBACK\n");
8540                         return I40E_ERR_CONFIG;
8541                 }
8542                 if (!ipv6_addr_any(&match.mask->dst) ||
8543                     !ipv6_addr_any(&match.mask->src))
8544                         field_flags |= I40E_CLOUD_FIELD_IIP;
8545
8546                 memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8547                        sizeof(filter->src_ipv6));
8548                 memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8549                        sizeof(filter->dst_ipv6));
8550         }
8551
8552         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8553                 struct flow_match_ports match;
8554
8555                 flow_rule_match_ports(rule, &match);
8556                 if (match.mask->src) {
8557                         if (match.mask->src == cpu_to_be16(0xffff)) {
8558                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8559                         } else {
8560                                 dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8561                                         be16_to_cpu(match.mask->src));
8562                                 return I40E_ERR_CONFIG;
8563                         }
8564                 }
8565
8566                 if (match.mask->dst) {
8567                         if (match.mask->dst == cpu_to_be16(0xffff)) {
8568                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8569                         } else {
8570                                 dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8571                                         be16_to_cpu(match.mask->dst));
8572                                 return I40E_ERR_CONFIG;
8573                         }
8574                 }
8575
8576                 filter->dst_port = match.key->dst;
8577                 filter->src_port = match.key->src;
8578
8579                 switch (filter->ip_proto) {
8580                 case IPPROTO_TCP:
8581                 case IPPROTO_UDP:
8582                         break;
8583                 default:
8584                         dev_err(&pf->pdev->dev,
8585                                 "Only UDP and TCP transport are supported\n");
8586                         return -EINVAL;
8587                 }
8588         }
8589         filter->flags = field_flags;
8590         return 0;
8591 }
8592
8593 /**
8594  * i40e_handle_tclass: Forward to a traffic class on the device
8595  * @vsi: Pointer to VSI
8596  * @tc: traffic class index on the device
8597  * @filter: Pointer to cloud filter structure
8598  *
8599  **/
8600 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8601                               struct i40e_cloud_filter *filter)
8602 {
8603         struct i40e_channel *ch, *ch_tmp;
8604
8605         /* direct to a traffic class on the same device */
8606         if (tc == 0) {
8607                 filter->seid = vsi->seid;
8608                 return 0;
8609         } else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8610                 if (!filter->dst_port) {
8611                         dev_err(&vsi->back->pdev->dev,
8612                                 "Specify destination port to direct to traffic class that is not default\n");
8613                         return -EINVAL;
8614                 }
8615                 if (list_empty(&vsi->ch_list))
8616                         return -EINVAL;
8617                 list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8618                                          list) {
8619                         if (ch->seid == vsi->tc_seid_map[tc])
8620                                 filter->seid = ch->seid;
8621                 }
8622                 return 0;
8623         }
8624         dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8625         return -EINVAL;
8626 }
8627
8628 /**
8629  * i40e_configure_clsflower - Configure tc flower filters
8630  * @vsi: Pointer to VSI
8631  * @cls_flower: Pointer to struct flow_cls_offload
8632  *
8633  **/
8634 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8635                                     struct flow_cls_offload *cls_flower)
8636 {
8637         int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8638         struct i40e_cloud_filter *filter = NULL;
8639         struct i40e_pf *pf = vsi->back;
8640         int err = 0;
8641
8642         if (tc < 0) {
8643                 dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8644                 return -EOPNOTSUPP;
8645         }
8646
8647         if (!tc) {
8648                 dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8649                 return -EINVAL;
8650         }
8651
8652         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8653             test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8654                 return -EBUSY;
8655
8656         if (pf->fdir_pf_active_filters ||
8657             (!hlist_empty(&pf->fdir_filter_list))) {
8658                 dev_err(&vsi->back->pdev->dev,
8659                         "Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8660                 return -EINVAL;
8661         }
8662
8663         if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8664                 dev_err(&vsi->back->pdev->dev,
8665                         "Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8666                 vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8667                 vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8668         }
8669
8670         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8671         if (!filter)
8672                 return -ENOMEM;
8673
8674         filter->cookie = cls_flower->cookie;
8675
8676         err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8677         if (err < 0)
8678                 goto err;
8679
8680         err = i40e_handle_tclass(vsi, tc, filter);
8681         if (err < 0)
8682                 goto err;
8683
8684         /* Add cloud filter */
8685         if (filter->dst_port)
8686                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8687         else
8688                 err = i40e_add_del_cloud_filter(vsi, filter, true);
8689
8690         if (err) {
8691                 dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8692                         err);
8693                 goto err;
8694         }
8695
8696         /* add filter to the ordered list */
8697         INIT_HLIST_NODE(&filter->cloud_node);
8698
8699         hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8700
8701         pf->num_cloud_filters++;
8702
8703         return err;
8704 err:
8705         kfree(filter);
8706         return err;
8707 }
8708
8709 /**
8710  * i40e_find_cloud_filter - Find the could filter in the list
8711  * @vsi: Pointer to VSI
8712  * @cookie: filter specific cookie
8713  *
8714  **/
8715 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8716                                                         unsigned long *cookie)
8717 {
8718         struct i40e_cloud_filter *filter = NULL;
8719         struct hlist_node *node2;
8720
8721         hlist_for_each_entry_safe(filter, node2,
8722                                   &vsi->back->cloud_filter_list, cloud_node)
8723                 if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8724                         return filter;
8725         return NULL;
8726 }
8727
8728 /**
8729  * i40e_delete_clsflower - Remove tc flower filters
8730  * @vsi: Pointer to VSI
8731  * @cls_flower: Pointer to struct flow_cls_offload
8732  *
8733  **/
8734 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8735                                  struct flow_cls_offload *cls_flower)
8736 {
8737         struct i40e_cloud_filter *filter = NULL;
8738         struct i40e_pf *pf = vsi->back;
8739         int err = 0;
8740
8741         filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8742
8743         if (!filter)
8744                 return -EINVAL;
8745
8746         hash_del(&filter->cloud_node);
8747
8748         if (filter->dst_port)
8749                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8750         else
8751                 err = i40e_add_del_cloud_filter(vsi, filter, false);
8752
8753         kfree(filter);
8754         if (err) {
8755                 dev_err(&pf->pdev->dev,
8756                         "Failed to delete cloud filter, err %s\n",
8757                         i40e_stat_str(&pf->hw, err));
8758                 return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8759         }
8760
8761         pf->num_cloud_filters--;
8762         if (!pf->num_cloud_filters)
8763                 if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8764                     !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8765                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8766                         pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8767                         pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8768                 }
8769         return 0;
8770 }
8771
8772 /**
8773  * i40e_setup_tc_cls_flower - flower classifier offloads
8774  * @np: net device to configure
8775  * @cls_flower: offload data
8776  **/
8777 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8778                                     struct flow_cls_offload *cls_flower)
8779 {
8780         struct i40e_vsi *vsi = np->vsi;
8781
8782         switch (cls_flower->command) {
8783         case FLOW_CLS_REPLACE:
8784                 return i40e_configure_clsflower(vsi, cls_flower);
8785         case FLOW_CLS_DESTROY:
8786                 return i40e_delete_clsflower(vsi, cls_flower);
8787         case FLOW_CLS_STATS:
8788                 return -EOPNOTSUPP;
8789         default:
8790                 return -EOPNOTSUPP;
8791         }
8792 }
8793
8794 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8795                                   void *cb_priv)
8796 {
8797         struct i40e_netdev_priv *np = cb_priv;
8798
8799         if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8800                 return -EOPNOTSUPP;
8801
8802         switch (type) {
8803         case TC_SETUP_CLSFLOWER:
8804                 return i40e_setup_tc_cls_flower(np, type_data);
8805
8806         default:
8807                 return -EOPNOTSUPP;
8808         }
8809 }
8810
8811 static LIST_HEAD(i40e_block_cb_list);
8812
8813 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8814                            void *type_data)
8815 {
8816         struct i40e_netdev_priv *np = netdev_priv(netdev);
8817
8818         switch (type) {
8819         case TC_SETUP_QDISC_MQPRIO:
8820                 return i40e_setup_tc(netdev, type_data);
8821         case TC_SETUP_BLOCK:
8822                 return flow_block_cb_setup_simple(type_data,
8823                                                   &i40e_block_cb_list,
8824                                                   i40e_setup_tc_block_cb,
8825                                                   np, np, true);
8826         default:
8827                 return -EOPNOTSUPP;
8828         }
8829 }
8830
8831 /**
8832  * i40e_open - Called when a network interface is made active
8833  * @netdev: network interface device structure
8834  *
8835  * The open entry point is called when a network interface is made
8836  * active by the system (IFF_UP).  At this point all resources needed
8837  * for transmit and receive operations are allocated, the interrupt
8838  * handler is registered with the OS, the netdev watchdog subtask is
8839  * enabled, and the stack is notified that the interface is ready.
8840  *
8841  * Returns 0 on success, negative value on failure
8842  **/
8843 int i40e_open(struct net_device *netdev)
8844 {
8845         struct i40e_netdev_priv *np = netdev_priv(netdev);
8846         struct i40e_vsi *vsi = np->vsi;
8847         struct i40e_pf *pf = vsi->back;
8848         int err;
8849
8850         /* disallow open during test or if eeprom is broken */
8851         if (test_bit(__I40E_TESTING, pf->state) ||
8852             test_bit(__I40E_BAD_EEPROM, pf->state))
8853                 return -EBUSY;
8854
8855         netif_carrier_off(netdev);
8856
8857         if (i40e_force_link_state(pf, true))
8858                 return -EAGAIN;
8859
8860         err = i40e_vsi_open(vsi);
8861         if (err)
8862                 return err;
8863
8864         /* configure global TSO hardware offload settings */
8865         wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8866                                                        TCP_FLAG_FIN) >> 16);
8867         wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8868                                                        TCP_FLAG_FIN |
8869                                                        TCP_FLAG_CWR) >> 16);
8870         wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8871         udp_tunnel_get_rx_info(netdev);
8872
8873         return 0;
8874 }
8875
8876 /**
8877  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
8878  * @vsi: vsi structure
8879  *
8880  * This updates netdev's number of tx/rx queues
8881  *
8882  * Returns status of setting tx/rx queues
8883  **/
8884 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
8885 {
8886         int ret;
8887
8888         ret = netif_set_real_num_rx_queues(vsi->netdev,
8889                                            vsi->num_queue_pairs);
8890         if (ret)
8891                 return ret;
8892
8893         return netif_set_real_num_tx_queues(vsi->netdev,
8894                                             vsi->num_queue_pairs);
8895 }
8896
8897 /**
8898  * i40e_vsi_open -
8899  * @vsi: the VSI to open
8900  *
8901  * Finish initialization of the VSI.
8902  *
8903  * Returns 0 on success, negative value on failure
8904  *
8905  * Note: expects to be called while under rtnl_lock()
8906  **/
8907 int i40e_vsi_open(struct i40e_vsi *vsi)
8908 {
8909         struct i40e_pf *pf = vsi->back;
8910         char int_name[I40E_INT_NAME_STR_LEN];
8911         int err;
8912
8913         /* allocate descriptors */
8914         err = i40e_vsi_setup_tx_resources(vsi);
8915         if (err)
8916                 goto err_setup_tx;
8917         err = i40e_vsi_setup_rx_resources(vsi);
8918         if (err)
8919                 goto err_setup_rx;
8920
8921         err = i40e_vsi_configure(vsi);
8922         if (err)
8923                 goto err_setup_rx;
8924
8925         if (vsi->netdev) {
8926                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
8927                          dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
8928                 err = i40e_vsi_request_irq(vsi, int_name);
8929                 if (err)
8930                         goto err_setup_rx;
8931
8932                 /* Notify the stack of the actual queue counts. */
8933                 err = i40e_netif_set_realnum_tx_rx_queues(vsi);
8934                 if (err)
8935                         goto err_set_queues;
8936
8937         } else if (vsi->type == I40E_VSI_FDIR) {
8938                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
8939                          dev_driver_string(&pf->pdev->dev),
8940                          dev_name(&pf->pdev->dev));
8941                 err = i40e_vsi_request_irq(vsi, int_name);
8942                 if (err)
8943                         goto err_setup_rx;
8944
8945         } else {
8946                 err = -EINVAL;
8947                 goto err_setup_rx;
8948         }
8949
8950         err = i40e_up_complete(vsi);
8951         if (err)
8952                 goto err_up_complete;
8953
8954         return 0;
8955
8956 err_up_complete:
8957         i40e_down(vsi);
8958 err_set_queues:
8959         i40e_vsi_free_irq(vsi);
8960 err_setup_rx:
8961         i40e_vsi_free_rx_resources(vsi);
8962 err_setup_tx:
8963         i40e_vsi_free_tx_resources(vsi);
8964         if (vsi == pf->vsi[pf->lan_vsi])
8965                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
8966
8967         return err;
8968 }
8969
8970 /**
8971  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
8972  * @pf: Pointer to PF
8973  *
8974  * This function destroys the hlist where all the Flow Director
8975  * filters were saved.
8976  **/
8977 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
8978 {
8979         struct i40e_fdir_filter *filter;
8980         struct i40e_flex_pit *pit_entry, *tmp;
8981         struct hlist_node *node2;
8982
8983         hlist_for_each_entry_safe(filter, node2,
8984                                   &pf->fdir_filter_list, fdir_node) {
8985                 hlist_del(&filter->fdir_node);
8986                 kfree(filter);
8987         }
8988
8989         list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
8990                 list_del(&pit_entry->list);
8991                 kfree(pit_entry);
8992         }
8993         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
8994
8995         list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
8996                 list_del(&pit_entry->list);
8997                 kfree(pit_entry);
8998         }
8999         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9000
9001         pf->fdir_pf_active_filters = 0;
9002         i40e_reset_fdir_filter_cnt(pf);
9003
9004         /* Reprogram the default input set for TCP/IPv4 */
9005         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9006                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9007                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9008
9009         /* Reprogram the default input set for TCP/IPv6 */
9010         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
9011                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9012                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9013
9014         /* Reprogram the default input set for UDP/IPv4 */
9015         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
9016                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9017                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9018
9019         /* Reprogram the default input set for UDP/IPv6 */
9020         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9021                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9022                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9023
9024         /* Reprogram the default input set for SCTP/IPv4 */
9025         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9026                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9027                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9028
9029         /* Reprogram the default input set for SCTP/IPv6 */
9030         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9031                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9032                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9033
9034         /* Reprogram the default input set for Other/IPv4 */
9035         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9036                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9037
9038         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9039                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9040
9041         /* Reprogram the default input set for Other/IPv6 */
9042         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9043                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9044
9045         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9046                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9047 }
9048
9049 /**
9050  * i40e_cloud_filter_exit - Cleans up the cloud filters
9051  * @pf: Pointer to PF
9052  *
9053  * This function destroys the hlist where all the cloud filters
9054  * were saved.
9055  **/
9056 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9057 {
9058         struct i40e_cloud_filter *cfilter;
9059         struct hlist_node *node;
9060
9061         hlist_for_each_entry_safe(cfilter, node,
9062                                   &pf->cloud_filter_list, cloud_node) {
9063                 hlist_del(&cfilter->cloud_node);
9064                 kfree(cfilter);
9065         }
9066         pf->num_cloud_filters = 0;
9067
9068         if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
9069             !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
9070                 pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9071                 pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
9072                 pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
9073         }
9074 }
9075
9076 /**
9077  * i40e_close - Disables a network interface
9078  * @netdev: network interface device structure
9079  *
9080  * The close entry point is called when an interface is de-activated
9081  * by the OS.  The hardware is still under the driver's control, but
9082  * this netdev interface is disabled.
9083  *
9084  * Returns 0, this is not allowed to fail
9085  **/
9086 int i40e_close(struct net_device *netdev)
9087 {
9088         struct i40e_netdev_priv *np = netdev_priv(netdev);
9089         struct i40e_vsi *vsi = np->vsi;
9090
9091         i40e_vsi_close(vsi);
9092
9093         return 0;
9094 }
9095
9096 /**
9097  * i40e_do_reset - Start a PF or Core Reset sequence
9098  * @pf: board private structure
9099  * @reset_flags: which reset is requested
9100  * @lock_acquired: indicates whether or not the lock has been acquired
9101  * before this function was called.
9102  *
9103  * The essential difference in resets is that the PF Reset
9104  * doesn't clear the packet buffers, doesn't reset the PE
9105  * firmware, and doesn't bother the other PFs on the chip.
9106  **/
9107 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9108 {
9109         u32 val;
9110
9111         /* do the biggest reset indicated */
9112         if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9113
9114                 /* Request a Global Reset
9115                  *
9116                  * This will start the chip's countdown to the actual full
9117                  * chip reset event, and a warning interrupt to be sent
9118                  * to all PFs, including the requestor.  Our handler
9119                  * for the warning interrupt will deal with the shutdown
9120                  * and recovery of the switch setup.
9121                  */
9122                 dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9123                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9124                 val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9125                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9126
9127         } else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9128
9129                 /* Request a Core Reset
9130                  *
9131                  * Same as Global Reset, except does *not* include the MAC/PHY
9132                  */
9133                 dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9134                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9135                 val |= I40E_GLGEN_RTRIG_CORER_MASK;
9136                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9137                 i40e_flush(&pf->hw);
9138
9139         } else if (reset_flags & I40E_PF_RESET_FLAG) {
9140
9141                 /* Request a PF Reset
9142                  *
9143                  * Resets only the PF-specific registers
9144                  *
9145                  * This goes directly to the tear-down and rebuild of
9146                  * the switch, since we need to do all the recovery as
9147                  * for the Core Reset.
9148                  */
9149                 dev_dbg(&pf->pdev->dev, "PFR requested\n");
9150                 i40e_handle_reset_warning(pf, lock_acquired);
9151
9152         } else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9153                 /* Request a PF Reset
9154                  *
9155                  * Resets PF and reinitializes PFs VSI.
9156                  */
9157                 i40e_prep_for_reset(pf);
9158                 i40e_reset_and_rebuild(pf, true, lock_acquired);
9159                 dev_info(&pf->pdev->dev,
9160                          pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
9161                          "FW LLDP is disabled\n" :
9162                          "FW LLDP is enabled\n");
9163
9164         } else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9165                 int v;
9166
9167                 /* Find the VSI(s) that requested a re-init */
9168                 dev_info(&pf->pdev->dev,
9169                          "VSI reinit requested\n");
9170                 for (v = 0; v < pf->num_alloc_vsi; v++) {
9171                         struct i40e_vsi *vsi = pf->vsi[v];
9172
9173                         if (vsi != NULL &&
9174                             test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9175                                                vsi->state))
9176                                 i40e_vsi_reinit_locked(pf->vsi[v]);
9177                 }
9178         } else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9179                 int v;
9180
9181                 /* Find the VSI(s) that needs to be brought down */
9182                 dev_info(&pf->pdev->dev, "VSI down requested\n");
9183                 for (v = 0; v < pf->num_alloc_vsi; v++) {
9184                         struct i40e_vsi *vsi = pf->vsi[v];
9185
9186                         if (vsi != NULL &&
9187                             test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9188                                                vsi->state)) {
9189                                 set_bit(__I40E_VSI_DOWN, vsi->state);
9190                                 i40e_down(vsi);
9191                         }
9192                 }
9193         } else {
9194                 dev_info(&pf->pdev->dev,
9195                          "bad reset request 0x%08x\n", reset_flags);
9196         }
9197 }
9198
9199 #ifdef CONFIG_I40E_DCB
9200 /**
9201  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9202  * @pf: board private structure
9203  * @old_cfg: current DCB config
9204  * @new_cfg: new DCB config
9205  **/
9206 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9207                             struct i40e_dcbx_config *old_cfg,
9208                             struct i40e_dcbx_config *new_cfg)
9209 {
9210         bool need_reconfig = false;
9211
9212         /* Check if ETS configuration has changed */
9213         if (memcmp(&new_cfg->etscfg,
9214                    &old_cfg->etscfg,
9215                    sizeof(new_cfg->etscfg))) {
9216                 /* If Priority Table has changed reconfig is needed */
9217                 if (memcmp(&new_cfg->etscfg.prioritytable,
9218                            &old_cfg->etscfg.prioritytable,
9219                            sizeof(new_cfg->etscfg.prioritytable))) {
9220                         need_reconfig = true;
9221                         dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9222                 }
9223
9224                 if (memcmp(&new_cfg->etscfg.tcbwtable,
9225                            &old_cfg->etscfg.tcbwtable,
9226                            sizeof(new_cfg->etscfg.tcbwtable)))
9227                         dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9228
9229                 if (memcmp(&new_cfg->etscfg.tsatable,
9230                            &old_cfg->etscfg.tsatable,
9231                            sizeof(new_cfg->etscfg.tsatable)))
9232                         dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9233         }
9234
9235         /* Check if PFC configuration has changed */
9236         if (memcmp(&new_cfg->pfc,
9237                    &old_cfg->pfc,
9238                    sizeof(new_cfg->pfc))) {
9239                 need_reconfig = true;
9240                 dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9241         }
9242
9243         /* Check if APP Table has changed */
9244         if (memcmp(&new_cfg->app,
9245                    &old_cfg->app,
9246                    sizeof(new_cfg->app))) {
9247                 need_reconfig = true;
9248                 dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9249         }
9250
9251         dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9252         return need_reconfig;
9253 }
9254
9255 /**
9256  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9257  * @pf: board private structure
9258  * @e: event info posted on ARQ
9259  **/
9260 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9261                                   struct i40e_arq_event_info *e)
9262 {
9263         struct i40e_aqc_lldp_get_mib *mib =
9264                 (struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9265         struct i40e_hw *hw = &pf->hw;
9266         struct i40e_dcbx_config tmp_dcbx_cfg;
9267         bool need_reconfig = false;
9268         int ret = 0;
9269         u8 type;
9270
9271         /* X710-T*L 2.5G and 5G speeds don't support DCB */
9272         if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9273             (hw->phy.link_info.link_speed &
9274              ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9275              !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9276                 /* let firmware decide if the DCB should be disabled */
9277                 pf->flags |= I40E_FLAG_DCB_CAPABLE;
9278
9279         /* Not DCB capable or capability disabled */
9280         if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9281                 return ret;
9282
9283         /* Ignore if event is not for Nearest Bridge */
9284         type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9285                 & I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9286         dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9287         if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9288                 return ret;
9289
9290         /* Check MIB Type and return if event for Remote MIB update */
9291         type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9292         dev_dbg(&pf->pdev->dev,
9293                 "LLDP event mib type %s\n", type ? "remote" : "local");
9294         if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9295                 /* Update the remote cached instance and return */
9296                 ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9297                                 I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9298                                 &hw->remote_dcbx_config);
9299                 goto exit;
9300         }
9301
9302         /* Store the old configuration */
9303         tmp_dcbx_cfg = hw->local_dcbx_config;
9304
9305         /* Reset the old DCBx configuration data */
9306         memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9307         /* Get updated DCBX data from firmware */
9308         ret = i40e_get_dcb_config(&pf->hw);
9309         if (ret) {
9310                 /* X710-T*L 2.5G and 5G speeds don't support DCB */
9311                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9312                     (hw->phy.link_info.link_speed &
9313                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9314                         dev_warn(&pf->pdev->dev,
9315                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9316                         pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9317                 } else {
9318                         dev_info(&pf->pdev->dev,
9319                                  "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
9320                                  i40e_stat_str(&pf->hw, ret),
9321                                  i40e_aq_str(&pf->hw,
9322                                              pf->hw.aq.asq_last_status));
9323                 }
9324                 goto exit;
9325         }
9326
9327         /* No change detected in DCBX configs */
9328         if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9329                     sizeof(tmp_dcbx_cfg))) {
9330                 dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9331                 goto exit;
9332         }
9333
9334         need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9335                                                &hw->local_dcbx_config);
9336
9337         i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9338
9339         if (!need_reconfig)
9340                 goto exit;
9341
9342         /* Enable DCB tagging only when more than one TC */
9343         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9344                 pf->flags |= I40E_FLAG_DCB_ENABLED;
9345         else
9346                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9347
9348         set_bit(__I40E_PORT_SUSPENDED, pf->state);
9349         /* Reconfiguration needed quiesce all VSIs */
9350         i40e_pf_quiesce_all_vsi(pf);
9351
9352         /* Changes in configuration update VEB/VSI */
9353         i40e_dcb_reconfigure(pf);
9354
9355         ret = i40e_resume_port_tx(pf);
9356
9357         clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9358         /* In case of error no point in resuming VSIs */
9359         if (ret)
9360                 goto exit;
9361
9362         /* Wait for the PF's queues to be disabled */
9363         ret = i40e_pf_wait_queues_disabled(pf);
9364         if (ret) {
9365                 /* Schedule PF reset to recover */
9366                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9367                 i40e_service_event_schedule(pf);
9368         } else {
9369                 i40e_pf_unquiesce_all_vsi(pf);
9370                 set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9371                 set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9372         }
9373
9374 exit:
9375         return ret;
9376 }
9377 #endif /* CONFIG_I40E_DCB */
9378
9379 /**
9380  * i40e_do_reset_safe - Protected reset path for userland calls.
9381  * @pf: board private structure
9382  * @reset_flags: which reset is requested
9383  *
9384  **/
9385 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9386 {
9387         rtnl_lock();
9388         i40e_do_reset(pf, reset_flags, true);
9389         rtnl_unlock();
9390 }
9391
9392 /**
9393  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9394  * @pf: board private structure
9395  * @e: event info posted on ARQ
9396  *
9397  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9398  * and VF queues
9399  **/
9400 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9401                                            struct i40e_arq_event_info *e)
9402 {
9403         struct i40e_aqc_lan_overflow *data =
9404                 (struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9405         u32 queue = le32_to_cpu(data->prtdcb_rupto);
9406         u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9407         struct i40e_hw *hw = &pf->hw;
9408         struct i40e_vf *vf;
9409         u16 vf_id;
9410
9411         dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9412                 queue, qtx_ctl);
9413
9414         /* Queue belongs to VF, find the VF and issue VF reset */
9415         if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9416             >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9417                 vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9418                          >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9419                 vf_id -= hw->func_caps.vf_base_id;
9420                 vf = &pf->vf[vf_id];
9421                 i40e_vc_notify_vf_reset(vf);
9422                 /* Allow VF to process pending reset notification */
9423                 msleep(20);
9424                 i40e_reset_vf(vf, false);
9425         }
9426 }
9427
9428 /**
9429  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9430  * @pf: board private structure
9431  **/
9432 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9433 {
9434         u32 val, fcnt_prog;
9435
9436         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9437         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9438         return fcnt_prog;
9439 }
9440
9441 /**
9442  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9443  * @pf: board private structure
9444  **/
9445 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9446 {
9447         u32 val, fcnt_prog;
9448
9449         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9450         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9451                     ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9452                       I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9453         return fcnt_prog;
9454 }
9455
9456 /**
9457  * i40e_get_global_fd_count - Get total FD filters programmed on device
9458  * @pf: board private structure
9459  **/
9460 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9461 {
9462         u32 val, fcnt_prog;
9463
9464         val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9465         fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9466                     ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9467                      I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9468         return fcnt_prog;
9469 }
9470
9471 /**
9472  * i40e_reenable_fdir_sb - Restore FDir SB capability
9473  * @pf: board private structure
9474  **/
9475 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9476 {
9477         if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9478                 if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9479                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9480                         dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9481 }
9482
9483 /**
9484  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9485  * @pf: board private structure
9486  **/
9487 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9488 {
9489         if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9490                 /* ATR uses the same filtering logic as SB rules. It only
9491                  * functions properly if the input set mask is at the default
9492                  * settings. It is safe to restore the default input set
9493                  * because there are no active TCPv4 filter rules.
9494                  */
9495                 i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9496                                         I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9497                                         I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9498
9499                 if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9500                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9501                         dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9502         }
9503 }
9504
9505 /**
9506  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9507  * @pf: board private structure
9508  * @filter: FDir filter to remove
9509  */
9510 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9511                                        struct i40e_fdir_filter *filter)
9512 {
9513         /* Update counters */
9514         pf->fdir_pf_active_filters--;
9515         pf->fd_inv = 0;
9516
9517         switch (filter->flow_type) {
9518         case TCP_V4_FLOW:
9519                 pf->fd_tcp4_filter_cnt--;
9520                 break;
9521         case UDP_V4_FLOW:
9522                 pf->fd_udp4_filter_cnt--;
9523                 break;
9524         case SCTP_V4_FLOW:
9525                 pf->fd_sctp4_filter_cnt--;
9526                 break;
9527         case TCP_V6_FLOW:
9528                 pf->fd_tcp6_filter_cnt--;
9529                 break;
9530         case UDP_V6_FLOW:
9531                 pf->fd_udp6_filter_cnt--;
9532                 break;
9533         case SCTP_V6_FLOW:
9534                 pf->fd_udp6_filter_cnt--;
9535                 break;
9536         case IP_USER_FLOW:
9537                 switch (filter->ipl4_proto) {
9538                 case IPPROTO_TCP:
9539                         pf->fd_tcp4_filter_cnt--;
9540                         break;
9541                 case IPPROTO_UDP:
9542                         pf->fd_udp4_filter_cnt--;
9543                         break;
9544                 case IPPROTO_SCTP:
9545                         pf->fd_sctp4_filter_cnt--;
9546                         break;
9547                 case IPPROTO_IP:
9548                         pf->fd_ip4_filter_cnt--;
9549                         break;
9550                 }
9551                 break;
9552         case IPV6_USER_FLOW:
9553                 switch (filter->ipl4_proto) {
9554                 case IPPROTO_TCP:
9555                         pf->fd_tcp6_filter_cnt--;
9556                         break;
9557                 case IPPROTO_UDP:
9558                         pf->fd_udp6_filter_cnt--;
9559                         break;
9560                 case IPPROTO_SCTP:
9561                         pf->fd_sctp6_filter_cnt--;
9562                         break;
9563                 case IPPROTO_IP:
9564                         pf->fd_ip6_filter_cnt--;
9565                         break;
9566                 }
9567                 break;
9568         }
9569
9570         /* Remove the filter from the list and free memory */
9571         hlist_del(&filter->fdir_node);
9572         kfree(filter);
9573 }
9574
9575 /**
9576  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9577  * @pf: board private structure
9578  **/
9579 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9580 {
9581         struct i40e_fdir_filter *filter;
9582         u32 fcnt_prog, fcnt_avail;
9583         struct hlist_node *node;
9584
9585         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9586                 return;
9587
9588         /* Check if we have enough room to re-enable FDir SB capability. */
9589         fcnt_prog = i40e_get_global_fd_count(pf);
9590         fcnt_avail = pf->fdir_pf_filter_count;
9591         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9592             (pf->fd_add_err == 0) ||
9593             (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9594                 i40e_reenable_fdir_sb(pf);
9595
9596         /* We should wait for even more space before re-enabling ATR.
9597          * Additionally, we cannot enable ATR as long as we still have TCP SB
9598          * rules active.
9599          */
9600         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9601             pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9602                 i40e_reenable_fdir_atr(pf);
9603
9604         /* if hw had a problem adding a filter, delete it */
9605         if (pf->fd_inv > 0) {
9606                 hlist_for_each_entry_safe(filter, node,
9607                                           &pf->fdir_filter_list, fdir_node)
9608                         if (filter->fd_id == pf->fd_inv)
9609                                 i40e_delete_invalid_filter(pf, filter);
9610         }
9611 }
9612
9613 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9614 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9615 /**
9616  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9617  * @pf: board private structure
9618  **/
9619 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9620 {
9621         unsigned long min_flush_time;
9622         int flush_wait_retry = 50;
9623         bool disable_atr = false;
9624         int fd_room;
9625         int reg;
9626
9627         if (!time_after(jiffies, pf->fd_flush_timestamp +
9628                                  (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9629                 return;
9630
9631         /* If the flush is happening too quick and we have mostly SB rules we
9632          * should not re-enable ATR for some time.
9633          */
9634         min_flush_time = pf->fd_flush_timestamp +
9635                          (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9636         fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9637
9638         if (!(time_after(jiffies, min_flush_time)) &&
9639             (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9640                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9641                         dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9642                 disable_atr = true;
9643         }
9644
9645         pf->fd_flush_timestamp = jiffies;
9646         set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9647         /* flush all filters */
9648         wr32(&pf->hw, I40E_PFQF_CTL_1,
9649              I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9650         i40e_flush(&pf->hw);
9651         pf->fd_flush_cnt++;
9652         pf->fd_add_err = 0;
9653         do {
9654                 /* Check FD flush status every 5-6msec */
9655                 usleep_range(5000, 6000);
9656                 reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9657                 if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9658                         break;
9659         } while (flush_wait_retry--);
9660         if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9661                 dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9662         } else {
9663                 /* replay sideband filters */
9664                 i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9665                 if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9666                         clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9667                 clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9668                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9669                         dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9670         }
9671 }
9672
9673 /**
9674  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9675  * @pf: board private structure
9676  **/
9677 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9678 {
9679         return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9680 }
9681
9682 /**
9683  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9684  * @pf: board private structure
9685  **/
9686 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9687 {
9688
9689         /* if interface is down do nothing */
9690         if (test_bit(__I40E_DOWN, pf->state))
9691                 return;
9692
9693         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9694                 i40e_fdir_flush_and_replay(pf);
9695
9696         i40e_fdir_check_and_reenable(pf);
9697
9698 }
9699
9700 /**
9701  * i40e_vsi_link_event - notify VSI of a link event
9702  * @vsi: vsi to be notified
9703  * @link_up: link up or down
9704  **/
9705 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9706 {
9707         if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9708                 return;
9709
9710         switch (vsi->type) {
9711         case I40E_VSI_MAIN:
9712                 if (!vsi->netdev || !vsi->netdev_registered)
9713                         break;
9714
9715                 if (link_up) {
9716                         netif_carrier_on(vsi->netdev);
9717                         netif_tx_wake_all_queues(vsi->netdev);
9718                 } else {
9719                         netif_carrier_off(vsi->netdev);
9720                         netif_tx_stop_all_queues(vsi->netdev);
9721                 }
9722                 break;
9723
9724         case I40E_VSI_SRIOV:
9725         case I40E_VSI_VMDQ2:
9726         case I40E_VSI_CTRL:
9727         case I40E_VSI_IWARP:
9728         case I40E_VSI_MIRROR:
9729         default:
9730                 /* there is no notification for other VSIs */
9731                 break;
9732         }
9733 }
9734
9735 /**
9736  * i40e_veb_link_event - notify elements on the veb of a link event
9737  * @veb: veb to be notified
9738  * @link_up: link up or down
9739  **/
9740 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9741 {
9742         struct i40e_pf *pf;
9743         int i;
9744
9745         if (!veb || !veb->pf)
9746                 return;
9747         pf = veb->pf;
9748
9749         /* depth first... */
9750         for (i = 0; i < I40E_MAX_VEB; i++)
9751                 if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9752                         i40e_veb_link_event(pf->veb[i], link_up);
9753
9754         /* ... now the local VSIs */
9755         for (i = 0; i < pf->num_alloc_vsi; i++)
9756                 if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9757                         i40e_vsi_link_event(pf->vsi[i], link_up);
9758 }
9759
9760 /**
9761  * i40e_link_event - Update netif_carrier status
9762  * @pf: board private structure
9763  **/
9764 static void i40e_link_event(struct i40e_pf *pf)
9765 {
9766         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9767         u8 new_link_speed, old_link_speed;
9768         i40e_status status;
9769         bool new_link, old_link;
9770 #ifdef CONFIG_I40E_DCB
9771         int err;
9772 #endif /* CONFIG_I40E_DCB */
9773
9774         /* set this to force the get_link_status call to refresh state */
9775         pf->hw.phy.get_link_info = true;
9776         old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9777         status = i40e_get_link_status(&pf->hw, &new_link);
9778
9779         /* On success, disable temp link polling */
9780         if (status == I40E_SUCCESS) {
9781                 clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9782         } else {
9783                 /* Enable link polling temporarily until i40e_get_link_status
9784                  * returns I40E_SUCCESS
9785                  */
9786                 set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9787                 dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9788                         status);
9789                 return;
9790         }
9791
9792         old_link_speed = pf->hw.phy.link_info_old.link_speed;
9793         new_link_speed = pf->hw.phy.link_info.link_speed;
9794
9795         if (new_link == old_link &&
9796             new_link_speed == old_link_speed &&
9797             (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9798              new_link == netif_carrier_ok(vsi->netdev)))
9799                 return;
9800
9801         i40e_print_link_message(vsi, new_link);
9802
9803         /* Notify the base of the switch tree connected to
9804          * the link.  Floating VEBs are not notified.
9805          */
9806         if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9807                 i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9808         else
9809                 i40e_vsi_link_event(vsi, new_link);
9810
9811         if (pf->vf)
9812                 i40e_vc_notify_link_state(pf);
9813
9814         if (pf->flags & I40E_FLAG_PTP)
9815                 i40e_ptp_set_increment(pf);
9816 #ifdef CONFIG_I40E_DCB
9817         if (new_link == old_link)
9818                 return;
9819         /* Not SW DCB so firmware will take care of default settings */
9820         if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9821                 return;
9822
9823         /* We cover here only link down, as after link up in case of SW DCB
9824          * SW LLDP agent will take care of setting it up
9825          */
9826         if (!new_link) {
9827                 dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9828                 memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9829                 err = i40e_dcb_sw_default_config(pf);
9830                 if (err) {
9831                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9832                                        I40E_FLAG_DCB_ENABLED);
9833                 } else {
9834                         pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9835                                        DCB_CAP_DCBX_VER_IEEE;
9836                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
9837                         pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9838                 }
9839         }
9840 #endif /* CONFIG_I40E_DCB */
9841 }
9842
9843 /**
9844  * i40e_watchdog_subtask - periodic checks not using event driven response
9845  * @pf: board private structure
9846  **/
9847 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9848 {
9849         int i;
9850
9851         /* if interface is down do nothing */
9852         if (test_bit(__I40E_DOWN, pf->state) ||
9853             test_bit(__I40E_CONFIG_BUSY, pf->state))
9854                 return;
9855
9856         /* make sure we don't do these things too often */
9857         if (time_before(jiffies, (pf->service_timer_previous +
9858                                   pf->service_timer_period)))
9859                 return;
9860         pf->service_timer_previous = jiffies;
9861
9862         if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9863             test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9864                 i40e_link_event(pf);
9865
9866         /* Update the stats for active netdevs so the network stack
9867          * can look at updated numbers whenever it cares to
9868          */
9869         for (i = 0; i < pf->num_alloc_vsi; i++)
9870                 if (pf->vsi[i] && pf->vsi[i]->netdev)
9871                         i40e_update_stats(pf->vsi[i]);
9872
9873         if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9874                 /* Update the stats for the active switching components */
9875                 for (i = 0; i < I40E_MAX_VEB; i++)
9876                         if (pf->veb[i])
9877                                 i40e_update_veb_stats(pf->veb[i]);
9878         }
9879
9880         i40e_ptp_rx_hang(pf);
9881         i40e_ptp_tx_hang(pf);
9882 }
9883
9884 /**
9885  * i40e_reset_subtask - Set up for resetting the device and driver
9886  * @pf: board private structure
9887  **/
9888 static void i40e_reset_subtask(struct i40e_pf *pf)
9889 {
9890         u32 reset_flags = 0;
9891
9892         if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
9893                 reset_flags |= BIT(__I40E_REINIT_REQUESTED);
9894                 clear_bit(__I40E_REINIT_REQUESTED, pf->state);
9895         }
9896         if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
9897                 reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
9898                 clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9899         }
9900         if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
9901                 reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
9902                 clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
9903         }
9904         if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
9905                 reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
9906                 clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
9907         }
9908         if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
9909                 reset_flags |= BIT(__I40E_DOWN_REQUESTED);
9910                 clear_bit(__I40E_DOWN_REQUESTED, pf->state);
9911         }
9912
9913         /* If there's a recovery already waiting, it takes
9914          * precedence before starting a new reset sequence.
9915          */
9916         if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
9917                 i40e_prep_for_reset(pf);
9918                 i40e_reset(pf);
9919                 i40e_rebuild(pf, false, false);
9920         }
9921
9922         /* If we're already down or resetting, just bail */
9923         if (reset_flags &&
9924             !test_bit(__I40E_DOWN, pf->state) &&
9925             !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
9926                 i40e_do_reset(pf, reset_flags, false);
9927         }
9928 }
9929
9930 /**
9931  * i40e_handle_link_event - Handle link event
9932  * @pf: board private structure
9933  * @e: event info posted on ARQ
9934  **/
9935 static void i40e_handle_link_event(struct i40e_pf *pf,
9936                                    struct i40e_arq_event_info *e)
9937 {
9938         struct i40e_aqc_get_link_status *status =
9939                 (struct i40e_aqc_get_link_status *)&e->desc.params.raw;
9940
9941         /* Do a new status request to re-enable LSE reporting
9942          * and load new status information into the hw struct
9943          * This completely ignores any state information
9944          * in the ARQ event info, instead choosing to always
9945          * issue the AQ update link status command.
9946          */
9947         i40e_link_event(pf);
9948
9949         /* Check if module meets thermal requirements */
9950         if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
9951                 dev_err(&pf->pdev->dev,
9952                         "Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
9953                 dev_err(&pf->pdev->dev,
9954                         "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9955         } else {
9956                 /* check for unqualified module, if link is down, suppress
9957                  * the message if link was forced to be down.
9958                  */
9959                 if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
9960                     (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
9961                     (!(status->link_info & I40E_AQ_LINK_UP)) &&
9962                     (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
9963                         dev_err(&pf->pdev->dev,
9964                                 "Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
9965                         dev_err(&pf->pdev->dev,
9966                                 "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9967                 }
9968         }
9969 }
9970
9971 /**
9972  * i40e_clean_adminq_subtask - Clean the AdminQ rings
9973  * @pf: board private structure
9974  **/
9975 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
9976 {
9977         struct i40e_arq_event_info event;
9978         struct i40e_hw *hw = &pf->hw;
9979         u16 pending, i = 0;
9980         i40e_status ret;
9981         u16 opcode;
9982         u32 oldval;
9983         u32 val;
9984
9985         /* Do not run clean AQ when PF reset fails */
9986         if (test_bit(__I40E_RESET_FAILED, pf->state))
9987                 return;
9988
9989         /* check for error indications */
9990         val = rd32(&pf->hw, pf->hw.aq.arq.len);
9991         oldval = val;
9992         if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
9993                 if (hw->debug_mask & I40E_DEBUG_AQ)
9994                         dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
9995                 val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
9996         }
9997         if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
9998                 if (hw->debug_mask & I40E_DEBUG_AQ)
9999                         dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10000                 val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10001                 pf->arq_overflows++;
10002         }
10003         if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10004                 if (hw->debug_mask & I40E_DEBUG_AQ)
10005                         dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10006                 val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10007         }
10008         if (oldval != val)
10009                 wr32(&pf->hw, pf->hw.aq.arq.len, val);
10010
10011         val = rd32(&pf->hw, pf->hw.aq.asq.len);
10012         oldval = val;
10013         if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10014                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10015                         dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10016                 val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10017         }
10018         if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10019                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10020                         dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10021                 val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10022         }
10023         if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10024                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10025                         dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10026                 val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10027         }
10028         if (oldval != val)
10029                 wr32(&pf->hw, pf->hw.aq.asq.len, val);
10030
10031         event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10032         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10033         if (!event.msg_buf)
10034                 return;
10035
10036         do {
10037                 ret = i40e_clean_arq_element(hw, &event, &pending);
10038                 if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
10039                         break;
10040                 else if (ret) {
10041                         dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10042                         break;
10043                 }
10044
10045                 opcode = le16_to_cpu(event.desc.opcode);
10046                 switch (opcode) {
10047
10048                 case i40e_aqc_opc_get_link_status:
10049                         rtnl_lock();
10050                         i40e_handle_link_event(pf, &event);
10051                         rtnl_unlock();
10052                         break;
10053                 case i40e_aqc_opc_send_msg_to_pf:
10054                         ret = i40e_vc_process_vf_msg(pf,
10055                                         le16_to_cpu(event.desc.retval),
10056                                         le32_to_cpu(event.desc.cookie_high),
10057                                         le32_to_cpu(event.desc.cookie_low),
10058                                         event.msg_buf,
10059                                         event.msg_len);
10060                         break;
10061                 case i40e_aqc_opc_lldp_update_mib:
10062                         dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10063 #ifdef CONFIG_I40E_DCB
10064                         rtnl_lock();
10065                         i40e_handle_lldp_event(pf, &event);
10066                         rtnl_unlock();
10067 #endif /* CONFIG_I40E_DCB */
10068                         break;
10069                 case i40e_aqc_opc_event_lan_overflow:
10070                         dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10071                         i40e_handle_lan_overflow_event(pf, &event);
10072                         break;
10073                 case i40e_aqc_opc_send_msg_to_peer:
10074                         dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10075                         break;
10076                 case i40e_aqc_opc_nvm_erase:
10077                 case i40e_aqc_opc_nvm_update:
10078                 case i40e_aqc_opc_oem_post_update:
10079                         i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10080                                    "ARQ NVM operation 0x%04x completed\n",
10081                                    opcode);
10082                         break;
10083                 default:
10084                         dev_info(&pf->pdev->dev,
10085                                  "ARQ: Unknown event 0x%04x ignored\n",
10086                                  opcode);
10087                         break;
10088                 }
10089         } while (i++ < pf->adminq_work_limit);
10090
10091         if (i < pf->adminq_work_limit)
10092                 clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10093
10094         /* re-enable Admin queue interrupt cause */
10095         val = rd32(hw, I40E_PFINT_ICR0_ENA);
10096         val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10097         wr32(hw, I40E_PFINT_ICR0_ENA, val);
10098         i40e_flush(hw);
10099
10100         kfree(event.msg_buf);
10101 }
10102
10103 /**
10104  * i40e_verify_eeprom - make sure eeprom is good to use
10105  * @pf: board private structure
10106  **/
10107 static void i40e_verify_eeprom(struct i40e_pf *pf)
10108 {
10109         int err;
10110
10111         err = i40e_diag_eeprom_test(&pf->hw);
10112         if (err) {
10113                 /* retry in case of garbage read */
10114                 err = i40e_diag_eeprom_test(&pf->hw);
10115                 if (err) {
10116                         dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10117                                  err);
10118                         set_bit(__I40E_BAD_EEPROM, pf->state);
10119                 }
10120         }
10121
10122         if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10123                 dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10124                 clear_bit(__I40E_BAD_EEPROM, pf->state);
10125         }
10126 }
10127
10128 /**
10129  * i40e_enable_pf_switch_lb
10130  * @pf: pointer to the PF structure
10131  *
10132  * enable switch loop back or die - no point in a return value
10133  **/
10134 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10135 {
10136         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10137         struct i40e_vsi_context ctxt;
10138         int ret;
10139
10140         ctxt.seid = pf->main_vsi_seid;
10141         ctxt.pf_num = pf->hw.pf_id;
10142         ctxt.vf_num = 0;
10143         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10144         if (ret) {
10145                 dev_info(&pf->pdev->dev,
10146                          "couldn't get PF vsi config, err %s aq_err %s\n",
10147                          i40e_stat_str(&pf->hw, ret),
10148                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10149                 return;
10150         }
10151         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10152         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10153         ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10154
10155         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10156         if (ret) {
10157                 dev_info(&pf->pdev->dev,
10158                          "update vsi switch failed, err %s aq_err %s\n",
10159                          i40e_stat_str(&pf->hw, ret),
10160                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10161         }
10162 }
10163
10164 /**
10165  * i40e_disable_pf_switch_lb
10166  * @pf: pointer to the PF structure
10167  *
10168  * disable switch loop back or die - no point in a return value
10169  **/
10170 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10171 {
10172         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10173         struct i40e_vsi_context ctxt;
10174         int ret;
10175
10176         ctxt.seid = pf->main_vsi_seid;
10177         ctxt.pf_num = pf->hw.pf_id;
10178         ctxt.vf_num = 0;
10179         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10180         if (ret) {
10181                 dev_info(&pf->pdev->dev,
10182                          "couldn't get PF vsi config, err %s aq_err %s\n",
10183                          i40e_stat_str(&pf->hw, ret),
10184                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10185                 return;
10186         }
10187         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10188         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10189         ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10190
10191         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10192         if (ret) {
10193                 dev_info(&pf->pdev->dev,
10194                          "update vsi switch failed, err %s aq_err %s\n",
10195                          i40e_stat_str(&pf->hw, ret),
10196                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10197         }
10198 }
10199
10200 /**
10201  * i40e_config_bridge_mode - Configure the HW bridge mode
10202  * @veb: pointer to the bridge instance
10203  *
10204  * Configure the loop back mode for the LAN VSI that is downlink to the
10205  * specified HW bridge instance. It is expected this function is called
10206  * when a new HW bridge is instantiated.
10207  **/
10208 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10209 {
10210         struct i40e_pf *pf = veb->pf;
10211
10212         if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10213                 dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10214                          veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10215         if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10216                 i40e_disable_pf_switch_lb(pf);
10217         else
10218                 i40e_enable_pf_switch_lb(pf);
10219 }
10220
10221 /**
10222  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10223  * @veb: pointer to the VEB instance
10224  *
10225  * This is a recursive function that first builds the attached VSIs then
10226  * recurses in to build the next layer of VEB.  We track the connections
10227  * through our own index numbers because the seid's from the HW could
10228  * change across the reset.
10229  **/
10230 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10231 {
10232         struct i40e_vsi *ctl_vsi = NULL;
10233         struct i40e_pf *pf = veb->pf;
10234         int v, veb_idx;
10235         int ret;
10236
10237         /* build VSI that owns this VEB, temporarily attached to base VEB */
10238         for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10239                 if (pf->vsi[v] &&
10240                     pf->vsi[v]->veb_idx == veb->idx &&
10241                     pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10242                         ctl_vsi = pf->vsi[v];
10243                         break;
10244                 }
10245         }
10246         if (!ctl_vsi) {
10247                 dev_info(&pf->pdev->dev,
10248                          "missing owner VSI for veb_idx %d\n", veb->idx);
10249                 ret = -ENOENT;
10250                 goto end_reconstitute;
10251         }
10252         if (ctl_vsi != pf->vsi[pf->lan_vsi])
10253                 ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10254         ret = i40e_add_vsi(ctl_vsi);
10255         if (ret) {
10256                 dev_info(&pf->pdev->dev,
10257                          "rebuild of veb_idx %d owner VSI failed: %d\n",
10258                          veb->idx, ret);
10259                 goto end_reconstitute;
10260         }
10261         i40e_vsi_reset_stats(ctl_vsi);
10262
10263         /* create the VEB in the switch and move the VSI onto the VEB */
10264         ret = i40e_add_veb(veb, ctl_vsi);
10265         if (ret)
10266                 goto end_reconstitute;
10267
10268         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10269                 veb->bridge_mode = BRIDGE_MODE_VEB;
10270         else
10271                 veb->bridge_mode = BRIDGE_MODE_VEPA;
10272         i40e_config_bridge_mode(veb);
10273
10274         /* create the remaining VSIs attached to this VEB */
10275         for (v = 0; v < pf->num_alloc_vsi; v++) {
10276                 if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10277                         continue;
10278
10279                 if (pf->vsi[v]->veb_idx == veb->idx) {
10280                         struct i40e_vsi *vsi = pf->vsi[v];
10281
10282                         vsi->uplink_seid = veb->seid;
10283                         ret = i40e_add_vsi(vsi);
10284                         if (ret) {
10285                                 dev_info(&pf->pdev->dev,
10286                                          "rebuild of vsi_idx %d failed: %d\n",
10287                                          v, ret);
10288                                 goto end_reconstitute;
10289                         }
10290                         i40e_vsi_reset_stats(vsi);
10291                 }
10292         }
10293
10294         /* create any VEBs attached to this VEB - RECURSION */
10295         for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10296                 if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10297                         pf->veb[veb_idx]->uplink_seid = veb->seid;
10298                         ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10299                         if (ret)
10300                                 break;
10301                 }
10302         }
10303
10304 end_reconstitute:
10305         return ret;
10306 }
10307
10308 /**
10309  * i40e_get_capabilities - get info about the HW
10310  * @pf: the PF struct
10311  * @list_type: AQ capability to be queried
10312  **/
10313 static int i40e_get_capabilities(struct i40e_pf *pf,
10314                                  enum i40e_admin_queue_opc list_type)
10315 {
10316         struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10317         u16 data_size;
10318         int buf_len;
10319         int err;
10320
10321         buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10322         do {
10323                 cap_buf = kzalloc(buf_len, GFP_KERNEL);
10324                 if (!cap_buf)
10325                         return -ENOMEM;
10326
10327                 /* this loads the data into the hw struct for us */
10328                 err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10329                                                     &data_size, list_type,
10330                                                     NULL);
10331                 /* data loaded, buffer no longer needed */
10332                 kfree(cap_buf);
10333
10334                 if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10335                         /* retry with a larger buffer */
10336                         buf_len = data_size;
10337                 } else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10338                         dev_info(&pf->pdev->dev,
10339                                  "capability discovery failed, err %s aq_err %s\n",
10340                                  i40e_stat_str(&pf->hw, err),
10341                                  i40e_aq_str(&pf->hw,
10342                                              pf->hw.aq.asq_last_status));
10343                         return -ENODEV;
10344                 }
10345         } while (err);
10346
10347         if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10348                 if (list_type == i40e_aqc_opc_list_func_capabilities) {
10349                         dev_info(&pf->pdev->dev,
10350                                  "pf=%d, num_vfs=%d, msix_pf=%d, msix_vf=%d, fd_g=%d, fd_b=%d, pf_max_q=%d num_vsi=%d\n",
10351                                  pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10352                                  pf->hw.func_caps.num_msix_vectors,
10353                                  pf->hw.func_caps.num_msix_vectors_vf,
10354                                  pf->hw.func_caps.fd_filters_guaranteed,
10355                                  pf->hw.func_caps.fd_filters_best_effort,
10356                                  pf->hw.func_caps.num_tx_qp,
10357                                  pf->hw.func_caps.num_vsis);
10358                 } else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10359                         dev_info(&pf->pdev->dev,
10360                                  "switch_mode=0x%04x, function_valid=0x%08x\n",
10361                                  pf->hw.dev_caps.switch_mode,
10362                                  pf->hw.dev_caps.valid_functions);
10363                         dev_info(&pf->pdev->dev,
10364                                  "SR-IOV=%d, num_vfs for all function=%u\n",
10365                                  pf->hw.dev_caps.sr_iov_1_1,
10366                                  pf->hw.dev_caps.num_vfs);
10367                         dev_info(&pf->pdev->dev,
10368                                  "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10369                                  pf->hw.dev_caps.num_vsis,
10370                                  pf->hw.dev_caps.num_rx_qp,
10371                                  pf->hw.dev_caps.num_tx_qp);
10372                 }
10373         }
10374         if (list_type == i40e_aqc_opc_list_func_capabilities) {
10375 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10376                        + pf->hw.func_caps.num_vfs)
10377                 if (pf->hw.revision_id == 0 &&
10378                     pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10379                         dev_info(&pf->pdev->dev,
10380                                  "got num_vsis %d, setting num_vsis to %d\n",
10381                                  pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10382                         pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10383                 }
10384         }
10385         return 0;
10386 }
10387
10388 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10389
10390 /**
10391  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10392  * @pf: board private structure
10393  **/
10394 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10395 {
10396         struct i40e_vsi *vsi;
10397
10398         /* quick workaround for an NVM issue that leaves a critical register
10399          * uninitialized
10400          */
10401         if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10402                 static const u32 hkey[] = {
10403                         0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10404                         0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10405                         0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10406                         0x95b3a76d};
10407                 int i;
10408
10409                 for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10410                         wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10411         }
10412
10413         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10414                 return;
10415
10416         /* find existing VSI and see if it needs configuring */
10417         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10418
10419         /* create a new VSI if none exists */
10420         if (!vsi) {
10421                 vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10422                                      pf->vsi[pf->lan_vsi]->seid, 0);
10423                 if (!vsi) {
10424                         dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10425                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10426                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10427                         return;
10428                 }
10429         }
10430
10431         i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10432 }
10433
10434 /**
10435  * i40e_fdir_teardown - release the Flow Director resources
10436  * @pf: board private structure
10437  **/
10438 static void i40e_fdir_teardown(struct i40e_pf *pf)
10439 {
10440         struct i40e_vsi *vsi;
10441
10442         i40e_fdir_filter_exit(pf);
10443         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10444         if (vsi)
10445                 i40e_vsi_release(vsi);
10446 }
10447
10448 /**
10449  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10450  * @vsi: PF main vsi
10451  * @seid: seid of main or channel VSIs
10452  *
10453  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10454  * existed before reset
10455  **/
10456 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10457 {
10458         struct i40e_cloud_filter *cfilter;
10459         struct i40e_pf *pf = vsi->back;
10460         struct hlist_node *node;
10461         i40e_status ret;
10462
10463         /* Add cloud filters back if they exist */
10464         hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10465                                   cloud_node) {
10466                 if (cfilter->seid != seid)
10467                         continue;
10468
10469                 if (cfilter->dst_port)
10470                         ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10471                                                                 true);
10472                 else
10473                         ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10474
10475                 if (ret) {
10476                         dev_dbg(&pf->pdev->dev,
10477                                 "Failed to rebuild cloud filter, err %s aq_err %s\n",
10478                                 i40e_stat_str(&pf->hw, ret),
10479                                 i40e_aq_str(&pf->hw,
10480                                             pf->hw.aq.asq_last_status));
10481                         return ret;
10482                 }
10483         }
10484         return 0;
10485 }
10486
10487 /**
10488  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10489  * @vsi: PF main vsi
10490  *
10491  * Rebuilds channel VSIs if they existed before reset
10492  **/
10493 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10494 {
10495         struct i40e_channel *ch, *ch_tmp;
10496         i40e_status ret;
10497
10498         if (list_empty(&vsi->ch_list))
10499                 return 0;
10500
10501         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10502                 if (!ch->initialized)
10503                         break;
10504                 /* Proceed with creation of channel (VMDq2) VSI */
10505                 ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10506                 if (ret) {
10507                         dev_info(&vsi->back->pdev->dev,
10508                                  "failed to rebuild channels using uplink_seid %u\n",
10509                                  vsi->uplink_seid);
10510                         return ret;
10511                 }
10512                 /* Reconfigure TX queues using QTX_CTL register */
10513                 ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10514                 if (ret) {
10515                         dev_info(&vsi->back->pdev->dev,
10516                                  "failed to configure TX rings for channel %u\n",
10517                                  ch->seid);
10518                         return ret;
10519                 }
10520                 /* update 'next_base_queue' */
10521                 vsi->next_base_queue = vsi->next_base_queue +
10522                                                         ch->num_queue_pairs;
10523                 if (ch->max_tx_rate) {
10524                         u64 credits = ch->max_tx_rate;
10525
10526                         if (i40e_set_bw_limit(vsi, ch->seid,
10527                                               ch->max_tx_rate))
10528                                 return -EINVAL;
10529
10530                         do_div(credits, I40E_BW_CREDIT_DIVISOR);
10531                         dev_dbg(&vsi->back->pdev->dev,
10532                                 "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10533                                 ch->max_tx_rate,
10534                                 credits,
10535                                 ch->seid);
10536                 }
10537                 ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10538                 if (ret) {
10539                         dev_dbg(&vsi->back->pdev->dev,
10540                                 "Failed to rebuild cloud filters for channel VSI %u\n",
10541                                 ch->seid);
10542                         return ret;
10543                 }
10544         }
10545         return 0;
10546 }
10547
10548 /**
10549  * i40e_prep_for_reset - prep for the core to reset
10550  * @pf: board private structure
10551  *
10552  * Close up the VFs and other things in prep for PF Reset.
10553   **/
10554 static void i40e_prep_for_reset(struct i40e_pf *pf)
10555 {
10556         struct i40e_hw *hw = &pf->hw;
10557         i40e_status ret = 0;
10558         u32 v;
10559
10560         clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10561         if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10562                 return;
10563         if (i40e_check_asq_alive(&pf->hw))
10564                 i40e_vc_notify_reset(pf);
10565
10566         dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10567
10568         /* quiesce the VSIs and their queues that are not already DOWN */
10569         i40e_pf_quiesce_all_vsi(pf);
10570
10571         for (v = 0; v < pf->num_alloc_vsi; v++) {
10572                 if (pf->vsi[v])
10573                         pf->vsi[v]->seid = 0;
10574         }
10575
10576         i40e_shutdown_adminq(&pf->hw);
10577
10578         /* call shutdown HMC */
10579         if (hw->hmc.hmc_obj) {
10580                 ret = i40e_shutdown_lan_hmc(hw);
10581                 if (ret)
10582                         dev_warn(&pf->pdev->dev,
10583                                  "shutdown_lan_hmc failed: %d\n", ret);
10584         }
10585
10586         /* Save the current PTP time so that we can restore the time after the
10587          * reset completes.
10588          */
10589         i40e_ptp_save_hw_time(pf);
10590 }
10591
10592 /**
10593  * i40e_send_version - update firmware with driver version
10594  * @pf: PF struct
10595  */
10596 static void i40e_send_version(struct i40e_pf *pf)
10597 {
10598         struct i40e_driver_version dv;
10599
10600         dv.major_version = 0xff;
10601         dv.minor_version = 0xff;
10602         dv.build_version = 0xff;
10603         dv.subbuild_version = 0;
10604         strlcpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10605         i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10606 }
10607
10608 /**
10609  * i40e_get_oem_version - get OEM specific version information
10610  * @hw: pointer to the hardware structure
10611  **/
10612 static void i40e_get_oem_version(struct i40e_hw *hw)
10613 {
10614         u16 block_offset = 0xffff;
10615         u16 block_length = 0;
10616         u16 capabilities = 0;
10617         u16 gen_snap = 0;
10618         u16 release = 0;
10619
10620 #define I40E_SR_NVM_OEM_VERSION_PTR             0x1B
10621 #define I40E_NVM_OEM_LENGTH_OFFSET              0x00
10622 #define I40E_NVM_OEM_CAPABILITIES_OFFSET        0x01
10623 #define I40E_NVM_OEM_GEN_OFFSET                 0x02
10624 #define I40E_NVM_OEM_RELEASE_OFFSET             0x03
10625 #define I40E_NVM_OEM_CAPABILITIES_MASK          0x000F
10626 #define I40E_NVM_OEM_LENGTH                     3
10627
10628         /* Check if pointer to OEM version block is valid. */
10629         i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10630         if (block_offset == 0xffff)
10631                 return;
10632
10633         /* Check if OEM version block has correct length. */
10634         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10635                            &block_length);
10636         if (block_length < I40E_NVM_OEM_LENGTH)
10637                 return;
10638
10639         /* Check if OEM version format is as expected. */
10640         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10641                            &capabilities);
10642         if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10643                 return;
10644
10645         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10646                            &gen_snap);
10647         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10648                            &release);
10649         hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10650         hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10651 }
10652
10653 /**
10654  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10655  * @pf: board private structure
10656  **/
10657 static int i40e_reset(struct i40e_pf *pf)
10658 {
10659         struct i40e_hw *hw = &pf->hw;
10660         i40e_status ret;
10661
10662         ret = i40e_pf_reset(hw);
10663         if (ret) {
10664                 dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10665                 set_bit(__I40E_RESET_FAILED, pf->state);
10666                 clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10667         } else {
10668                 pf->pfr_count++;
10669         }
10670         return ret;
10671 }
10672
10673 /**
10674  * i40e_rebuild - rebuild using a saved config
10675  * @pf: board private structure
10676  * @reinit: if the Main VSI needs to re-initialized.
10677  * @lock_acquired: indicates whether or not the lock has been acquired
10678  * before this function was called.
10679  **/
10680 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10681 {
10682         const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10683         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10684         struct i40e_hw *hw = &pf->hw;
10685         i40e_status ret;
10686         u32 val;
10687         int v;
10688
10689         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10690             is_recovery_mode_reported)
10691                 i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10692
10693         if (test_bit(__I40E_DOWN, pf->state) &&
10694             !test_bit(__I40E_RECOVERY_MODE, pf->state))
10695                 goto clear_recovery;
10696         dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10697
10698         /* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10699         ret = i40e_init_adminq(&pf->hw);
10700         if (ret) {
10701                 dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
10702                          i40e_stat_str(&pf->hw, ret),
10703                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10704                 goto clear_recovery;
10705         }
10706         i40e_get_oem_version(&pf->hw);
10707
10708         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10709                 /* The following delay is necessary for firmware update. */
10710                 mdelay(1000);
10711         }
10712
10713         /* re-verify the eeprom if we just had an EMP reset */
10714         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10715                 i40e_verify_eeprom(pf);
10716
10717         /* if we are going out of or into recovery mode we have to act
10718          * accordingly with regard to resources initialization
10719          * and deinitialization
10720          */
10721         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10722                 if (i40e_get_capabilities(pf,
10723                                           i40e_aqc_opc_list_func_capabilities))
10724                         goto end_unlock;
10725
10726                 if (is_recovery_mode_reported) {
10727                         /* we're staying in recovery mode so we'll reinitialize
10728                          * misc vector here
10729                          */
10730                         if (i40e_setup_misc_vector_for_recovery_mode(pf))
10731                                 goto end_unlock;
10732                 } else {
10733                         if (!lock_acquired)
10734                                 rtnl_lock();
10735                         /* we're going out of recovery mode so we'll free
10736                          * the IRQ allocated specifically for recovery mode
10737                          * and restore the interrupt scheme
10738                          */
10739                         free_irq(pf->pdev->irq, pf);
10740                         i40e_clear_interrupt_scheme(pf);
10741                         if (i40e_restore_interrupt_scheme(pf))
10742                                 goto end_unlock;
10743                 }
10744
10745                 /* tell the firmware that we're starting */
10746                 i40e_send_version(pf);
10747
10748                 /* bail out in case recovery mode was detected, as there is
10749                  * no need for further configuration.
10750                  */
10751                 goto end_unlock;
10752         }
10753
10754         i40e_clear_pxe_mode(hw);
10755         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10756         if (ret)
10757                 goto end_core_reset;
10758
10759         ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10760                                 hw->func_caps.num_rx_qp, 0, 0);
10761         if (ret) {
10762                 dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10763                 goto end_core_reset;
10764         }
10765         ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10766         if (ret) {
10767                 dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10768                 goto end_core_reset;
10769         }
10770
10771 #ifdef CONFIG_I40E_DCB
10772         /* Enable FW to write a default DCB config on link-up
10773          * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10774          * is not supported with new link speed
10775          */
10776         if (i40e_is_tc_mqprio_enabled(pf)) {
10777                 i40e_aq_set_dcb_parameters(hw, false, NULL);
10778         } else {
10779                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10780                     (hw->phy.link_info.link_speed &
10781                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10782                         i40e_aq_set_dcb_parameters(hw, false, NULL);
10783                         dev_warn(&pf->pdev->dev,
10784                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10785                         pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10786                 } else {
10787                         i40e_aq_set_dcb_parameters(hw, true, NULL);
10788                         ret = i40e_init_pf_dcb(pf);
10789                         if (ret) {
10790                                 dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10791                                          ret);
10792                                 pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10793                                 /* Continue without DCB enabled */
10794                         }
10795                 }
10796         }
10797
10798 #endif /* CONFIG_I40E_DCB */
10799         if (!lock_acquired)
10800                 rtnl_lock();
10801         ret = i40e_setup_pf_switch(pf, reinit, true);
10802         if (ret)
10803                 goto end_unlock;
10804
10805         /* The driver only wants link up/down and module qualification
10806          * reports from firmware.  Note the negative logic.
10807          */
10808         ret = i40e_aq_set_phy_int_mask(&pf->hw,
10809                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
10810                                          I40E_AQ_EVENT_MEDIA_NA |
10811                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10812         if (ret)
10813                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
10814                          i40e_stat_str(&pf->hw, ret),
10815                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10816
10817         /* Rebuild the VSIs and VEBs that existed before reset.
10818          * They are still in our local switch element arrays, so only
10819          * need to rebuild the switch model in the HW.
10820          *
10821          * If there were VEBs but the reconstitution failed, we'll try
10822          * to recover minimal use by getting the basic PF VSI working.
10823          */
10824         if (vsi->uplink_seid != pf->mac_seid) {
10825                 dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10826                 /* find the one VEB connected to the MAC, and find orphans */
10827                 for (v = 0; v < I40E_MAX_VEB; v++) {
10828                         if (!pf->veb[v])
10829                                 continue;
10830
10831                         if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10832                             pf->veb[v]->uplink_seid == 0) {
10833                                 ret = i40e_reconstitute_veb(pf->veb[v]);
10834
10835                                 if (!ret)
10836                                         continue;
10837
10838                                 /* If Main VEB failed, we're in deep doodoo,
10839                                  * so give up rebuilding the switch and set up
10840                                  * for minimal rebuild of PF VSI.
10841                                  * If orphan failed, we'll report the error
10842                                  * but try to keep going.
10843                                  */
10844                                 if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10845                                         dev_info(&pf->pdev->dev,
10846                                                  "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10847                                                  ret);
10848                                         vsi->uplink_seid = pf->mac_seid;
10849                                         break;
10850                                 } else if (pf->veb[v]->uplink_seid == 0) {
10851                                         dev_info(&pf->pdev->dev,
10852                                                  "rebuild of orphan VEB failed: %d\n",
10853                                                  ret);
10854                                 }
10855                         }
10856                 }
10857         }
10858
10859         if (vsi->uplink_seid == pf->mac_seid) {
10860                 dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
10861                 /* no VEB, so rebuild only the Main VSI */
10862                 ret = i40e_add_vsi(vsi);
10863                 if (ret) {
10864                         dev_info(&pf->pdev->dev,
10865                                  "rebuild of Main VSI failed: %d\n", ret);
10866                         goto end_unlock;
10867                 }
10868         }
10869
10870         if (vsi->mqprio_qopt.max_rate[0]) {
10871                 u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
10872                                                   vsi->mqprio_qopt.max_rate[0]);
10873                 u64 credits = 0;
10874
10875                 ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
10876                 if (ret)
10877                         goto end_unlock;
10878
10879                 credits = max_tx_rate;
10880                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
10881                 dev_dbg(&vsi->back->pdev->dev,
10882                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10883                         max_tx_rate,
10884                         credits,
10885                         vsi->seid);
10886         }
10887
10888         ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
10889         if (ret)
10890                 goto end_unlock;
10891
10892         /* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
10893          * for this main VSI if they exist
10894          */
10895         ret = i40e_rebuild_channels(vsi);
10896         if (ret)
10897                 goto end_unlock;
10898
10899         /* Reconfigure hardware for allowing smaller MSS in the case
10900          * of TSO, so that we avoid the MDD being fired and causing
10901          * a reset in the case of small MSS+TSO.
10902          */
10903 #define I40E_REG_MSS          0x000E64DC
10904 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
10905 #define I40E_64BYTE_MSS       0x400000
10906         val = rd32(hw, I40E_REG_MSS);
10907         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
10908                 val &= ~I40E_REG_MSS_MIN_MASK;
10909                 val |= I40E_64BYTE_MSS;
10910                 wr32(hw, I40E_REG_MSS, val);
10911         }
10912
10913         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
10914                 msleep(75);
10915                 ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
10916                 if (ret)
10917                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
10918                                  i40e_stat_str(&pf->hw, ret),
10919                                  i40e_aq_str(&pf->hw,
10920                                              pf->hw.aq.asq_last_status));
10921         }
10922         /* reinit the misc interrupt */
10923         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
10924                 ret = i40e_setup_misc_vector(pf);
10925
10926         /* Add a filter to drop all Flow control frames from any VSI from being
10927          * transmitted. By doing so we stop a malicious VF from sending out
10928          * PAUSE or PFC frames and potentially controlling traffic for other
10929          * PF/VF VSIs.
10930          * The FW can still send Flow control frames if enabled.
10931          */
10932         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
10933                                                        pf->main_vsi_seid);
10934
10935         /* restart the VSIs that were rebuilt and running before the reset */
10936         i40e_pf_unquiesce_all_vsi(pf);
10937
10938         /* Release the RTNL lock before we start resetting VFs */
10939         if (!lock_acquired)
10940                 rtnl_unlock();
10941
10942         /* Restore promiscuous settings */
10943         ret = i40e_set_promiscuous(pf, pf->cur_promisc);
10944         if (ret)
10945                 dev_warn(&pf->pdev->dev,
10946                          "Failed to restore promiscuous setting: %s, err %s aq_err %s\n",
10947                          pf->cur_promisc ? "on" : "off",
10948                          i40e_stat_str(&pf->hw, ret),
10949                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10950
10951         i40e_reset_all_vfs(pf, true);
10952
10953         /* tell the firmware that we're starting */
10954         i40e_send_version(pf);
10955
10956         /* We've already released the lock, so don't do it again */
10957         goto end_core_reset;
10958
10959 end_unlock:
10960         if (!lock_acquired)
10961                 rtnl_unlock();
10962 end_core_reset:
10963         clear_bit(__I40E_RESET_FAILED, pf->state);
10964 clear_recovery:
10965         clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10966         clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
10967 }
10968
10969 /**
10970  * i40e_reset_and_rebuild - reset and rebuild using a saved config
10971  * @pf: board private structure
10972  * @reinit: if the Main VSI needs to re-initialized.
10973  * @lock_acquired: indicates whether or not the lock has been acquired
10974  * before this function was called.
10975  **/
10976 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
10977                                    bool lock_acquired)
10978 {
10979         int ret;
10980
10981         if (test_bit(__I40E_IN_REMOVE, pf->state))
10982                 return;
10983         /* Now we wait for GRST to settle out.
10984          * We don't have to delete the VEBs or VSIs from the hw switch
10985          * because the reset will make them disappear.
10986          */
10987         ret = i40e_reset(pf);
10988         if (!ret)
10989                 i40e_rebuild(pf, reinit, lock_acquired);
10990 }
10991
10992 /**
10993  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
10994  * @pf: board private structure
10995  *
10996  * Close up the VFs and other things in prep for a Core Reset,
10997  * then get ready to rebuild the world.
10998  * @lock_acquired: indicates whether or not the lock has been acquired
10999  * before this function was called.
11000  **/
11001 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11002 {
11003         i40e_prep_for_reset(pf);
11004         i40e_reset_and_rebuild(pf, false, lock_acquired);
11005 }
11006
11007 /**
11008  * i40e_handle_mdd_event
11009  * @pf: pointer to the PF structure
11010  *
11011  * Called from the MDD irq handler to identify possibly malicious vfs
11012  **/
11013 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11014 {
11015         struct i40e_hw *hw = &pf->hw;
11016         bool mdd_detected = false;
11017         struct i40e_vf *vf;
11018         u32 reg;
11019         int i;
11020
11021         if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11022                 return;
11023
11024         /* find what triggered the MDD event */
11025         reg = rd32(hw, I40E_GL_MDET_TX);
11026         if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11027                 u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
11028                                 I40E_GL_MDET_TX_PF_NUM_SHIFT;
11029                 u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
11030                                 I40E_GL_MDET_TX_VF_NUM_SHIFT;
11031                 u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
11032                                 I40E_GL_MDET_TX_EVENT_SHIFT;
11033                 u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
11034                                 I40E_GL_MDET_TX_QUEUE_SHIFT) -
11035                                 pf->hw.func_caps.base_queue;
11036                 if (netif_msg_tx_err(pf))
11037                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11038                                  event, queue, pf_num, vf_num);
11039                 wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11040                 mdd_detected = true;
11041         }
11042         reg = rd32(hw, I40E_GL_MDET_RX);
11043         if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11044                 u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
11045                                 I40E_GL_MDET_RX_FUNCTION_SHIFT;
11046                 u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
11047                                 I40E_GL_MDET_RX_EVENT_SHIFT;
11048                 u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
11049                                 I40E_GL_MDET_RX_QUEUE_SHIFT) -
11050                                 pf->hw.func_caps.base_queue;
11051                 if (netif_msg_rx_err(pf))
11052                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11053                                  event, queue, func);
11054                 wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11055                 mdd_detected = true;
11056         }
11057
11058         if (mdd_detected) {
11059                 reg = rd32(hw, I40E_PF_MDET_TX);
11060                 if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11061                         wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11062                         dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11063                 }
11064                 reg = rd32(hw, I40E_PF_MDET_RX);
11065                 if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11066                         wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11067                         dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11068                 }
11069         }
11070
11071         /* see if one of the VFs needs its hand slapped */
11072         for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11073                 vf = &(pf->vf[i]);
11074                 reg = rd32(hw, I40E_VP_MDET_TX(i));
11075                 if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11076                         wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11077                         vf->num_mdd_events++;
11078                         dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11079                                  i);
11080                         dev_info(&pf->pdev->dev,
11081                                  "Use PF Control I/F to re-enable the VF\n");
11082                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11083                 }
11084
11085                 reg = rd32(hw, I40E_VP_MDET_RX(i));
11086                 if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11087                         wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11088                         vf->num_mdd_events++;
11089                         dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11090                                  i);
11091                         dev_info(&pf->pdev->dev,
11092                                  "Use PF Control I/F to re-enable the VF\n");
11093                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11094                 }
11095         }
11096
11097         /* re-enable mdd interrupt cause */
11098         clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11099         reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11100         reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11101         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11102         i40e_flush(hw);
11103 }
11104
11105 /**
11106  * i40e_service_task - Run the driver's async subtasks
11107  * @work: pointer to work_struct containing our data
11108  **/
11109 static void i40e_service_task(struct work_struct *work)
11110 {
11111         struct i40e_pf *pf = container_of(work,
11112                                           struct i40e_pf,
11113                                           service_task);
11114         unsigned long start_time = jiffies;
11115
11116         /* don't bother with service tasks if a reset is in progress */
11117         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11118             test_bit(__I40E_SUSPENDED, pf->state))
11119                 return;
11120
11121         if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11122                 return;
11123
11124         if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11125                 i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11126                 i40e_sync_filters_subtask(pf);
11127                 i40e_reset_subtask(pf);
11128                 i40e_handle_mdd_event(pf);
11129                 i40e_vc_process_vflr_event(pf);
11130                 i40e_watchdog_subtask(pf);
11131                 i40e_fdir_reinit_subtask(pf);
11132                 if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11133                         /* Client subtask will reopen next time through. */
11134                         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11135                                                            true);
11136                 } else {
11137                         i40e_client_subtask(pf);
11138                         if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11139                                                pf->state))
11140                                 i40e_notify_client_of_l2_param_changes(
11141                                                                 pf->vsi[pf->lan_vsi]);
11142                 }
11143                 i40e_sync_filters_subtask(pf);
11144         } else {
11145                 i40e_reset_subtask(pf);
11146         }
11147
11148         i40e_clean_adminq_subtask(pf);
11149
11150         /* flush memory to make sure state is correct before next watchdog */
11151         smp_mb__before_atomic();
11152         clear_bit(__I40E_SERVICE_SCHED, pf->state);
11153
11154         /* If the tasks have taken longer than one timer cycle or there
11155          * is more work to be done, reschedule the service task now
11156          * rather than wait for the timer to tick again.
11157          */
11158         if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11159             test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)             ||
11160             test_bit(__I40E_MDD_EVENT_PENDING, pf->state)                ||
11161             test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11162                 i40e_service_event_schedule(pf);
11163 }
11164
11165 /**
11166  * i40e_service_timer - timer callback
11167  * @t: timer list pointer
11168  **/
11169 static void i40e_service_timer(struct timer_list *t)
11170 {
11171         struct i40e_pf *pf = from_timer(pf, t, service_timer);
11172
11173         mod_timer(&pf->service_timer,
11174                   round_jiffies(jiffies + pf->service_timer_period));
11175         i40e_service_event_schedule(pf);
11176 }
11177
11178 /**
11179  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11180  * @vsi: the VSI being configured
11181  **/
11182 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11183 {
11184         struct i40e_pf *pf = vsi->back;
11185
11186         switch (vsi->type) {
11187         case I40E_VSI_MAIN:
11188                 vsi->alloc_queue_pairs = pf->num_lan_qps;
11189                 if (!vsi->num_tx_desc)
11190                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11191                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11192                 if (!vsi->num_rx_desc)
11193                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11194                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11195                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11196                         vsi->num_q_vectors = pf->num_lan_msix;
11197                 else
11198                         vsi->num_q_vectors = 1;
11199
11200                 break;
11201
11202         case I40E_VSI_FDIR:
11203                 vsi->alloc_queue_pairs = 1;
11204                 vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11205                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
11206                 vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11207                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
11208                 vsi->num_q_vectors = pf->num_fdsb_msix;
11209                 break;
11210
11211         case I40E_VSI_VMDQ2:
11212                 vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11213                 if (!vsi->num_tx_desc)
11214                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11215                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11216                 if (!vsi->num_rx_desc)
11217                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11218                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11219                 vsi->num_q_vectors = pf->num_vmdq_msix;
11220                 break;
11221
11222         case I40E_VSI_SRIOV:
11223                 vsi->alloc_queue_pairs = pf->num_vf_qps;
11224                 if (!vsi->num_tx_desc)
11225                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11226                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11227                 if (!vsi->num_rx_desc)
11228                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11229                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11230                 break;
11231
11232         default:
11233                 WARN_ON(1);
11234                 return -ENODATA;
11235         }
11236
11237         if (is_kdump_kernel()) {
11238                 vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11239                 vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11240         }
11241
11242         return 0;
11243 }
11244
11245 /**
11246  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11247  * @vsi: VSI pointer
11248  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11249  *
11250  * On error: returns error code (negative)
11251  * On success: returns 0
11252  **/
11253 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11254 {
11255         struct i40e_ring **next_rings;
11256         int size;
11257         int ret = 0;
11258
11259         /* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11260         size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11261                (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11262         vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11263         if (!vsi->tx_rings)
11264                 return -ENOMEM;
11265         next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11266         if (i40e_enabled_xdp_vsi(vsi)) {
11267                 vsi->xdp_rings = next_rings;
11268                 next_rings += vsi->alloc_queue_pairs;
11269         }
11270         vsi->rx_rings = next_rings;
11271
11272         if (alloc_qvectors) {
11273                 /* allocate memory for q_vector pointers */
11274                 size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11275                 vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11276                 if (!vsi->q_vectors) {
11277                         ret = -ENOMEM;
11278                         goto err_vectors;
11279                 }
11280         }
11281         return ret;
11282
11283 err_vectors:
11284         kfree(vsi->tx_rings);
11285         return ret;
11286 }
11287
11288 /**
11289  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11290  * @pf: board private structure
11291  * @type: type of VSI
11292  *
11293  * On error: returns error code (negative)
11294  * On success: returns vsi index in PF (positive)
11295  **/
11296 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11297 {
11298         int ret = -ENODEV;
11299         struct i40e_vsi *vsi;
11300         int vsi_idx;
11301         int i;
11302
11303         /* Need to protect the allocation of the VSIs at the PF level */
11304         mutex_lock(&pf->switch_mutex);
11305
11306         /* VSI list may be fragmented if VSI creation/destruction has
11307          * been happening.  We can afford to do a quick scan to look
11308          * for any free VSIs in the list.
11309          *
11310          * find next empty vsi slot, looping back around if necessary
11311          */
11312         i = pf->next_vsi;
11313         while (i < pf->num_alloc_vsi && pf->vsi[i])
11314                 i++;
11315         if (i >= pf->num_alloc_vsi) {
11316                 i = 0;
11317                 while (i < pf->next_vsi && pf->vsi[i])
11318                         i++;
11319         }
11320
11321         if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11322                 vsi_idx = i;             /* Found one! */
11323         } else {
11324                 ret = -ENODEV;
11325                 goto unlock_pf;  /* out of VSI slots! */
11326         }
11327         pf->next_vsi = ++i;
11328
11329         vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11330         if (!vsi) {
11331                 ret = -ENOMEM;
11332                 goto unlock_pf;
11333         }
11334         vsi->type = type;
11335         vsi->back = pf;
11336         set_bit(__I40E_VSI_DOWN, vsi->state);
11337         vsi->flags = 0;
11338         vsi->idx = vsi_idx;
11339         vsi->int_rate_limit = 0;
11340         vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11341                                 pf->rss_table_size : 64;
11342         vsi->netdev_registered = false;
11343         vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11344         hash_init(vsi->mac_filter_hash);
11345         vsi->irqs_ready = false;
11346
11347         if (type == I40E_VSI_MAIN) {
11348                 vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11349                 if (!vsi->af_xdp_zc_qps)
11350                         goto err_rings;
11351         }
11352
11353         ret = i40e_set_num_rings_in_vsi(vsi);
11354         if (ret)
11355                 goto err_rings;
11356
11357         ret = i40e_vsi_alloc_arrays(vsi, true);
11358         if (ret)
11359                 goto err_rings;
11360
11361         /* Setup default MSIX irq handler for VSI */
11362         i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11363
11364         /* Initialize VSI lock */
11365         spin_lock_init(&vsi->mac_filter_hash_lock);
11366         pf->vsi[vsi_idx] = vsi;
11367         ret = vsi_idx;
11368         goto unlock_pf;
11369
11370 err_rings:
11371         bitmap_free(vsi->af_xdp_zc_qps);
11372         pf->next_vsi = i - 1;
11373         kfree(vsi);
11374 unlock_pf:
11375         mutex_unlock(&pf->switch_mutex);
11376         return ret;
11377 }
11378
11379 /**
11380  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11381  * @vsi: VSI pointer
11382  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11383  *
11384  * On error: returns error code (negative)
11385  * On success: returns 0
11386  **/
11387 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11388 {
11389         /* free the ring and vector containers */
11390         if (free_qvectors) {
11391                 kfree(vsi->q_vectors);
11392                 vsi->q_vectors = NULL;
11393         }
11394         kfree(vsi->tx_rings);
11395         vsi->tx_rings = NULL;
11396         vsi->rx_rings = NULL;
11397         vsi->xdp_rings = NULL;
11398 }
11399
11400 /**
11401  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11402  * and lookup table
11403  * @vsi: Pointer to VSI structure
11404  */
11405 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11406 {
11407         if (!vsi)
11408                 return;
11409
11410         kfree(vsi->rss_hkey_user);
11411         vsi->rss_hkey_user = NULL;
11412
11413         kfree(vsi->rss_lut_user);
11414         vsi->rss_lut_user = NULL;
11415 }
11416
11417 /**
11418  * i40e_vsi_clear - Deallocate the VSI provided
11419  * @vsi: the VSI being un-configured
11420  **/
11421 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11422 {
11423         struct i40e_pf *pf;
11424
11425         if (!vsi)
11426                 return 0;
11427
11428         if (!vsi->back)
11429                 goto free_vsi;
11430         pf = vsi->back;
11431
11432         mutex_lock(&pf->switch_mutex);
11433         if (!pf->vsi[vsi->idx]) {
11434                 dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11435                         vsi->idx, vsi->idx, vsi->type);
11436                 goto unlock_vsi;
11437         }
11438
11439         if (pf->vsi[vsi->idx] != vsi) {
11440                 dev_err(&pf->pdev->dev,
11441                         "pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11442                         pf->vsi[vsi->idx]->idx,
11443                         pf->vsi[vsi->idx]->type,
11444                         vsi->idx, vsi->type);
11445                 goto unlock_vsi;
11446         }
11447
11448         /* updates the PF for this cleared vsi */
11449         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11450         i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11451
11452         bitmap_free(vsi->af_xdp_zc_qps);
11453         i40e_vsi_free_arrays(vsi, true);
11454         i40e_clear_rss_config_user(vsi);
11455
11456         pf->vsi[vsi->idx] = NULL;
11457         if (vsi->idx < pf->next_vsi)
11458                 pf->next_vsi = vsi->idx;
11459
11460 unlock_vsi:
11461         mutex_unlock(&pf->switch_mutex);
11462 free_vsi:
11463         kfree(vsi);
11464
11465         return 0;
11466 }
11467
11468 /**
11469  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11470  * @vsi: the VSI being cleaned
11471  **/
11472 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11473 {
11474         int i;
11475
11476         if (vsi->tx_rings && vsi->tx_rings[0]) {
11477                 for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11478                         kfree_rcu(vsi->tx_rings[i], rcu);
11479                         WRITE_ONCE(vsi->tx_rings[i], NULL);
11480                         WRITE_ONCE(vsi->rx_rings[i], NULL);
11481                         if (vsi->xdp_rings)
11482                                 WRITE_ONCE(vsi->xdp_rings[i], NULL);
11483                 }
11484         }
11485 }
11486
11487 /**
11488  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11489  * @vsi: the VSI being configured
11490  **/
11491 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11492 {
11493         int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11494         struct i40e_pf *pf = vsi->back;
11495         struct i40e_ring *ring;
11496
11497         /* Set basic values in the rings to be used later during open() */
11498         for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11499                 /* allocate space for both Tx and Rx in one shot */
11500                 ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11501                 if (!ring)
11502                         goto err_out;
11503
11504                 ring->queue_index = i;
11505                 ring->reg_idx = vsi->base_queue + i;
11506                 ring->ring_active = false;
11507                 ring->vsi = vsi;
11508                 ring->netdev = vsi->netdev;
11509                 ring->dev = &pf->pdev->dev;
11510                 ring->count = vsi->num_tx_desc;
11511                 ring->size = 0;
11512                 ring->dcb_tc = 0;
11513                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11514                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11515                 ring->itr_setting = pf->tx_itr_default;
11516                 WRITE_ONCE(vsi->tx_rings[i], ring++);
11517
11518                 if (!i40e_enabled_xdp_vsi(vsi))
11519                         goto setup_rx;
11520
11521                 ring->queue_index = vsi->alloc_queue_pairs + i;
11522                 ring->reg_idx = vsi->base_queue + ring->queue_index;
11523                 ring->ring_active = false;
11524                 ring->vsi = vsi;
11525                 ring->netdev = NULL;
11526                 ring->dev = &pf->pdev->dev;
11527                 ring->count = vsi->num_tx_desc;
11528                 ring->size = 0;
11529                 ring->dcb_tc = 0;
11530                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11531                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11532                 set_ring_xdp(ring);
11533                 ring->itr_setting = pf->tx_itr_default;
11534                 WRITE_ONCE(vsi->xdp_rings[i], ring++);
11535
11536 setup_rx:
11537                 ring->queue_index = i;
11538                 ring->reg_idx = vsi->base_queue + i;
11539                 ring->ring_active = false;
11540                 ring->vsi = vsi;
11541                 ring->netdev = vsi->netdev;
11542                 ring->dev = &pf->pdev->dev;
11543                 ring->count = vsi->num_rx_desc;
11544                 ring->size = 0;
11545                 ring->dcb_tc = 0;
11546                 ring->itr_setting = pf->rx_itr_default;
11547                 WRITE_ONCE(vsi->rx_rings[i], ring);
11548         }
11549
11550         return 0;
11551
11552 err_out:
11553         i40e_vsi_clear_rings(vsi);
11554         return -ENOMEM;
11555 }
11556
11557 /**
11558  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11559  * @pf: board private structure
11560  * @vectors: the number of MSI-X vectors to request
11561  *
11562  * Returns the number of vectors reserved, or error
11563  **/
11564 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11565 {
11566         vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11567                                         I40E_MIN_MSIX, vectors);
11568         if (vectors < 0) {
11569                 dev_info(&pf->pdev->dev,
11570                          "MSI-X vector reservation failed: %d\n", vectors);
11571                 vectors = 0;
11572         }
11573
11574         return vectors;
11575 }
11576
11577 /**
11578  * i40e_init_msix - Setup the MSIX capability
11579  * @pf: board private structure
11580  *
11581  * Work with the OS to set up the MSIX vectors needed.
11582  *
11583  * Returns the number of vectors reserved or negative on failure
11584  **/
11585 static int i40e_init_msix(struct i40e_pf *pf)
11586 {
11587         struct i40e_hw *hw = &pf->hw;
11588         int cpus, extra_vectors;
11589         int vectors_left;
11590         int v_budget, i;
11591         int v_actual;
11592         int iwarp_requested = 0;
11593
11594         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11595                 return -ENODEV;
11596
11597         /* The number of vectors we'll request will be comprised of:
11598          *   - Add 1 for "other" cause for Admin Queue events, etc.
11599          *   - The number of LAN queue pairs
11600          *      - Queues being used for RSS.
11601          *              We don't need as many as max_rss_size vectors.
11602          *              use rss_size instead in the calculation since that
11603          *              is governed by number of cpus in the system.
11604          *      - assumes symmetric Tx/Rx pairing
11605          *   - The number of VMDq pairs
11606          *   - The CPU count within the NUMA node if iWARP is enabled
11607          * Once we count this up, try the request.
11608          *
11609          * If we can't get what we want, we'll simplify to nearly nothing
11610          * and try again.  If that still fails, we punt.
11611          */
11612         vectors_left = hw->func_caps.num_msix_vectors;
11613         v_budget = 0;
11614
11615         /* reserve one vector for miscellaneous handler */
11616         if (vectors_left) {
11617                 v_budget++;
11618                 vectors_left--;
11619         }
11620
11621         /* reserve some vectors for the main PF traffic queues. Initially we
11622          * only reserve at most 50% of the available vectors, in the case that
11623          * the number of online CPUs is large. This ensures that we can enable
11624          * extra features as well. Once we've enabled the other features, we
11625          * will use any remaining vectors to reach as close as we can to the
11626          * number of online CPUs.
11627          */
11628         cpus = num_online_cpus();
11629         pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11630         vectors_left -= pf->num_lan_msix;
11631
11632         /* reserve one vector for sideband flow director */
11633         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11634                 if (vectors_left) {
11635                         pf->num_fdsb_msix = 1;
11636                         v_budget++;
11637                         vectors_left--;
11638                 } else {
11639                         pf->num_fdsb_msix = 0;
11640                 }
11641         }
11642
11643         /* can we reserve enough for iWARP? */
11644         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11645                 iwarp_requested = pf->num_iwarp_msix;
11646
11647                 if (!vectors_left)
11648                         pf->num_iwarp_msix = 0;
11649                 else if (vectors_left < pf->num_iwarp_msix)
11650                         pf->num_iwarp_msix = 1;
11651                 v_budget += pf->num_iwarp_msix;
11652                 vectors_left -= pf->num_iwarp_msix;
11653         }
11654
11655         /* any vectors left over go for VMDq support */
11656         if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11657                 if (!vectors_left) {
11658                         pf->num_vmdq_msix = 0;
11659                         pf->num_vmdq_qps = 0;
11660                 } else {
11661                         int vmdq_vecs_wanted =
11662                                 pf->num_vmdq_vsis * pf->num_vmdq_qps;
11663                         int vmdq_vecs =
11664                                 min_t(int, vectors_left, vmdq_vecs_wanted);
11665
11666                         /* if we're short on vectors for what's desired, we limit
11667                          * the queues per vmdq.  If this is still more than are
11668                          * available, the user will need to change the number of
11669                          * queues/vectors used by the PF later with the ethtool
11670                          * channels command
11671                          */
11672                         if (vectors_left < vmdq_vecs_wanted) {
11673                                 pf->num_vmdq_qps = 1;
11674                                 vmdq_vecs_wanted = pf->num_vmdq_vsis;
11675                                 vmdq_vecs = min_t(int,
11676                                                   vectors_left,
11677                                                   vmdq_vecs_wanted);
11678                         }
11679                         pf->num_vmdq_msix = pf->num_vmdq_qps;
11680
11681                         v_budget += vmdq_vecs;
11682                         vectors_left -= vmdq_vecs;
11683                 }
11684         }
11685
11686         /* On systems with a large number of SMP cores, we previously limited
11687          * the number of vectors for num_lan_msix to be at most 50% of the
11688          * available vectors, to allow for other features. Now, we add back
11689          * the remaining vectors. However, we ensure that the total
11690          * num_lan_msix will not exceed num_online_cpus(). To do this, we
11691          * calculate the number of vectors we can add without going over the
11692          * cap of CPUs. For systems with a small number of CPUs this will be
11693          * zero.
11694          */
11695         extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11696         pf->num_lan_msix += extra_vectors;
11697         vectors_left -= extra_vectors;
11698
11699         WARN(vectors_left < 0,
11700              "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11701
11702         v_budget += pf->num_lan_msix;
11703         pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11704                                    GFP_KERNEL);
11705         if (!pf->msix_entries)
11706                 return -ENOMEM;
11707
11708         for (i = 0; i < v_budget; i++)
11709                 pf->msix_entries[i].entry = i;
11710         v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11711
11712         if (v_actual < I40E_MIN_MSIX) {
11713                 pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11714                 kfree(pf->msix_entries);
11715                 pf->msix_entries = NULL;
11716                 pci_disable_msix(pf->pdev);
11717                 return -ENODEV;
11718
11719         } else if (v_actual == I40E_MIN_MSIX) {
11720                 /* Adjust for minimal MSIX use */
11721                 pf->num_vmdq_vsis = 0;
11722                 pf->num_vmdq_qps = 0;
11723                 pf->num_lan_qps = 1;
11724                 pf->num_lan_msix = 1;
11725
11726         } else if (v_actual != v_budget) {
11727                 /* If we have limited resources, we will start with no vectors
11728                  * for the special features and then allocate vectors to some
11729                  * of these features based on the policy and at the end disable
11730                  * the features that did not get any vectors.
11731                  */
11732                 int vec;
11733
11734                 dev_info(&pf->pdev->dev,
11735                          "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11736                          v_actual, v_budget);
11737                 /* reserve the misc vector */
11738                 vec = v_actual - 1;
11739
11740                 /* Scale vector usage down */
11741                 pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11742                 pf->num_vmdq_vsis = 1;
11743                 pf->num_vmdq_qps = 1;
11744
11745                 /* partition out the remaining vectors */
11746                 switch (vec) {
11747                 case 2:
11748                         pf->num_lan_msix = 1;
11749                         break;
11750                 case 3:
11751                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11752                                 pf->num_lan_msix = 1;
11753                                 pf->num_iwarp_msix = 1;
11754                         } else {
11755                                 pf->num_lan_msix = 2;
11756                         }
11757                         break;
11758                 default:
11759                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11760                                 pf->num_iwarp_msix = min_t(int, (vec / 3),
11761                                                  iwarp_requested);
11762                                 pf->num_vmdq_vsis = min_t(int, (vec / 3),
11763                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11764                         } else {
11765                                 pf->num_vmdq_vsis = min_t(int, (vec / 2),
11766                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11767                         }
11768                         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11769                                 pf->num_fdsb_msix = 1;
11770                                 vec--;
11771                         }
11772                         pf->num_lan_msix = min_t(int,
11773                                (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11774                                                               pf->num_lan_msix);
11775                         pf->num_lan_qps = pf->num_lan_msix;
11776                         break;
11777                 }
11778         }
11779
11780         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11781             (pf->num_fdsb_msix == 0)) {
11782                 dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11783                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11784                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11785         }
11786         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11787             (pf->num_vmdq_msix == 0)) {
11788                 dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11789                 pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11790         }
11791
11792         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11793             (pf->num_iwarp_msix == 0)) {
11794                 dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11795                 pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11796         }
11797         i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11798                    "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11799                    pf->num_lan_msix,
11800                    pf->num_vmdq_msix * pf->num_vmdq_vsis,
11801                    pf->num_fdsb_msix,
11802                    pf->num_iwarp_msix);
11803
11804         return v_actual;
11805 }
11806
11807 /**
11808  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11809  * @vsi: the VSI being configured
11810  * @v_idx: index of the vector in the vsi struct
11811  *
11812  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11813  **/
11814 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11815 {
11816         struct i40e_q_vector *q_vector;
11817
11818         /* allocate q_vector */
11819         q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11820         if (!q_vector)
11821                 return -ENOMEM;
11822
11823         q_vector->vsi = vsi;
11824         q_vector->v_idx = v_idx;
11825         cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11826
11827         if (vsi->netdev)
11828                 netif_napi_add(vsi->netdev, &q_vector->napi,
11829                                i40e_napi_poll, NAPI_POLL_WEIGHT);
11830
11831         /* tie q_vector and vsi together */
11832         vsi->q_vectors[v_idx] = q_vector;
11833
11834         return 0;
11835 }
11836
11837 /**
11838  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11839  * @vsi: the VSI being configured
11840  *
11841  * We allocate one q_vector per queue interrupt.  If allocation fails we
11842  * return -ENOMEM.
11843  **/
11844 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11845 {
11846         struct i40e_pf *pf = vsi->back;
11847         int err, v_idx, num_q_vectors;
11848
11849         /* if not MSIX, give the one vector only to the LAN VSI */
11850         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11851                 num_q_vectors = vsi->num_q_vectors;
11852         else if (vsi == pf->vsi[pf->lan_vsi])
11853                 num_q_vectors = 1;
11854         else
11855                 return -EINVAL;
11856
11857         for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
11858                 err = i40e_vsi_alloc_q_vector(vsi, v_idx);
11859                 if (err)
11860                         goto err_out;
11861         }
11862
11863         return 0;
11864
11865 err_out:
11866         while (v_idx--)
11867                 i40e_free_q_vector(vsi, v_idx);
11868
11869         return err;
11870 }
11871
11872 /**
11873  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
11874  * @pf: board private structure to initialize
11875  **/
11876 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
11877 {
11878         int vectors = 0;
11879         ssize_t size;
11880
11881         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11882                 vectors = i40e_init_msix(pf);
11883                 if (vectors < 0) {
11884                         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED   |
11885                                        I40E_FLAG_IWARP_ENABLED  |
11886                                        I40E_FLAG_RSS_ENABLED    |
11887                                        I40E_FLAG_DCB_CAPABLE    |
11888                                        I40E_FLAG_DCB_ENABLED    |
11889                                        I40E_FLAG_SRIOV_ENABLED  |
11890                                        I40E_FLAG_FD_SB_ENABLED  |
11891                                        I40E_FLAG_FD_ATR_ENABLED |
11892                                        I40E_FLAG_VMDQ_ENABLED);
11893                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11894
11895                         /* rework the queue expectations without MSIX */
11896                         i40e_determine_queue_usage(pf);
11897                 }
11898         }
11899
11900         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11901             (pf->flags & I40E_FLAG_MSI_ENABLED)) {
11902                 dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
11903                 vectors = pci_enable_msi(pf->pdev);
11904                 if (vectors < 0) {
11905                         dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
11906                                  vectors);
11907                         pf->flags &= ~I40E_FLAG_MSI_ENABLED;
11908                 }
11909                 vectors = 1;  /* one MSI or Legacy vector */
11910         }
11911
11912         if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
11913                 dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
11914
11915         /* set up vector assignment tracking */
11916         size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
11917         pf->irq_pile = kzalloc(size, GFP_KERNEL);
11918         if (!pf->irq_pile)
11919                 return -ENOMEM;
11920
11921         pf->irq_pile->num_entries = vectors;
11922
11923         /* track first vector for misc interrupts, ignore return */
11924         (void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
11925
11926         return 0;
11927 }
11928
11929 /**
11930  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
11931  * @pf: private board data structure
11932  *
11933  * Restore the interrupt scheme that was cleared when we suspended the
11934  * device. This should be called during resume to re-allocate the q_vectors
11935  * and reacquire IRQs.
11936  */
11937 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
11938 {
11939         int err, i;
11940
11941         /* We cleared the MSI and MSI-X flags when disabling the old interrupt
11942          * scheme. We need to re-enabled them here in order to attempt to
11943          * re-acquire the MSI or MSI-X vectors
11944          */
11945         pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
11946
11947         err = i40e_init_interrupt_scheme(pf);
11948         if (err)
11949                 return err;
11950
11951         /* Now that we've re-acquired IRQs, we need to remap the vectors and
11952          * rings together again.
11953          */
11954         for (i = 0; i < pf->num_alloc_vsi; i++) {
11955                 if (pf->vsi[i]) {
11956                         err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
11957                         if (err)
11958                                 goto err_unwind;
11959                         i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
11960                 }
11961         }
11962
11963         err = i40e_setup_misc_vector(pf);
11964         if (err)
11965                 goto err_unwind;
11966
11967         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
11968                 i40e_client_update_msix_info(pf);
11969
11970         return 0;
11971
11972 err_unwind:
11973         while (i--) {
11974                 if (pf->vsi[i])
11975                         i40e_vsi_free_q_vectors(pf->vsi[i]);
11976         }
11977
11978         return err;
11979 }
11980
11981 /**
11982  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
11983  * non queue events in recovery mode
11984  * @pf: board private structure
11985  *
11986  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
11987  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
11988  * This is handled differently than in recovery mode since no Tx/Rx resources
11989  * are being allocated.
11990  **/
11991 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
11992 {
11993         int err;
11994
11995         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11996                 err = i40e_setup_misc_vector(pf);
11997
11998                 if (err) {
11999                         dev_info(&pf->pdev->dev,
12000                                  "MSI-X misc vector request failed, error %d\n",
12001                                  err);
12002                         return err;
12003                 }
12004         } else {
12005                 u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
12006
12007                 err = request_irq(pf->pdev->irq, i40e_intr, flags,
12008                                   pf->int_name, pf);
12009
12010                 if (err) {
12011                         dev_info(&pf->pdev->dev,
12012                                  "MSI/legacy misc vector request failed, error %d\n",
12013                                  err);
12014                         return err;
12015                 }
12016                 i40e_enable_misc_int_causes(pf);
12017                 i40e_irq_dynamic_enable_icr0(pf);
12018         }
12019
12020         return 0;
12021 }
12022
12023 /**
12024  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12025  * @pf: board private structure
12026  *
12027  * This sets up the handler for MSIX 0, which is used to manage the
12028  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12029  * when in MSI or Legacy interrupt mode.
12030  **/
12031 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12032 {
12033         struct i40e_hw *hw = &pf->hw;
12034         int err = 0;
12035
12036         /* Only request the IRQ once, the first time through. */
12037         if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12038                 err = request_irq(pf->msix_entries[0].vector,
12039                                   i40e_intr, 0, pf->int_name, pf);
12040                 if (err) {
12041                         clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12042                         dev_info(&pf->pdev->dev,
12043                                  "request_irq for %s failed: %d\n",
12044                                  pf->int_name, err);
12045                         return -EFAULT;
12046                 }
12047         }
12048
12049         i40e_enable_misc_int_causes(pf);
12050
12051         /* associate no queues to the misc vector */
12052         wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12053         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12054
12055         i40e_flush(hw);
12056
12057         i40e_irq_dynamic_enable_icr0(pf);
12058
12059         return err;
12060 }
12061
12062 /**
12063  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12064  * @vsi: Pointer to vsi structure
12065  * @seed: Buffter to store the hash keys
12066  * @lut: Buffer to store the lookup table entries
12067  * @lut_size: Size of buffer to store the lookup table entries
12068  *
12069  * Return 0 on success, negative on failure
12070  */
12071 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12072                            u8 *lut, u16 lut_size)
12073 {
12074         struct i40e_pf *pf = vsi->back;
12075         struct i40e_hw *hw = &pf->hw;
12076         int ret = 0;
12077
12078         if (seed) {
12079                 ret = i40e_aq_get_rss_key(hw, vsi->id,
12080                         (struct i40e_aqc_get_set_rss_key_data *)seed);
12081                 if (ret) {
12082                         dev_info(&pf->pdev->dev,
12083                                  "Cannot get RSS key, err %s aq_err %s\n",
12084                                  i40e_stat_str(&pf->hw, ret),
12085                                  i40e_aq_str(&pf->hw,
12086                                              pf->hw.aq.asq_last_status));
12087                         return ret;
12088                 }
12089         }
12090
12091         if (lut) {
12092                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
12093
12094                 ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12095                 if (ret) {
12096                         dev_info(&pf->pdev->dev,
12097                                  "Cannot get RSS lut, err %s aq_err %s\n",
12098                                  i40e_stat_str(&pf->hw, ret),
12099                                  i40e_aq_str(&pf->hw,
12100                                              pf->hw.aq.asq_last_status));
12101                         return ret;
12102                 }
12103         }
12104
12105         return ret;
12106 }
12107
12108 /**
12109  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12110  * @vsi: Pointer to vsi structure
12111  * @seed: RSS hash seed
12112  * @lut: Lookup table
12113  * @lut_size: Lookup table size
12114  *
12115  * Returns 0 on success, negative on failure
12116  **/
12117 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12118                                const u8 *lut, u16 lut_size)
12119 {
12120         struct i40e_pf *pf = vsi->back;
12121         struct i40e_hw *hw = &pf->hw;
12122         u16 vf_id = vsi->vf_id;
12123         u8 i;
12124
12125         /* Fill out hash function seed */
12126         if (seed) {
12127                 u32 *seed_dw = (u32 *)seed;
12128
12129                 if (vsi->type == I40E_VSI_MAIN) {
12130                         for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12131                                 wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12132                 } else if (vsi->type == I40E_VSI_SRIOV) {
12133                         for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12134                                 wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12135                 } else {
12136                         dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12137                 }
12138         }
12139
12140         if (lut) {
12141                 u32 *lut_dw = (u32 *)lut;
12142
12143                 if (vsi->type == I40E_VSI_MAIN) {
12144                         if (lut_size != I40E_HLUT_ARRAY_SIZE)
12145                                 return -EINVAL;
12146                         for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12147                                 wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12148                 } else if (vsi->type == I40E_VSI_SRIOV) {
12149                         if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12150                                 return -EINVAL;
12151                         for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12152                                 wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12153                 } else {
12154                         dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12155                 }
12156         }
12157         i40e_flush(hw);
12158
12159         return 0;
12160 }
12161
12162 /**
12163  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12164  * @vsi: Pointer to VSI structure
12165  * @seed: Buffer to store the keys
12166  * @lut: Buffer to store the lookup table entries
12167  * @lut_size: Size of buffer to store the lookup table entries
12168  *
12169  * Returns 0 on success, negative on failure
12170  */
12171 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12172                             u8 *lut, u16 lut_size)
12173 {
12174         struct i40e_pf *pf = vsi->back;
12175         struct i40e_hw *hw = &pf->hw;
12176         u16 i;
12177
12178         if (seed) {
12179                 u32 *seed_dw = (u32 *)seed;
12180
12181                 for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12182                         seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12183         }
12184         if (lut) {
12185                 u32 *lut_dw = (u32 *)lut;
12186
12187                 if (lut_size != I40E_HLUT_ARRAY_SIZE)
12188                         return -EINVAL;
12189                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12190                         lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12191         }
12192
12193         return 0;
12194 }
12195
12196 /**
12197  * i40e_config_rss - Configure RSS keys and lut
12198  * @vsi: Pointer to VSI structure
12199  * @seed: RSS hash seed
12200  * @lut: Lookup table
12201  * @lut_size: Lookup table size
12202  *
12203  * Returns 0 on success, negative on failure
12204  */
12205 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12206 {
12207         struct i40e_pf *pf = vsi->back;
12208
12209         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12210                 return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12211         else
12212                 return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12213 }
12214
12215 /**
12216  * i40e_get_rss - Get RSS keys and lut
12217  * @vsi: Pointer to VSI structure
12218  * @seed: Buffer to store the keys
12219  * @lut: Buffer to store the lookup table entries
12220  * @lut_size: Size of buffer to store the lookup table entries
12221  *
12222  * Returns 0 on success, negative on failure
12223  */
12224 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12225 {
12226         struct i40e_pf *pf = vsi->back;
12227
12228         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12229                 return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12230         else
12231                 return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12232 }
12233
12234 /**
12235  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12236  * @pf: Pointer to board private structure
12237  * @lut: Lookup table
12238  * @rss_table_size: Lookup table size
12239  * @rss_size: Range of queue number for hashing
12240  */
12241 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12242                        u16 rss_table_size, u16 rss_size)
12243 {
12244         u16 i;
12245
12246         for (i = 0; i < rss_table_size; i++)
12247                 lut[i] = i % rss_size;
12248 }
12249
12250 /**
12251  * i40e_pf_config_rss - Prepare for RSS if used
12252  * @pf: board private structure
12253  **/
12254 static int i40e_pf_config_rss(struct i40e_pf *pf)
12255 {
12256         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12257         u8 seed[I40E_HKEY_ARRAY_SIZE];
12258         u8 *lut;
12259         struct i40e_hw *hw = &pf->hw;
12260         u32 reg_val;
12261         u64 hena;
12262         int ret;
12263
12264         /* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12265         hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12266                 ((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12267         hena |= i40e_pf_get_default_rss_hena(pf);
12268
12269         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12270         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12271
12272         /* Determine the RSS table size based on the hardware capabilities */
12273         reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12274         reg_val = (pf->rss_table_size == 512) ?
12275                         (reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12276                         (reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12277         i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12278
12279         /* Determine the RSS size of the VSI */
12280         if (!vsi->rss_size) {
12281                 u16 qcount;
12282                 /* If the firmware does something weird during VSI init, we
12283                  * could end up with zero TCs. Check for that to avoid
12284                  * divide-by-zero. It probably won't pass traffic, but it also
12285                  * won't panic.
12286                  */
12287                 qcount = vsi->num_queue_pairs /
12288                          (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12289                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12290         }
12291         if (!vsi->rss_size)
12292                 return -EINVAL;
12293
12294         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12295         if (!lut)
12296                 return -ENOMEM;
12297
12298         /* Use user configured lut if there is one, otherwise use default */
12299         if (vsi->rss_lut_user)
12300                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12301         else
12302                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12303
12304         /* Use user configured hash key if there is one, otherwise
12305          * use default.
12306          */
12307         if (vsi->rss_hkey_user)
12308                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12309         else
12310                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12311         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12312         kfree(lut);
12313
12314         return ret;
12315 }
12316
12317 /**
12318  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12319  * @pf: board private structure
12320  * @queue_count: the requested queue count for rss.
12321  *
12322  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12323  * count which may be different from the requested queue count.
12324  * Note: expects to be called while under rtnl_lock()
12325  **/
12326 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12327 {
12328         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12329         int new_rss_size;
12330
12331         if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12332                 return 0;
12333
12334         queue_count = min_t(int, queue_count, num_online_cpus());
12335         new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12336
12337         if (queue_count != vsi->num_queue_pairs) {
12338                 u16 qcount;
12339
12340                 vsi->req_queue_pairs = queue_count;
12341                 i40e_prep_for_reset(pf);
12342                 if (test_bit(__I40E_IN_REMOVE, pf->state))
12343                         return pf->alloc_rss_size;
12344
12345                 pf->alloc_rss_size = new_rss_size;
12346
12347                 i40e_reset_and_rebuild(pf, true, true);
12348
12349                 /* Discard the user configured hash keys and lut, if less
12350                  * queues are enabled.
12351                  */
12352                 if (queue_count < vsi->rss_size) {
12353                         i40e_clear_rss_config_user(vsi);
12354                         dev_dbg(&pf->pdev->dev,
12355                                 "discard user configured hash keys and lut\n");
12356                 }
12357
12358                 /* Reset vsi->rss_size, as number of enabled queues changed */
12359                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12360                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12361
12362                 i40e_pf_config_rss(pf);
12363         }
12364         dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12365                  vsi->req_queue_pairs, pf->rss_size_max);
12366         return pf->alloc_rss_size;
12367 }
12368
12369 /**
12370  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12371  * @pf: board private structure
12372  **/
12373 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
12374 {
12375         i40e_status status;
12376         bool min_valid, max_valid;
12377         u32 max_bw, min_bw;
12378
12379         status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12380                                            &min_valid, &max_valid);
12381
12382         if (!status) {
12383                 if (min_valid)
12384                         pf->min_bw = min_bw;
12385                 if (max_valid)
12386                         pf->max_bw = max_bw;
12387         }
12388
12389         return status;
12390 }
12391
12392 /**
12393  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12394  * @pf: board private structure
12395  **/
12396 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
12397 {
12398         struct i40e_aqc_configure_partition_bw_data bw_data;
12399         i40e_status status;
12400
12401         memset(&bw_data, 0, sizeof(bw_data));
12402
12403         /* Set the valid bit for this PF */
12404         bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12405         bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12406         bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12407
12408         /* Set the new bandwidths */
12409         status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12410
12411         return status;
12412 }
12413
12414 /**
12415  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12416  * @pf: board private structure
12417  **/
12418 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12419 {
12420         /* Commit temporary BW setting to permanent NVM image */
12421         enum i40e_admin_queue_err last_aq_status;
12422         i40e_status ret;
12423         u16 nvm_word;
12424
12425         if (pf->hw.partition_id != 1) {
12426                 dev_info(&pf->pdev->dev,
12427                          "Commit BW only works on partition 1! This is partition %d",
12428                          pf->hw.partition_id);
12429                 ret = I40E_NOT_SUPPORTED;
12430                 goto bw_commit_out;
12431         }
12432
12433         /* Acquire NVM for read access */
12434         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12435         last_aq_status = pf->hw.aq.asq_last_status;
12436         if (ret) {
12437                 dev_info(&pf->pdev->dev,
12438                          "Cannot acquire NVM for read access, err %s aq_err %s\n",
12439                          i40e_stat_str(&pf->hw, ret),
12440                          i40e_aq_str(&pf->hw, last_aq_status));
12441                 goto bw_commit_out;
12442         }
12443
12444         /* Read word 0x10 of NVM - SW compatibility word 1 */
12445         ret = i40e_aq_read_nvm(&pf->hw,
12446                                I40E_SR_NVM_CONTROL_WORD,
12447                                0x10, sizeof(nvm_word), &nvm_word,
12448                                false, NULL);
12449         /* Save off last admin queue command status before releasing
12450          * the NVM
12451          */
12452         last_aq_status = pf->hw.aq.asq_last_status;
12453         i40e_release_nvm(&pf->hw);
12454         if (ret) {
12455                 dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
12456                          i40e_stat_str(&pf->hw, ret),
12457                          i40e_aq_str(&pf->hw, last_aq_status));
12458                 goto bw_commit_out;
12459         }
12460
12461         /* Wait a bit for NVM release to complete */
12462         msleep(50);
12463
12464         /* Acquire NVM for write access */
12465         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12466         last_aq_status = pf->hw.aq.asq_last_status;
12467         if (ret) {
12468                 dev_info(&pf->pdev->dev,
12469                          "Cannot acquire NVM for write access, err %s aq_err %s\n",
12470                          i40e_stat_str(&pf->hw, ret),
12471                          i40e_aq_str(&pf->hw, last_aq_status));
12472                 goto bw_commit_out;
12473         }
12474         /* Write it back out unchanged to initiate update NVM,
12475          * which will force a write of the shadow (alt) RAM to
12476          * the NVM - thus storing the bandwidth values permanently.
12477          */
12478         ret = i40e_aq_update_nvm(&pf->hw,
12479                                  I40E_SR_NVM_CONTROL_WORD,
12480                                  0x10, sizeof(nvm_word),
12481                                  &nvm_word, true, 0, NULL);
12482         /* Save off last admin queue command status before releasing
12483          * the NVM
12484          */
12485         last_aq_status = pf->hw.aq.asq_last_status;
12486         i40e_release_nvm(&pf->hw);
12487         if (ret)
12488                 dev_info(&pf->pdev->dev,
12489                          "BW settings NOT SAVED, err %s aq_err %s\n",
12490                          i40e_stat_str(&pf->hw, ret),
12491                          i40e_aq_str(&pf->hw, last_aq_status));
12492 bw_commit_out:
12493
12494         return ret;
12495 }
12496
12497 /**
12498  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12499  * if total port shutdown feature is enabled for this PF
12500  * @pf: board private structure
12501  **/
12502 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12503 {
12504 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED        BIT(4)
12505 #define I40E_FEATURES_ENABLE_PTR                0x2A
12506 #define I40E_CURRENT_SETTING_PTR                0x2B
12507 #define I40E_LINK_BEHAVIOR_WORD_OFFSET          0x2D
12508 #define I40E_LINK_BEHAVIOR_WORD_LENGTH          0x1
12509 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED    BIT(0)
12510 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH      4
12511         i40e_status read_status = I40E_SUCCESS;
12512         u16 sr_emp_sr_settings_ptr = 0;
12513         u16 features_enable = 0;
12514         u16 link_behavior = 0;
12515         bool ret = false;
12516
12517         read_status = i40e_read_nvm_word(&pf->hw,
12518                                          I40E_SR_EMP_SR_SETTINGS_PTR,
12519                                          &sr_emp_sr_settings_ptr);
12520         if (read_status)
12521                 goto err_nvm;
12522         read_status = i40e_read_nvm_word(&pf->hw,
12523                                          sr_emp_sr_settings_ptr +
12524                                          I40E_FEATURES_ENABLE_PTR,
12525                                          &features_enable);
12526         if (read_status)
12527                 goto err_nvm;
12528         if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12529                 read_status = i40e_read_nvm_module_data(&pf->hw,
12530                                                         I40E_SR_EMP_SR_SETTINGS_PTR,
12531                                                         I40E_CURRENT_SETTING_PTR,
12532                                                         I40E_LINK_BEHAVIOR_WORD_OFFSET,
12533                                                         I40E_LINK_BEHAVIOR_WORD_LENGTH,
12534                                                         &link_behavior);
12535                 if (read_status)
12536                         goto err_nvm;
12537                 link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12538                 ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12539         }
12540         return ret;
12541
12542 err_nvm:
12543         dev_warn(&pf->pdev->dev,
12544                  "total-port-shutdown feature is off due to read nvm error: %s\n",
12545                  i40e_stat_str(&pf->hw, read_status));
12546         return ret;
12547 }
12548
12549 /**
12550  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12551  * @pf: board private structure to initialize
12552  *
12553  * i40e_sw_init initializes the Adapter private data structure.
12554  * Fields are initialized based on PCI device information and
12555  * OS network device settings (MTU size).
12556  **/
12557 static int i40e_sw_init(struct i40e_pf *pf)
12558 {
12559         int err = 0;
12560         int size;
12561         u16 pow;
12562
12563         /* Set default capability flags */
12564         pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12565                     I40E_FLAG_MSI_ENABLED     |
12566                     I40E_FLAG_MSIX_ENABLED;
12567
12568         /* Set default ITR */
12569         pf->rx_itr_default = I40E_ITR_RX_DEF;
12570         pf->tx_itr_default = I40E_ITR_TX_DEF;
12571
12572         /* Depending on PF configurations, it is possible that the RSS
12573          * maximum might end up larger than the available queues
12574          */
12575         pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12576         pf->alloc_rss_size = 1;
12577         pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12578         pf->rss_size_max = min_t(int, pf->rss_size_max,
12579                                  pf->hw.func_caps.num_tx_qp);
12580
12581         /* find the next higher power-of-2 of num cpus */
12582         pow = roundup_pow_of_two(num_online_cpus());
12583         pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12584
12585         if (pf->hw.func_caps.rss) {
12586                 pf->flags |= I40E_FLAG_RSS_ENABLED;
12587                 pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12588                                            num_online_cpus());
12589         }
12590
12591         /* MFP mode enabled */
12592         if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12593                 pf->flags |= I40E_FLAG_MFP_ENABLED;
12594                 dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12595                 if (i40e_get_partition_bw_setting(pf)) {
12596                         dev_warn(&pf->pdev->dev,
12597                                  "Could not get partition bw settings\n");
12598                 } else {
12599                         dev_info(&pf->pdev->dev,
12600                                  "Partition BW Min = %8.8x, Max = %8.8x\n",
12601                                  pf->min_bw, pf->max_bw);
12602
12603                         /* nudge the Tx scheduler */
12604                         i40e_set_partition_bw_setting(pf);
12605                 }
12606         }
12607
12608         if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12609             (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12610                 pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12611                 pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12612                 if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12613                     pf->hw.num_partitions > 1)
12614                         dev_info(&pf->pdev->dev,
12615                                  "Flow Director Sideband mode Disabled in MFP mode\n");
12616                 else
12617                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12618                 pf->fdir_pf_filter_count =
12619                                  pf->hw.func_caps.fd_filters_guaranteed;
12620                 pf->hw.fdir_shared_filter_count =
12621                                  pf->hw.func_caps.fd_filters_best_effort;
12622         }
12623
12624         if (pf->hw.mac.type == I40E_MAC_X722) {
12625                 pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12626                                     I40E_HW_128_QP_RSS_CAPABLE |
12627                                     I40E_HW_ATR_EVICT_CAPABLE |
12628                                     I40E_HW_WB_ON_ITR_CAPABLE |
12629                                     I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12630                                     I40E_HW_NO_PCI_LINK_CHECK |
12631                                     I40E_HW_USE_SET_LLDP_MIB |
12632                                     I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12633                                     I40E_HW_PTP_L4_CAPABLE |
12634                                     I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12635                                     I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12636
12637 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12638                 if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12639                     I40E_FDEVICT_PCTYPE_DEFAULT) {
12640                         dev_warn(&pf->pdev->dev,
12641                                  "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12642                         pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12643                 }
12644         } else if ((pf->hw.aq.api_maj_ver > 1) ||
12645                    ((pf->hw.aq.api_maj_ver == 1) &&
12646                     (pf->hw.aq.api_min_ver > 4))) {
12647                 /* Supported in FW API version higher than 1.4 */
12648                 pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12649         }
12650
12651         /* Enable HW ATR eviction if possible */
12652         if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12653                 pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12654
12655         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12656             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12657             (pf->hw.aq.fw_maj_ver < 4))) {
12658                 pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12659                 /* No DCB support  for FW < v4.33 */
12660                 pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12661         }
12662
12663         /* Disable FW LLDP if FW < v4.3 */
12664         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12665             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12666             (pf->hw.aq.fw_maj_ver < 4)))
12667                 pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12668
12669         /* Use the FW Set LLDP MIB API if FW > v4.40 */
12670         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12671             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12672             (pf->hw.aq.fw_maj_ver >= 5)))
12673                 pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12674
12675         /* Enable PTP L4 if FW > v6.0 */
12676         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12677             pf->hw.aq.fw_maj_ver >= 6)
12678                 pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12679
12680         if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12681                 pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12682                 pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12683                 pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12684         }
12685
12686         if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12687                 pf->flags |= I40E_FLAG_IWARP_ENABLED;
12688                 /* IWARP needs one extra vector for CQP just like MISC.*/
12689                 pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12690         }
12691         /* Stopping FW LLDP engine is supported on XL710 and X722
12692          * starting from FW versions determined in i40e_init_adminq.
12693          * Stopping the FW LLDP engine is not supported on XL710
12694          * if NPAR is functioning so unset this hw flag in this case.
12695          */
12696         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12697             pf->hw.func_caps.npar_enable &&
12698             (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12699                 pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12700
12701 #ifdef CONFIG_PCI_IOV
12702         if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12703                 pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12704                 pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12705                 pf->num_req_vfs = min_t(int,
12706                                         pf->hw.func_caps.num_vfs,
12707                                         I40E_MAX_VF_COUNT);
12708         }
12709 #endif /* CONFIG_PCI_IOV */
12710         pf->eeprom_version = 0xDEAD;
12711         pf->lan_veb = I40E_NO_VEB;
12712         pf->lan_vsi = I40E_NO_VSI;
12713
12714         /* By default FW has this off for performance reasons */
12715         pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12716
12717         /* set up queue assignment tracking */
12718         size = sizeof(struct i40e_lump_tracking)
12719                 + (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12720         pf->qp_pile = kzalloc(size, GFP_KERNEL);
12721         if (!pf->qp_pile) {
12722                 err = -ENOMEM;
12723                 goto sw_init_done;
12724         }
12725         pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12726
12727         pf->tx_timeout_recovery_level = 1;
12728
12729         if (pf->hw.mac.type != I40E_MAC_X722 &&
12730             i40e_is_total_port_shutdown_enabled(pf)) {
12731                 /* Link down on close must be on when total port shutdown
12732                  * is enabled for a given port
12733                  */
12734                 pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12735                               I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12736                 dev_info(&pf->pdev->dev,
12737                          "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12738         }
12739         mutex_init(&pf->switch_mutex);
12740
12741 sw_init_done:
12742         return err;
12743 }
12744
12745 /**
12746  * i40e_set_ntuple - set the ntuple feature flag and take action
12747  * @pf: board private structure to initialize
12748  * @features: the feature set that the stack is suggesting
12749  *
12750  * returns a bool to indicate if reset needs to happen
12751  **/
12752 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12753 {
12754         bool need_reset = false;
12755
12756         /* Check if Flow Director n-tuple support was enabled or disabled.  If
12757          * the state changed, we need to reset.
12758          */
12759         if (features & NETIF_F_NTUPLE) {
12760                 /* Enable filters and mark for reset */
12761                 if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12762                         need_reset = true;
12763                 /* enable FD_SB only if there is MSI-X vector and no cloud
12764                  * filters exist
12765                  */
12766                 if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12767                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12768                         pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12769                 }
12770         } else {
12771                 /* turn off filters, mark for reset and clear SW filter list */
12772                 if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12773                         need_reset = true;
12774                         i40e_fdir_filter_exit(pf);
12775                 }
12776                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12777                 clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12778                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12779
12780                 /* reset fd counters */
12781                 pf->fd_add_err = 0;
12782                 pf->fd_atr_cnt = 0;
12783                 /* if ATR was auto disabled it can be re-enabled. */
12784                 if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12785                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12786                             (I40E_DEBUG_FD & pf->hw.debug_mask))
12787                                 dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12788         }
12789         return need_reset;
12790 }
12791
12792 /**
12793  * i40e_clear_rss_lut - clear the rx hash lookup table
12794  * @vsi: the VSI being configured
12795  **/
12796 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12797 {
12798         struct i40e_pf *pf = vsi->back;
12799         struct i40e_hw *hw = &pf->hw;
12800         u16 vf_id = vsi->vf_id;
12801         u8 i;
12802
12803         if (vsi->type == I40E_VSI_MAIN) {
12804                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12805                         wr32(hw, I40E_PFQF_HLUT(i), 0);
12806         } else if (vsi->type == I40E_VSI_SRIOV) {
12807                 for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12808                         i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12809         } else {
12810                 dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12811         }
12812 }
12813
12814 /**
12815  * i40e_set_features - set the netdev feature flags
12816  * @netdev: ptr to the netdev being adjusted
12817  * @features: the feature set that the stack is suggesting
12818  * Note: expects to be called while under rtnl_lock()
12819  **/
12820 static int i40e_set_features(struct net_device *netdev,
12821                              netdev_features_t features)
12822 {
12823         struct i40e_netdev_priv *np = netdev_priv(netdev);
12824         struct i40e_vsi *vsi = np->vsi;
12825         struct i40e_pf *pf = vsi->back;
12826         bool need_reset;
12827
12828         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12829                 i40e_pf_config_rss(pf);
12830         else if (!(features & NETIF_F_RXHASH) &&
12831                  netdev->features & NETIF_F_RXHASH)
12832                 i40e_clear_rss_lut(vsi);
12833
12834         if (features & NETIF_F_HW_VLAN_CTAG_RX)
12835                 i40e_vlan_stripping_enable(vsi);
12836         else
12837                 i40e_vlan_stripping_disable(vsi);
12838
12839         if (!(features & NETIF_F_HW_TC) &&
12840             (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12841                 dev_err(&pf->pdev->dev,
12842                         "Offloaded tc filters active, can't turn hw_tc_offload off");
12843                 return -EINVAL;
12844         }
12845
12846         if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12847                 i40e_del_all_macvlans(vsi);
12848
12849         need_reset = i40e_set_ntuple(pf, features);
12850
12851         if (need_reset)
12852                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12853
12854         return 0;
12855 }
12856
12857 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12858                                     unsigned int table, unsigned int idx,
12859                                     struct udp_tunnel_info *ti)
12860 {
12861         struct i40e_netdev_priv *np = netdev_priv(netdev);
12862         struct i40e_hw *hw = &np->vsi->back->hw;
12863         u8 type, filter_index;
12864         i40e_status ret;
12865
12866         type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
12867                                                    I40E_AQC_TUNNEL_TYPE_NGE;
12868
12869         ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
12870                                      NULL);
12871         if (ret) {
12872                 netdev_info(netdev, "add UDP port failed, err %s aq_err %s\n",
12873                             i40e_stat_str(hw, ret),
12874                             i40e_aq_str(hw, hw->aq.asq_last_status));
12875                 return -EIO;
12876         }
12877
12878         udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
12879         return 0;
12880 }
12881
12882 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
12883                                       unsigned int table, unsigned int idx,
12884                                       struct udp_tunnel_info *ti)
12885 {
12886         struct i40e_netdev_priv *np = netdev_priv(netdev);
12887         struct i40e_hw *hw = &np->vsi->back->hw;
12888         i40e_status ret;
12889
12890         ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
12891         if (ret) {
12892                 netdev_info(netdev, "delete UDP port failed, err %s aq_err %s\n",
12893                             i40e_stat_str(hw, ret),
12894                             i40e_aq_str(hw, hw->aq.asq_last_status));
12895                 return -EIO;
12896         }
12897
12898         return 0;
12899 }
12900
12901 static int i40e_get_phys_port_id(struct net_device *netdev,
12902                                  struct netdev_phys_item_id *ppid)
12903 {
12904         struct i40e_netdev_priv *np = netdev_priv(netdev);
12905         struct i40e_pf *pf = np->vsi->back;
12906         struct i40e_hw *hw = &pf->hw;
12907
12908         if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
12909                 return -EOPNOTSUPP;
12910
12911         ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
12912         memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
12913
12914         return 0;
12915 }
12916
12917 /**
12918  * i40e_ndo_fdb_add - add an entry to the hardware database
12919  * @ndm: the input from the stack
12920  * @tb: pointer to array of nladdr (unused)
12921  * @dev: the net device pointer
12922  * @addr: the MAC address entry being added
12923  * @vid: VLAN ID
12924  * @flags: instructions from stack about fdb operation
12925  * @extack: netlink extended ack, unused currently
12926  */
12927 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
12928                             struct net_device *dev,
12929                             const unsigned char *addr, u16 vid,
12930                             u16 flags,
12931                             struct netlink_ext_ack *extack)
12932 {
12933         struct i40e_netdev_priv *np = netdev_priv(dev);
12934         struct i40e_pf *pf = np->vsi->back;
12935         int err = 0;
12936
12937         if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
12938                 return -EOPNOTSUPP;
12939
12940         if (vid) {
12941                 pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
12942                 return -EINVAL;
12943         }
12944
12945         /* Hardware does not support aging addresses so if a
12946          * ndm_state is given only allow permanent addresses
12947          */
12948         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
12949                 netdev_info(dev, "FDB only supports static addresses\n");
12950                 return -EINVAL;
12951         }
12952
12953         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
12954                 err = dev_uc_add_excl(dev, addr);
12955         else if (is_multicast_ether_addr(addr))
12956                 err = dev_mc_add_excl(dev, addr);
12957         else
12958                 err = -EINVAL;
12959
12960         /* Only return duplicate errors if NLM_F_EXCL is set */
12961         if (err == -EEXIST && !(flags & NLM_F_EXCL))
12962                 err = 0;
12963
12964         return err;
12965 }
12966
12967 /**
12968  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
12969  * @dev: the netdev being configured
12970  * @nlh: RTNL message
12971  * @flags: bridge flags
12972  * @extack: netlink extended ack
12973  *
12974  * Inserts a new hardware bridge if not already created and
12975  * enables the bridging mode requested (VEB or VEPA). If the
12976  * hardware bridge has already been inserted and the request
12977  * is to change the mode then that requires a PF reset to
12978  * allow rebuild of the components with required hardware
12979  * bridge mode enabled.
12980  *
12981  * Note: expects to be called while under rtnl_lock()
12982  **/
12983 static int i40e_ndo_bridge_setlink(struct net_device *dev,
12984                                    struct nlmsghdr *nlh,
12985                                    u16 flags,
12986                                    struct netlink_ext_ack *extack)
12987 {
12988         struct i40e_netdev_priv *np = netdev_priv(dev);
12989         struct i40e_vsi *vsi = np->vsi;
12990         struct i40e_pf *pf = vsi->back;
12991         struct i40e_veb *veb = NULL;
12992         struct nlattr *attr, *br_spec;
12993         int i, rem;
12994
12995         /* Only for PF VSI for now */
12996         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
12997                 return -EOPNOTSUPP;
12998
12999         /* Find the HW bridge for PF VSI */
13000         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13001                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13002                         veb = pf->veb[i];
13003         }
13004
13005         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13006
13007         nla_for_each_nested(attr, br_spec, rem) {
13008                 __u16 mode;
13009
13010                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
13011                         continue;
13012
13013                 mode = nla_get_u16(attr);
13014                 if ((mode != BRIDGE_MODE_VEPA) &&
13015                     (mode != BRIDGE_MODE_VEB))
13016                         return -EINVAL;
13017
13018                 /* Insert a new HW bridge */
13019                 if (!veb) {
13020                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13021                                              vsi->tc_config.enabled_tc);
13022                         if (veb) {
13023                                 veb->bridge_mode = mode;
13024                                 i40e_config_bridge_mode(veb);
13025                         } else {
13026                                 /* No Bridge HW offload available */
13027                                 return -ENOENT;
13028                         }
13029                         break;
13030                 } else if (mode != veb->bridge_mode) {
13031                         /* Existing HW bridge but different mode needs reset */
13032                         veb->bridge_mode = mode;
13033                         /* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13034                         if (mode == BRIDGE_MODE_VEB)
13035                                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
13036                         else
13037                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13038                         i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13039                         break;
13040                 }
13041         }
13042
13043         return 0;
13044 }
13045
13046 /**
13047  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13048  * @skb: skb buff
13049  * @pid: process id
13050  * @seq: RTNL message seq #
13051  * @dev: the netdev being configured
13052  * @filter_mask: unused
13053  * @nlflags: netlink flags passed in
13054  *
13055  * Return the mode in which the hardware bridge is operating in
13056  * i.e VEB or VEPA.
13057  **/
13058 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13059                                    struct net_device *dev,
13060                                    u32 __always_unused filter_mask,
13061                                    int nlflags)
13062 {
13063         struct i40e_netdev_priv *np = netdev_priv(dev);
13064         struct i40e_vsi *vsi = np->vsi;
13065         struct i40e_pf *pf = vsi->back;
13066         struct i40e_veb *veb = NULL;
13067         int i;
13068
13069         /* Only for PF VSI for now */
13070         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13071                 return -EOPNOTSUPP;
13072
13073         /* Find the HW bridge for the PF VSI */
13074         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13075                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13076                         veb = pf->veb[i];
13077         }
13078
13079         if (!veb)
13080                 return 0;
13081
13082         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13083                                        0, 0, nlflags, filter_mask, NULL);
13084 }
13085
13086 /**
13087  * i40e_features_check - Validate encapsulated packet conforms to limits
13088  * @skb: skb buff
13089  * @dev: This physical port's netdev
13090  * @features: Offload features that the stack believes apply
13091  **/
13092 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13093                                              struct net_device *dev,
13094                                              netdev_features_t features)
13095 {
13096         size_t len;
13097
13098         /* No point in doing any of this if neither checksum nor GSO are
13099          * being requested for this frame.  We can rule out both by just
13100          * checking for CHECKSUM_PARTIAL
13101          */
13102         if (skb->ip_summed != CHECKSUM_PARTIAL)
13103                 return features;
13104
13105         /* We cannot support GSO if the MSS is going to be less than
13106          * 64 bytes.  If it is then we need to drop support for GSO.
13107          */
13108         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13109                 features &= ~NETIF_F_GSO_MASK;
13110
13111         /* MACLEN can support at most 63 words */
13112         len = skb_network_header(skb) - skb->data;
13113         if (len & ~(63 * 2))
13114                 goto out_err;
13115
13116         /* IPLEN and EIPLEN can support at most 127 dwords */
13117         len = skb_transport_header(skb) - skb_network_header(skb);
13118         if (len & ~(127 * 4))
13119                 goto out_err;
13120
13121         if (skb->encapsulation) {
13122                 /* L4TUNLEN can support 127 words */
13123                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
13124                 if (len & ~(127 * 2))
13125                         goto out_err;
13126
13127                 /* IPLEN can support at most 127 dwords */
13128                 len = skb_inner_transport_header(skb) -
13129                       skb_inner_network_header(skb);
13130                 if (len & ~(127 * 4))
13131                         goto out_err;
13132         }
13133
13134         /* No need to validate L4LEN as TCP is the only protocol with a
13135          * a flexible value and we support all possible values supported
13136          * by TCP, which is at most 15 dwords
13137          */
13138
13139         return features;
13140 out_err:
13141         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13142 }
13143
13144 /**
13145  * i40e_xdp_setup - add/remove an XDP program
13146  * @vsi: VSI to changed
13147  * @prog: XDP program
13148  * @extack: netlink extended ack
13149  **/
13150 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13151                           struct netlink_ext_ack *extack)
13152 {
13153         int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
13154         struct i40e_pf *pf = vsi->back;
13155         struct bpf_prog *old_prog;
13156         bool need_reset;
13157         int i;
13158
13159         /* Don't allow frames that span over multiple buffers */
13160         if (frame_size > vsi->rx_buf_len) {
13161                 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
13162                 return -EINVAL;
13163         }
13164
13165         /* When turning XDP on->off/off->on we reset and rebuild the rings. */
13166         need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13167
13168         if (need_reset)
13169                 i40e_prep_for_reset(pf);
13170
13171         /* VSI shall be deleted in a moment, just return EINVAL */
13172         if (test_bit(__I40E_IN_REMOVE, pf->state))
13173                 return -EINVAL;
13174
13175         old_prog = xchg(&vsi->xdp_prog, prog);
13176
13177         if (need_reset) {
13178                 if (!prog)
13179                         /* Wait until ndo_xsk_wakeup completes. */
13180                         synchronize_rcu();
13181                 i40e_reset_and_rebuild(pf, true, true);
13182         }
13183
13184         for (i = 0; i < vsi->num_queue_pairs; i++)
13185                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13186
13187         if (old_prog)
13188                 bpf_prog_put(old_prog);
13189
13190         /* Kick start the NAPI context if there is an AF_XDP socket open
13191          * on that queue id. This so that receiving will start.
13192          */
13193         if (need_reset && prog)
13194                 for (i = 0; i < vsi->num_queue_pairs; i++)
13195                         if (vsi->xdp_rings[i]->xsk_pool)
13196                                 (void)i40e_xsk_wakeup(vsi->netdev, i,
13197                                                       XDP_WAKEUP_RX);
13198
13199         return 0;
13200 }
13201
13202 /**
13203  * i40e_enter_busy_conf - Enters busy config state
13204  * @vsi: vsi
13205  *
13206  * Returns 0 on success, <0 for failure.
13207  **/
13208 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13209 {
13210         struct i40e_pf *pf = vsi->back;
13211         int timeout = 50;
13212
13213         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13214                 timeout--;
13215                 if (!timeout)
13216                         return -EBUSY;
13217                 usleep_range(1000, 2000);
13218         }
13219
13220         return 0;
13221 }
13222
13223 /**
13224  * i40e_exit_busy_conf - Exits busy config state
13225  * @vsi: vsi
13226  **/
13227 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13228 {
13229         struct i40e_pf *pf = vsi->back;
13230
13231         clear_bit(__I40E_CONFIG_BUSY, pf->state);
13232 }
13233
13234 /**
13235  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13236  * @vsi: vsi
13237  * @queue_pair: queue pair
13238  **/
13239 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13240 {
13241         memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13242                sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13243         memset(&vsi->tx_rings[queue_pair]->stats, 0,
13244                sizeof(vsi->tx_rings[queue_pair]->stats));
13245         if (i40e_enabled_xdp_vsi(vsi)) {
13246                 memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13247                        sizeof(vsi->xdp_rings[queue_pair]->stats));
13248         }
13249 }
13250
13251 /**
13252  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13253  * @vsi: vsi
13254  * @queue_pair: queue pair
13255  **/
13256 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13257 {
13258         i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13259         if (i40e_enabled_xdp_vsi(vsi)) {
13260                 /* Make sure that in-progress ndo_xdp_xmit calls are
13261                  * completed.
13262                  */
13263                 synchronize_rcu();
13264                 i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13265         }
13266         i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13267 }
13268
13269 /**
13270  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13271  * @vsi: vsi
13272  * @queue_pair: queue pair
13273  * @enable: true for enable, false for disable
13274  **/
13275 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13276                                         bool enable)
13277 {
13278         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13279         struct i40e_q_vector *q_vector = rxr->q_vector;
13280
13281         if (!vsi->netdev)
13282                 return;
13283
13284         /* All rings in a qp belong to the same qvector. */
13285         if (q_vector->rx.ring || q_vector->tx.ring) {
13286                 if (enable)
13287                         napi_enable(&q_vector->napi);
13288                 else
13289                         napi_disable(&q_vector->napi);
13290         }
13291 }
13292
13293 /**
13294  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13295  * @vsi: vsi
13296  * @queue_pair: queue pair
13297  * @enable: true for enable, false for disable
13298  *
13299  * Returns 0 on success, <0 on failure.
13300  **/
13301 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13302                                         bool enable)
13303 {
13304         struct i40e_pf *pf = vsi->back;
13305         int pf_q, ret = 0;
13306
13307         pf_q = vsi->base_queue + queue_pair;
13308         ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13309                                      false /*is xdp*/, enable);
13310         if (ret) {
13311                 dev_info(&pf->pdev->dev,
13312                          "VSI seid %d Tx ring %d %sable timeout\n",
13313                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13314                 return ret;
13315         }
13316
13317         i40e_control_rx_q(pf, pf_q, enable);
13318         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13319         if (ret) {
13320                 dev_info(&pf->pdev->dev,
13321                          "VSI seid %d Rx ring %d %sable timeout\n",
13322                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13323                 return ret;
13324         }
13325
13326         /* Due to HW errata, on Rx disable only, the register can
13327          * indicate done before it really is. Needs 50ms to be sure
13328          */
13329         if (!enable)
13330                 mdelay(50);
13331
13332         if (!i40e_enabled_xdp_vsi(vsi))
13333                 return ret;
13334
13335         ret = i40e_control_wait_tx_q(vsi->seid, pf,
13336                                      pf_q + vsi->alloc_queue_pairs,
13337                                      true /*is xdp*/, enable);
13338         if (ret) {
13339                 dev_info(&pf->pdev->dev,
13340                          "VSI seid %d XDP Tx ring %d %sable timeout\n",
13341                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13342         }
13343
13344         return ret;
13345 }
13346
13347 /**
13348  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13349  * @vsi: vsi
13350  * @queue_pair: queue_pair
13351  **/
13352 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13353 {
13354         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13355         struct i40e_pf *pf = vsi->back;
13356         struct i40e_hw *hw = &pf->hw;
13357
13358         /* All rings in a qp belong to the same qvector. */
13359         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13360                 i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13361         else
13362                 i40e_irq_dynamic_enable_icr0(pf);
13363
13364         i40e_flush(hw);
13365 }
13366
13367 /**
13368  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13369  * @vsi: vsi
13370  * @queue_pair: queue_pair
13371  **/
13372 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13373 {
13374         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13375         struct i40e_pf *pf = vsi->back;
13376         struct i40e_hw *hw = &pf->hw;
13377
13378         /* For simplicity, instead of removing the qp interrupt causes
13379          * from the interrupt linked list, we simply disable the interrupt, and
13380          * leave the list intact.
13381          *
13382          * All rings in a qp belong to the same qvector.
13383          */
13384         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13385                 u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13386
13387                 wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13388                 i40e_flush(hw);
13389                 synchronize_irq(pf->msix_entries[intpf].vector);
13390         } else {
13391                 /* Legacy and MSI mode - this stops all interrupt handling */
13392                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13393                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13394                 i40e_flush(hw);
13395                 synchronize_irq(pf->pdev->irq);
13396         }
13397 }
13398
13399 /**
13400  * i40e_queue_pair_disable - Disables a queue pair
13401  * @vsi: vsi
13402  * @queue_pair: queue pair
13403  *
13404  * Returns 0 on success, <0 on failure.
13405  **/
13406 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13407 {
13408         int err;
13409
13410         err = i40e_enter_busy_conf(vsi);
13411         if (err)
13412                 return err;
13413
13414         i40e_queue_pair_disable_irq(vsi, queue_pair);
13415         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13416         i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13417         i40e_queue_pair_clean_rings(vsi, queue_pair);
13418         i40e_queue_pair_reset_stats(vsi, queue_pair);
13419
13420         return err;
13421 }
13422
13423 /**
13424  * i40e_queue_pair_enable - Enables a queue pair
13425  * @vsi: vsi
13426  * @queue_pair: queue pair
13427  *
13428  * Returns 0 on success, <0 on failure.
13429  **/
13430 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13431 {
13432         int err;
13433
13434         err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13435         if (err)
13436                 return err;
13437
13438         if (i40e_enabled_xdp_vsi(vsi)) {
13439                 err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13440                 if (err)
13441                         return err;
13442         }
13443
13444         err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13445         if (err)
13446                 return err;
13447
13448         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13449         i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13450         i40e_queue_pair_enable_irq(vsi, queue_pair);
13451
13452         i40e_exit_busy_conf(vsi);
13453
13454         return err;
13455 }
13456
13457 /**
13458  * i40e_xdp - implements ndo_bpf for i40e
13459  * @dev: netdevice
13460  * @xdp: XDP command
13461  **/
13462 static int i40e_xdp(struct net_device *dev,
13463                     struct netdev_bpf *xdp)
13464 {
13465         struct i40e_netdev_priv *np = netdev_priv(dev);
13466         struct i40e_vsi *vsi = np->vsi;
13467
13468         if (vsi->type != I40E_VSI_MAIN)
13469                 return -EINVAL;
13470
13471         switch (xdp->command) {
13472         case XDP_SETUP_PROG:
13473                 return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13474         case XDP_SETUP_XSK_POOL:
13475                 return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13476                                            xdp->xsk.queue_id);
13477         default:
13478                 return -EINVAL;
13479         }
13480 }
13481
13482 static const struct net_device_ops i40e_netdev_ops = {
13483         .ndo_open               = i40e_open,
13484         .ndo_stop               = i40e_close,
13485         .ndo_start_xmit         = i40e_lan_xmit_frame,
13486         .ndo_get_stats64        = i40e_get_netdev_stats_struct,
13487         .ndo_set_rx_mode        = i40e_set_rx_mode,
13488         .ndo_validate_addr      = eth_validate_addr,
13489         .ndo_set_mac_address    = i40e_set_mac,
13490         .ndo_change_mtu         = i40e_change_mtu,
13491         .ndo_eth_ioctl          = i40e_ioctl,
13492         .ndo_tx_timeout         = i40e_tx_timeout,
13493         .ndo_vlan_rx_add_vid    = i40e_vlan_rx_add_vid,
13494         .ndo_vlan_rx_kill_vid   = i40e_vlan_rx_kill_vid,
13495 #ifdef CONFIG_NET_POLL_CONTROLLER
13496         .ndo_poll_controller    = i40e_netpoll,
13497 #endif
13498         .ndo_setup_tc           = __i40e_setup_tc,
13499         .ndo_select_queue       = i40e_lan_select_queue,
13500         .ndo_set_features       = i40e_set_features,
13501         .ndo_set_vf_mac         = i40e_ndo_set_vf_mac,
13502         .ndo_set_vf_vlan        = i40e_ndo_set_vf_port_vlan,
13503         .ndo_get_vf_stats       = i40e_get_vf_stats,
13504         .ndo_set_vf_rate        = i40e_ndo_set_vf_bw,
13505         .ndo_get_vf_config      = i40e_ndo_get_vf_config,
13506         .ndo_set_vf_link_state  = i40e_ndo_set_vf_link_state,
13507         .ndo_set_vf_spoofchk    = i40e_ndo_set_vf_spoofchk,
13508         .ndo_set_vf_trust       = i40e_ndo_set_vf_trust,
13509         .ndo_get_phys_port_id   = i40e_get_phys_port_id,
13510         .ndo_fdb_add            = i40e_ndo_fdb_add,
13511         .ndo_features_check     = i40e_features_check,
13512         .ndo_bridge_getlink     = i40e_ndo_bridge_getlink,
13513         .ndo_bridge_setlink     = i40e_ndo_bridge_setlink,
13514         .ndo_bpf                = i40e_xdp,
13515         .ndo_xdp_xmit           = i40e_xdp_xmit,
13516         .ndo_xsk_wakeup         = i40e_xsk_wakeup,
13517         .ndo_dfwd_add_station   = i40e_fwd_add,
13518         .ndo_dfwd_del_station   = i40e_fwd_del,
13519 };
13520
13521 /**
13522  * i40e_config_netdev - Setup the netdev flags
13523  * @vsi: the VSI being configured
13524  *
13525  * Returns 0 on success, negative value on failure
13526  **/
13527 static int i40e_config_netdev(struct i40e_vsi *vsi)
13528 {
13529         struct i40e_pf *pf = vsi->back;
13530         struct i40e_hw *hw = &pf->hw;
13531         struct i40e_netdev_priv *np;
13532         struct net_device *netdev;
13533         u8 broadcast[ETH_ALEN];
13534         u8 mac_addr[ETH_ALEN];
13535         int etherdev_size;
13536         netdev_features_t hw_enc_features;
13537         netdev_features_t hw_features;
13538
13539         etherdev_size = sizeof(struct i40e_netdev_priv);
13540         netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13541         if (!netdev)
13542                 return -ENOMEM;
13543
13544         vsi->netdev = netdev;
13545         np = netdev_priv(netdev);
13546         np->vsi = vsi;
13547
13548         hw_enc_features = NETIF_F_SG                    |
13549                           NETIF_F_HW_CSUM               |
13550                           NETIF_F_HIGHDMA               |
13551                           NETIF_F_SOFT_FEATURES         |
13552                           NETIF_F_TSO                   |
13553                           NETIF_F_TSO_ECN               |
13554                           NETIF_F_TSO6                  |
13555                           NETIF_F_GSO_GRE               |
13556                           NETIF_F_GSO_GRE_CSUM          |
13557                           NETIF_F_GSO_PARTIAL           |
13558                           NETIF_F_GSO_IPXIP4            |
13559                           NETIF_F_GSO_IPXIP6            |
13560                           NETIF_F_GSO_UDP_TUNNEL        |
13561                           NETIF_F_GSO_UDP_TUNNEL_CSUM   |
13562                           NETIF_F_GSO_UDP_L4            |
13563                           NETIF_F_SCTP_CRC              |
13564                           NETIF_F_RXHASH                |
13565                           NETIF_F_RXCSUM                |
13566                           0;
13567
13568         if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13569                 netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13570
13571         netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13572
13573         netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13574
13575         netdev->hw_enc_features |= hw_enc_features;
13576
13577         /* record features VLANs can make use of */
13578         netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13579
13580 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |            \
13581                                    NETIF_F_GSO_GRE_CSUM |       \
13582                                    NETIF_F_GSO_IPXIP4 |         \
13583                                    NETIF_F_GSO_IPXIP6 |         \
13584                                    NETIF_F_GSO_UDP_TUNNEL |     \
13585                                    NETIF_F_GSO_UDP_TUNNEL_CSUM)
13586
13587         netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13588         netdev->features |= NETIF_F_GSO_PARTIAL |
13589                             I40E_GSO_PARTIAL_FEATURES;
13590
13591         netdev->mpls_features |= NETIF_F_SG;
13592         netdev->mpls_features |= NETIF_F_HW_CSUM;
13593         netdev->mpls_features |= NETIF_F_TSO;
13594         netdev->mpls_features |= NETIF_F_TSO6;
13595         netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13596
13597         /* enable macvlan offloads */
13598         netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13599
13600         hw_features = hw_enc_features           |
13601                       NETIF_F_HW_VLAN_CTAG_TX   |
13602                       NETIF_F_HW_VLAN_CTAG_RX;
13603
13604         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13605                 hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13606
13607         netdev->hw_features |= hw_features;
13608
13609         netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13610         netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13611
13612         netdev->features &= ~NETIF_F_HW_TC;
13613
13614         if (vsi->type == I40E_VSI_MAIN) {
13615                 SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13616                 ether_addr_copy(mac_addr, hw->mac.perm_addr);
13617                 /* The following steps are necessary for two reasons. First,
13618                  * some older NVM configurations load a default MAC-VLAN
13619                  * filter that will accept any tagged packet, and we want to
13620                  * replace this with a normal filter. Additionally, it is
13621                  * possible our MAC address was provided by the platform using
13622                  * Open Firmware or similar.
13623                  *
13624                  * Thus, we need to remove the default filter and install one
13625                  * specific to the MAC address.
13626                  */
13627                 i40e_rm_default_mac_filter(vsi, mac_addr);
13628                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13629                 i40e_add_mac_filter(vsi, mac_addr);
13630                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13631         } else {
13632                 /* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13633                  * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13634                  * the end, which is 4 bytes long, so force truncation of the
13635                  * original name by IFNAMSIZ - 4
13636                  */
13637                 snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13638                          IFNAMSIZ - 4,
13639                          pf->vsi[pf->lan_vsi]->netdev->name);
13640                 eth_random_addr(mac_addr);
13641
13642                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13643                 i40e_add_mac_filter(vsi, mac_addr);
13644                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13645         }
13646
13647         /* Add the broadcast filter so that we initially will receive
13648          * broadcast packets. Note that when a new VLAN is first added the
13649          * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13650          * specific filters as part of transitioning into "vlan" operation.
13651          * When more VLANs are added, the driver will copy each existing MAC
13652          * filter and add it for the new VLAN.
13653          *
13654          * Broadcast filters are handled specially by
13655          * i40e_sync_filters_subtask, as the driver must to set the broadcast
13656          * promiscuous bit instead of adding this directly as a MAC/VLAN
13657          * filter. The subtask will update the correct broadcast promiscuous
13658          * bits as VLANs become active or inactive.
13659          */
13660         eth_broadcast_addr(broadcast);
13661         spin_lock_bh(&vsi->mac_filter_hash_lock);
13662         i40e_add_mac_filter(vsi, broadcast);
13663         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13664
13665         eth_hw_addr_set(netdev, mac_addr);
13666         ether_addr_copy(netdev->perm_addr, mac_addr);
13667
13668         /* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13669         netdev->neigh_priv_len = sizeof(u32) * 4;
13670
13671         netdev->priv_flags |= IFF_UNICAST_FLT;
13672         netdev->priv_flags |= IFF_SUPP_NOFCS;
13673         /* Setup netdev TC information */
13674         i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13675
13676         netdev->netdev_ops = &i40e_netdev_ops;
13677         netdev->watchdog_timeo = 5 * HZ;
13678         i40e_set_ethtool_ops(netdev);
13679
13680         /* MTU range: 68 - 9706 */
13681         netdev->min_mtu = ETH_MIN_MTU;
13682         netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13683
13684         return 0;
13685 }
13686
13687 /**
13688  * i40e_vsi_delete - Delete a VSI from the switch
13689  * @vsi: the VSI being removed
13690  *
13691  * Returns 0 on success, negative value on failure
13692  **/
13693 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13694 {
13695         /* remove default VSI is not allowed */
13696         if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13697                 return;
13698
13699         i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13700 }
13701
13702 /**
13703  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13704  * @vsi: the VSI being queried
13705  *
13706  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13707  **/
13708 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13709 {
13710         struct i40e_veb *veb;
13711         struct i40e_pf *pf = vsi->back;
13712
13713         /* Uplink is not a bridge so default to VEB */
13714         if (vsi->veb_idx >= I40E_MAX_VEB)
13715                 return 1;
13716
13717         veb = pf->veb[vsi->veb_idx];
13718         if (!veb) {
13719                 dev_info(&pf->pdev->dev,
13720                          "There is no veb associated with the bridge\n");
13721                 return -ENOENT;
13722         }
13723
13724         /* Uplink is a bridge in VEPA mode */
13725         if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13726                 return 0;
13727         } else {
13728                 /* Uplink is a bridge in VEB mode */
13729                 return 1;
13730         }
13731
13732         /* VEPA is now default bridge, so return 0 */
13733         return 0;
13734 }
13735
13736 /**
13737  * i40e_add_vsi - Add a VSI to the switch
13738  * @vsi: the VSI being configured
13739  *
13740  * This initializes a VSI context depending on the VSI type to be added and
13741  * passes it down to the add_vsi aq command.
13742  **/
13743 static int i40e_add_vsi(struct i40e_vsi *vsi)
13744 {
13745         int ret = -ENODEV;
13746         struct i40e_pf *pf = vsi->back;
13747         struct i40e_hw *hw = &pf->hw;
13748         struct i40e_vsi_context ctxt;
13749         struct i40e_mac_filter *f;
13750         struct hlist_node *h;
13751         int bkt;
13752
13753         u8 enabled_tc = 0x1; /* TC0 enabled */
13754         int f_count = 0;
13755
13756         memset(&ctxt, 0, sizeof(ctxt));
13757         switch (vsi->type) {
13758         case I40E_VSI_MAIN:
13759                 /* The PF's main VSI is already setup as part of the
13760                  * device initialization, so we'll not bother with
13761                  * the add_vsi call, but we will retrieve the current
13762                  * VSI context.
13763                  */
13764                 ctxt.seid = pf->main_vsi_seid;
13765                 ctxt.pf_num = pf->hw.pf_id;
13766                 ctxt.vf_num = 0;
13767                 ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13768                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13769                 if (ret) {
13770                         dev_info(&pf->pdev->dev,
13771                                  "couldn't get PF vsi config, err %s aq_err %s\n",
13772                                  i40e_stat_str(&pf->hw, ret),
13773                                  i40e_aq_str(&pf->hw,
13774                                              pf->hw.aq.asq_last_status));
13775                         return -ENOENT;
13776                 }
13777                 vsi->info = ctxt.info;
13778                 vsi->info.valid_sections = 0;
13779
13780                 vsi->seid = ctxt.seid;
13781                 vsi->id = ctxt.vsi_number;
13782
13783                 enabled_tc = i40e_pf_get_tc_map(pf);
13784
13785                 /* Source pruning is enabled by default, so the flag is
13786                  * negative logic - if it's set, we need to fiddle with
13787                  * the VSI to disable source pruning.
13788                  */
13789                 if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13790                         memset(&ctxt, 0, sizeof(ctxt));
13791                         ctxt.seid = pf->main_vsi_seid;
13792                         ctxt.pf_num = pf->hw.pf_id;
13793                         ctxt.vf_num = 0;
13794                         ctxt.info.valid_sections |=
13795                                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13796                         ctxt.info.switch_id =
13797                                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13798                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13799                         if (ret) {
13800                                 dev_info(&pf->pdev->dev,
13801                                          "update vsi failed, err %s aq_err %s\n",
13802                                          i40e_stat_str(&pf->hw, ret),
13803                                          i40e_aq_str(&pf->hw,
13804                                                      pf->hw.aq.asq_last_status));
13805                                 ret = -ENOENT;
13806                                 goto err;
13807                         }
13808                 }
13809
13810                 /* MFP mode setup queue map and update VSI */
13811                 if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
13812                     !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13813                         memset(&ctxt, 0, sizeof(ctxt));
13814                         ctxt.seid = pf->main_vsi_seid;
13815                         ctxt.pf_num = pf->hw.pf_id;
13816                         ctxt.vf_num = 0;
13817                         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13818                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13819                         if (ret) {
13820                                 dev_info(&pf->pdev->dev,
13821                                          "update vsi failed, err %s aq_err %s\n",
13822                                          i40e_stat_str(&pf->hw, ret),
13823                                          i40e_aq_str(&pf->hw,
13824                                                     pf->hw.aq.asq_last_status));
13825                                 ret = -ENOENT;
13826                                 goto err;
13827                         }
13828                         /* update the local VSI info queue map */
13829                         i40e_vsi_update_queue_map(vsi, &ctxt);
13830                         vsi->info.valid_sections = 0;
13831                 } else {
13832                         /* Default/Main VSI is only enabled for TC0
13833                          * reconfigure it to enable all TCs that are
13834                          * available on the port in SFP mode.
13835                          * For MFP case the iSCSI PF would use this
13836                          * flow to enable LAN+iSCSI TC.
13837                          */
13838                         ret = i40e_vsi_config_tc(vsi, enabled_tc);
13839                         if (ret) {
13840                                 /* Single TC condition is not fatal,
13841                                  * message and continue
13842                                  */
13843                                 dev_info(&pf->pdev->dev,
13844                                          "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
13845                                          enabled_tc,
13846                                          i40e_stat_str(&pf->hw, ret),
13847                                          i40e_aq_str(&pf->hw,
13848                                                     pf->hw.aq.asq_last_status));
13849                         }
13850                 }
13851                 break;
13852
13853         case I40E_VSI_FDIR:
13854                 ctxt.pf_num = hw->pf_id;
13855                 ctxt.vf_num = 0;
13856                 ctxt.uplink_seid = vsi->uplink_seid;
13857                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13858                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13859                 if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
13860                     (i40e_is_vsi_uplink_mode_veb(vsi))) {
13861                         ctxt.info.valid_sections |=
13862                              cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13863                         ctxt.info.switch_id =
13864                            cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13865                 }
13866                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13867                 break;
13868
13869         case I40E_VSI_VMDQ2:
13870                 ctxt.pf_num = hw->pf_id;
13871                 ctxt.vf_num = 0;
13872                 ctxt.uplink_seid = vsi->uplink_seid;
13873                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13874                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13875
13876                 /* This VSI is connected to VEB so the switch_id
13877                  * should be set to zero by default.
13878                  */
13879                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13880                         ctxt.info.valid_sections |=
13881                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13882                         ctxt.info.switch_id =
13883                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13884                 }
13885
13886                 /* Setup the VSI tx/rx queue map for TC0 only for now */
13887                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13888                 break;
13889
13890         case I40E_VSI_SRIOV:
13891                 ctxt.pf_num = hw->pf_id;
13892                 ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
13893                 ctxt.uplink_seid = vsi->uplink_seid;
13894                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13895                 ctxt.flags = I40E_AQ_VSI_TYPE_VF;
13896
13897                 /* This VSI is connected to VEB so the switch_id
13898                  * should be set to zero by default.
13899                  */
13900                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13901                         ctxt.info.valid_sections |=
13902                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13903                         ctxt.info.switch_id =
13904                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13905                 }
13906
13907                 if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
13908                         ctxt.info.valid_sections |=
13909                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
13910                         ctxt.info.queueing_opt_flags |=
13911                                 (I40E_AQ_VSI_QUE_OPT_TCP_ENA |
13912                                  I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
13913                 }
13914
13915                 ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
13916                 ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
13917                 if (pf->vf[vsi->vf_id].spoofchk) {
13918                         ctxt.info.valid_sections |=
13919                                 cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
13920                         ctxt.info.sec_flags |=
13921                                 (I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
13922                                  I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
13923                 }
13924                 /* Setup the VSI tx/rx queue map for TC0 only for now */
13925                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13926                 break;
13927
13928         case I40E_VSI_IWARP:
13929                 /* send down message to iWARP */
13930                 break;
13931
13932         default:
13933                 return -ENODEV;
13934         }
13935
13936         if (vsi->type != I40E_VSI_MAIN) {
13937                 ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
13938                 if (ret) {
13939                         dev_info(&vsi->back->pdev->dev,
13940                                  "add vsi failed, err %s aq_err %s\n",
13941                                  i40e_stat_str(&pf->hw, ret),
13942                                  i40e_aq_str(&pf->hw,
13943                                              pf->hw.aq.asq_last_status));
13944                         ret = -ENOENT;
13945                         goto err;
13946                 }
13947                 vsi->info = ctxt.info;
13948                 vsi->info.valid_sections = 0;
13949                 vsi->seid = ctxt.seid;
13950                 vsi->id = ctxt.vsi_number;
13951         }
13952
13953         vsi->active_filters = 0;
13954         clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
13955         spin_lock_bh(&vsi->mac_filter_hash_lock);
13956         /* If macvlan filters already exist, force them to get loaded */
13957         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
13958                 f->state = I40E_FILTER_NEW;
13959                 f_count++;
13960         }
13961         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13962
13963         if (f_count) {
13964                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
13965                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
13966         }
13967
13968         /* Update VSI BW information */
13969         ret = i40e_vsi_get_bw_info(vsi);
13970         if (ret) {
13971                 dev_info(&pf->pdev->dev,
13972                          "couldn't get vsi bw info, err %s aq_err %s\n",
13973                          i40e_stat_str(&pf->hw, ret),
13974                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13975                 /* VSI is already added so not tearing that up */
13976                 ret = 0;
13977         }
13978
13979 err:
13980         return ret;
13981 }
13982
13983 /**
13984  * i40e_vsi_release - Delete a VSI and free its resources
13985  * @vsi: the VSI being removed
13986  *
13987  * Returns 0 on success or < 0 on error
13988  **/
13989 int i40e_vsi_release(struct i40e_vsi *vsi)
13990 {
13991         struct i40e_mac_filter *f;
13992         struct hlist_node *h;
13993         struct i40e_veb *veb = NULL;
13994         struct i40e_pf *pf;
13995         u16 uplink_seid;
13996         int i, n, bkt;
13997
13998         pf = vsi->back;
13999
14000         /* release of a VEB-owner or last VSI is not allowed */
14001         if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14002                 dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14003                          vsi->seid, vsi->uplink_seid);
14004                 return -ENODEV;
14005         }
14006         if (vsi == pf->vsi[pf->lan_vsi] &&
14007             !test_bit(__I40E_DOWN, pf->state)) {
14008                 dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14009                 return -ENODEV;
14010         }
14011         set_bit(__I40E_VSI_RELEASING, vsi->state);
14012         uplink_seid = vsi->uplink_seid;
14013         if (vsi->type != I40E_VSI_SRIOV) {
14014                 if (vsi->netdev_registered) {
14015                         vsi->netdev_registered = false;
14016                         if (vsi->netdev) {
14017                                 /* results in a call to i40e_close() */
14018                                 unregister_netdev(vsi->netdev);
14019                         }
14020                 } else {
14021                         i40e_vsi_close(vsi);
14022                 }
14023                 i40e_vsi_disable_irq(vsi);
14024         }
14025
14026         spin_lock_bh(&vsi->mac_filter_hash_lock);
14027
14028         /* clear the sync flag on all filters */
14029         if (vsi->netdev) {
14030                 __dev_uc_unsync(vsi->netdev, NULL);
14031                 __dev_mc_unsync(vsi->netdev, NULL);
14032         }
14033
14034         /* make sure any remaining filters are marked for deletion */
14035         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14036                 __i40e_del_filter(vsi, f);
14037
14038         spin_unlock_bh(&vsi->mac_filter_hash_lock);
14039
14040         i40e_sync_vsi_filters(vsi);
14041
14042         i40e_vsi_delete(vsi);
14043         i40e_vsi_free_q_vectors(vsi);
14044         if (vsi->netdev) {
14045                 free_netdev(vsi->netdev);
14046                 vsi->netdev = NULL;
14047         }
14048         i40e_vsi_clear_rings(vsi);
14049         i40e_vsi_clear(vsi);
14050
14051         /* If this was the last thing on the VEB, except for the
14052          * controlling VSI, remove the VEB, which puts the controlling
14053          * VSI onto the next level down in the switch.
14054          *
14055          * Well, okay, there's one more exception here: don't remove
14056          * the orphan VEBs yet.  We'll wait for an explicit remove request
14057          * from up the network stack.
14058          */
14059         for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14060                 if (pf->vsi[i] &&
14061                     pf->vsi[i]->uplink_seid == uplink_seid &&
14062                     (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14063                         n++;      /* count the VSIs */
14064                 }
14065         }
14066         for (i = 0; i < I40E_MAX_VEB; i++) {
14067                 if (!pf->veb[i])
14068                         continue;
14069                 if (pf->veb[i]->uplink_seid == uplink_seid)
14070                         n++;     /* count the VEBs */
14071                 if (pf->veb[i]->seid == uplink_seid)
14072                         veb = pf->veb[i];
14073         }
14074         if (n == 0 && veb && veb->uplink_seid != 0)
14075                 i40e_veb_release(veb);
14076
14077         return 0;
14078 }
14079
14080 /**
14081  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14082  * @vsi: ptr to the VSI
14083  *
14084  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14085  * corresponding SW VSI structure and initializes num_queue_pairs for the
14086  * newly allocated VSI.
14087  *
14088  * Returns 0 on success or negative on failure
14089  **/
14090 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14091 {
14092         int ret = -ENOENT;
14093         struct i40e_pf *pf = vsi->back;
14094
14095         if (vsi->q_vectors[0]) {
14096                 dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14097                          vsi->seid);
14098                 return -EEXIST;
14099         }
14100
14101         if (vsi->base_vector) {
14102                 dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14103                          vsi->seid, vsi->base_vector);
14104                 return -EEXIST;
14105         }
14106
14107         ret = i40e_vsi_alloc_q_vectors(vsi);
14108         if (ret) {
14109                 dev_info(&pf->pdev->dev,
14110                          "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14111                          vsi->num_q_vectors, vsi->seid, ret);
14112                 vsi->num_q_vectors = 0;
14113                 goto vector_setup_out;
14114         }
14115
14116         /* In Legacy mode, we do not have to get any other vector since we
14117          * piggyback on the misc/ICR0 for queue interrupts.
14118         */
14119         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
14120                 return ret;
14121         if (vsi->num_q_vectors)
14122                 vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14123                                                  vsi->num_q_vectors, vsi->idx);
14124         if (vsi->base_vector < 0) {
14125                 dev_info(&pf->pdev->dev,
14126                          "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14127                          vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14128                 i40e_vsi_free_q_vectors(vsi);
14129                 ret = -ENOENT;
14130                 goto vector_setup_out;
14131         }
14132
14133 vector_setup_out:
14134         return ret;
14135 }
14136
14137 /**
14138  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14139  * @vsi: pointer to the vsi.
14140  *
14141  * This re-allocates a vsi's queue resources.
14142  *
14143  * Returns pointer to the successfully allocated and configured VSI sw struct
14144  * on success, otherwise returns NULL on failure.
14145  **/
14146 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14147 {
14148         u16 alloc_queue_pairs;
14149         struct i40e_pf *pf;
14150         u8 enabled_tc;
14151         int ret;
14152
14153         if (!vsi)
14154                 return NULL;
14155
14156         pf = vsi->back;
14157
14158         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14159         i40e_vsi_clear_rings(vsi);
14160
14161         i40e_vsi_free_arrays(vsi, false);
14162         i40e_set_num_rings_in_vsi(vsi);
14163         ret = i40e_vsi_alloc_arrays(vsi, false);
14164         if (ret)
14165                 goto err_vsi;
14166
14167         alloc_queue_pairs = vsi->alloc_queue_pairs *
14168                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14169
14170         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14171         if (ret < 0) {
14172                 dev_info(&pf->pdev->dev,
14173                          "failed to get tracking for %d queues for VSI %d err %d\n",
14174                          alloc_queue_pairs, vsi->seid, ret);
14175                 goto err_vsi;
14176         }
14177         vsi->base_queue = ret;
14178
14179         /* Update the FW view of the VSI. Force a reset of TC and queue
14180          * layout configurations.
14181          */
14182         enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14183         pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14184         pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14185         i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14186         if (vsi->type == I40E_VSI_MAIN)
14187                 i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14188
14189         /* assign it some queues */
14190         ret = i40e_alloc_rings(vsi);
14191         if (ret)
14192                 goto err_rings;
14193
14194         /* map all of the rings to the q_vectors */
14195         i40e_vsi_map_rings_to_vectors(vsi);
14196         return vsi;
14197
14198 err_rings:
14199         i40e_vsi_free_q_vectors(vsi);
14200         if (vsi->netdev_registered) {
14201                 vsi->netdev_registered = false;
14202                 unregister_netdev(vsi->netdev);
14203                 free_netdev(vsi->netdev);
14204                 vsi->netdev = NULL;
14205         }
14206         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14207 err_vsi:
14208         i40e_vsi_clear(vsi);
14209         return NULL;
14210 }
14211
14212 /**
14213  * i40e_vsi_setup - Set up a VSI by a given type
14214  * @pf: board private structure
14215  * @type: VSI type
14216  * @uplink_seid: the switch element to link to
14217  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14218  *
14219  * This allocates the sw VSI structure and its queue resources, then add a VSI
14220  * to the identified VEB.
14221  *
14222  * Returns pointer to the successfully allocated and configure VSI sw struct on
14223  * success, otherwise returns NULL on failure.
14224  **/
14225 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14226                                 u16 uplink_seid, u32 param1)
14227 {
14228         struct i40e_vsi *vsi = NULL;
14229         struct i40e_veb *veb = NULL;
14230         u16 alloc_queue_pairs;
14231         int ret, i;
14232         int v_idx;
14233
14234         /* The requested uplink_seid must be either
14235          *     - the PF's port seid
14236          *              no VEB is needed because this is the PF
14237          *              or this is a Flow Director special case VSI
14238          *     - seid of an existing VEB
14239          *     - seid of a VSI that owns an existing VEB
14240          *     - seid of a VSI that doesn't own a VEB
14241          *              a new VEB is created and the VSI becomes the owner
14242          *     - seid of the PF VSI, which is what creates the first VEB
14243          *              this is a special case of the previous
14244          *
14245          * Find which uplink_seid we were given and create a new VEB if needed
14246          */
14247         for (i = 0; i < I40E_MAX_VEB; i++) {
14248                 if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14249                         veb = pf->veb[i];
14250                         break;
14251                 }
14252         }
14253
14254         if (!veb && uplink_seid != pf->mac_seid) {
14255
14256                 for (i = 0; i < pf->num_alloc_vsi; i++) {
14257                         if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14258                                 vsi = pf->vsi[i];
14259                                 break;
14260                         }
14261                 }
14262                 if (!vsi) {
14263                         dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14264                                  uplink_seid);
14265                         return NULL;
14266                 }
14267
14268                 if (vsi->uplink_seid == pf->mac_seid)
14269                         veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14270                                              vsi->tc_config.enabled_tc);
14271                 else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14272                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14273                                              vsi->tc_config.enabled_tc);
14274                 if (veb) {
14275                         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14276                                 dev_info(&vsi->back->pdev->dev,
14277                                          "New VSI creation error, uplink seid of LAN VSI expected.\n");
14278                                 return NULL;
14279                         }
14280                         /* We come up by default in VEPA mode if SRIOV is not
14281                          * already enabled, in which case we can't force VEPA
14282                          * mode.
14283                          */
14284                         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14285                                 veb->bridge_mode = BRIDGE_MODE_VEPA;
14286                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14287                         }
14288                         i40e_config_bridge_mode(veb);
14289                 }
14290                 for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14291                         if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14292                                 veb = pf->veb[i];
14293                 }
14294                 if (!veb) {
14295                         dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14296                         return NULL;
14297                 }
14298
14299                 vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14300                 uplink_seid = veb->seid;
14301         }
14302
14303         /* get vsi sw struct */
14304         v_idx = i40e_vsi_mem_alloc(pf, type);
14305         if (v_idx < 0)
14306                 goto err_alloc;
14307         vsi = pf->vsi[v_idx];
14308         if (!vsi)
14309                 goto err_alloc;
14310         vsi->type = type;
14311         vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14312
14313         if (type == I40E_VSI_MAIN)
14314                 pf->lan_vsi = v_idx;
14315         else if (type == I40E_VSI_SRIOV)
14316                 vsi->vf_id = param1;
14317         /* assign it some queues */
14318         alloc_queue_pairs = vsi->alloc_queue_pairs *
14319                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14320
14321         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14322         if (ret < 0) {
14323                 dev_info(&pf->pdev->dev,
14324                          "failed to get tracking for %d queues for VSI %d err=%d\n",
14325                          alloc_queue_pairs, vsi->seid, ret);
14326                 goto err_vsi;
14327         }
14328         vsi->base_queue = ret;
14329
14330         /* get a VSI from the hardware */
14331         vsi->uplink_seid = uplink_seid;
14332         ret = i40e_add_vsi(vsi);
14333         if (ret)
14334                 goto err_vsi;
14335
14336         switch (vsi->type) {
14337         /* setup the netdev if needed */
14338         case I40E_VSI_MAIN:
14339         case I40E_VSI_VMDQ2:
14340                 ret = i40e_config_netdev(vsi);
14341                 if (ret)
14342                         goto err_netdev;
14343                 ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14344                 if (ret)
14345                         goto err_netdev;
14346                 ret = register_netdev(vsi->netdev);
14347                 if (ret)
14348                         goto err_netdev;
14349                 vsi->netdev_registered = true;
14350                 netif_carrier_off(vsi->netdev);
14351 #ifdef CONFIG_I40E_DCB
14352                 /* Setup DCB netlink interface */
14353                 i40e_dcbnl_setup(vsi);
14354 #endif /* CONFIG_I40E_DCB */
14355                 fallthrough;
14356         case I40E_VSI_FDIR:
14357                 /* set up vectors and rings if needed */
14358                 ret = i40e_vsi_setup_vectors(vsi);
14359                 if (ret)
14360                         goto err_msix;
14361
14362                 ret = i40e_alloc_rings(vsi);
14363                 if (ret)
14364                         goto err_rings;
14365
14366                 /* map all of the rings to the q_vectors */
14367                 i40e_vsi_map_rings_to_vectors(vsi);
14368
14369                 i40e_vsi_reset_stats(vsi);
14370                 break;
14371         default:
14372                 /* no netdev or rings for the other VSI types */
14373                 break;
14374         }
14375
14376         if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14377             (vsi->type == I40E_VSI_VMDQ2)) {
14378                 ret = i40e_vsi_config_rss(vsi);
14379         }
14380         return vsi;
14381
14382 err_rings:
14383         i40e_vsi_free_q_vectors(vsi);
14384 err_msix:
14385         if (vsi->netdev_registered) {
14386                 vsi->netdev_registered = false;
14387                 unregister_netdev(vsi->netdev);
14388                 free_netdev(vsi->netdev);
14389                 vsi->netdev = NULL;
14390         }
14391 err_netdev:
14392         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14393 err_vsi:
14394         i40e_vsi_clear(vsi);
14395 err_alloc:
14396         return NULL;
14397 }
14398
14399 /**
14400  * i40e_veb_get_bw_info - Query VEB BW information
14401  * @veb: the veb to query
14402  *
14403  * Query the Tx scheduler BW configuration data for given VEB
14404  **/
14405 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14406 {
14407         struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14408         struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14409         struct i40e_pf *pf = veb->pf;
14410         struct i40e_hw *hw = &pf->hw;
14411         u32 tc_bw_max;
14412         int ret = 0;
14413         int i;
14414
14415         ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14416                                                   &bw_data, NULL);
14417         if (ret) {
14418                 dev_info(&pf->pdev->dev,
14419                          "query veb bw config failed, err %s aq_err %s\n",
14420                          i40e_stat_str(&pf->hw, ret),
14421                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14422                 goto out;
14423         }
14424
14425         ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14426                                                    &ets_data, NULL);
14427         if (ret) {
14428                 dev_info(&pf->pdev->dev,
14429                          "query veb bw ets config failed, err %s aq_err %s\n",
14430                          i40e_stat_str(&pf->hw, ret),
14431                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14432                 goto out;
14433         }
14434
14435         veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14436         veb->bw_max_quanta = ets_data.tc_bw_max;
14437         veb->is_abs_credits = bw_data.absolute_credits_enable;
14438         veb->enabled_tc = ets_data.tc_valid_bits;
14439         tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14440                     (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14441         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14442                 veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14443                 veb->bw_tc_limit_credits[i] =
14444                                         le16_to_cpu(bw_data.tc_bw_limits[i]);
14445                 veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14446         }
14447
14448 out:
14449         return ret;
14450 }
14451
14452 /**
14453  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14454  * @pf: board private structure
14455  *
14456  * On error: returns error code (negative)
14457  * On success: returns vsi index in PF (positive)
14458  **/
14459 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14460 {
14461         int ret = -ENOENT;
14462         struct i40e_veb *veb;
14463         int i;
14464
14465         /* Need to protect the allocation of switch elements at the PF level */
14466         mutex_lock(&pf->switch_mutex);
14467
14468         /* VEB list may be fragmented if VEB creation/destruction has
14469          * been happening.  We can afford to do a quick scan to look
14470          * for any free slots in the list.
14471          *
14472          * find next empty veb slot, looping back around if necessary
14473          */
14474         i = 0;
14475         while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14476                 i++;
14477         if (i >= I40E_MAX_VEB) {
14478                 ret = -ENOMEM;
14479                 goto err_alloc_veb;  /* out of VEB slots! */
14480         }
14481
14482         veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14483         if (!veb) {
14484                 ret = -ENOMEM;
14485                 goto err_alloc_veb;
14486         }
14487         veb->pf = pf;
14488         veb->idx = i;
14489         veb->enabled_tc = 1;
14490
14491         pf->veb[i] = veb;
14492         ret = i;
14493 err_alloc_veb:
14494         mutex_unlock(&pf->switch_mutex);
14495         return ret;
14496 }
14497
14498 /**
14499  * i40e_switch_branch_release - Delete a branch of the switch tree
14500  * @branch: where to start deleting
14501  *
14502  * This uses recursion to find the tips of the branch to be
14503  * removed, deleting until we get back to and can delete this VEB.
14504  **/
14505 static void i40e_switch_branch_release(struct i40e_veb *branch)
14506 {
14507         struct i40e_pf *pf = branch->pf;
14508         u16 branch_seid = branch->seid;
14509         u16 veb_idx = branch->idx;
14510         int i;
14511
14512         /* release any VEBs on this VEB - RECURSION */
14513         for (i = 0; i < I40E_MAX_VEB; i++) {
14514                 if (!pf->veb[i])
14515                         continue;
14516                 if (pf->veb[i]->uplink_seid == branch->seid)
14517                         i40e_switch_branch_release(pf->veb[i]);
14518         }
14519
14520         /* Release the VSIs on this VEB, but not the owner VSI.
14521          *
14522          * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14523          *       the VEB itself, so don't use (*branch) after this loop.
14524          */
14525         for (i = 0; i < pf->num_alloc_vsi; i++) {
14526                 if (!pf->vsi[i])
14527                         continue;
14528                 if (pf->vsi[i]->uplink_seid == branch_seid &&
14529                    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14530                         i40e_vsi_release(pf->vsi[i]);
14531                 }
14532         }
14533
14534         /* There's one corner case where the VEB might not have been
14535          * removed, so double check it here and remove it if needed.
14536          * This case happens if the veb was created from the debugfs
14537          * commands and no VSIs were added to it.
14538          */
14539         if (pf->veb[veb_idx])
14540                 i40e_veb_release(pf->veb[veb_idx]);
14541 }
14542
14543 /**
14544  * i40e_veb_clear - remove veb struct
14545  * @veb: the veb to remove
14546  **/
14547 static void i40e_veb_clear(struct i40e_veb *veb)
14548 {
14549         if (!veb)
14550                 return;
14551
14552         if (veb->pf) {
14553                 struct i40e_pf *pf = veb->pf;
14554
14555                 mutex_lock(&pf->switch_mutex);
14556                 if (pf->veb[veb->idx] == veb)
14557                         pf->veb[veb->idx] = NULL;
14558                 mutex_unlock(&pf->switch_mutex);
14559         }
14560
14561         kfree(veb);
14562 }
14563
14564 /**
14565  * i40e_veb_release - Delete a VEB and free its resources
14566  * @veb: the VEB being removed
14567  **/
14568 void i40e_veb_release(struct i40e_veb *veb)
14569 {
14570         struct i40e_vsi *vsi = NULL;
14571         struct i40e_pf *pf;
14572         int i, n = 0;
14573
14574         pf = veb->pf;
14575
14576         /* find the remaining VSI and check for extras */
14577         for (i = 0; i < pf->num_alloc_vsi; i++) {
14578                 if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14579                         n++;
14580                         vsi = pf->vsi[i];
14581                 }
14582         }
14583         if (n != 1) {
14584                 dev_info(&pf->pdev->dev,
14585                          "can't remove VEB %d with %d VSIs left\n",
14586                          veb->seid, n);
14587                 return;
14588         }
14589
14590         /* move the remaining VSI to uplink veb */
14591         vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14592         if (veb->uplink_seid) {
14593                 vsi->uplink_seid = veb->uplink_seid;
14594                 if (veb->uplink_seid == pf->mac_seid)
14595                         vsi->veb_idx = I40E_NO_VEB;
14596                 else
14597                         vsi->veb_idx = veb->veb_idx;
14598         } else {
14599                 /* floating VEB */
14600                 vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14601                 vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14602         }
14603
14604         i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14605         i40e_veb_clear(veb);
14606 }
14607
14608 /**
14609  * i40e_add_veb - create the VEB in the switch
14610  * @veb: the VEB to be instantiated
14611  * @vsi: the controlling VSI
14612  **/
14613 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14614 {
14615         struct i40e_pf *pf = veb->pf;
14616         bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14617         int ret;
14618
14619         ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14620                               veb->enabled_tc, false,
14621                               &veb->seid, enable_stats, NULL);
14622
14623         /* get a VEB from the hardware */
14624         if (ret) {
14625                 dev_info(&pf->pdev->dev,
14626                          "couldn't add VEB, err %s aq_err %s\n",
14627                          i40e_stat_str(&pf->hw, ret),
14628                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14629                 return -EPERM;
14630         }
14631
14632         /* get statistics counter */
14633         ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14634                                          &veb->stats_idx, NULL, NULL, NULL);
14635         if (ret) {
14636                 dev_info(&pf->pdev->dev,
14637                          "couldn't get VEB statistics idx, err %s aq_err %s\n",
14638                          i40e_stat_str(&pf->hw, ret),
14639                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14640                 return -EPERM;
14641         }
14642         ret = i40e_veb_get_bw_info(veb);
14643         if (ret) {
14644                 dev_info(&pf->pdev->dev,
14645                          "couldn't get VEB bw info, err %s aq_err %s\n",
14646                          i40e_stat_str(&pf->hw, ret),
14647                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14648                 i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14649                 return -ENOENT;
14650         }
14651
14652         vsi->uplink_seid = veb->seid;
14653         vsi->veb_idx = veb->idx;
14654         vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14655
14656         return 0;
14657 }
14658
14659 /**
14660  * i40e_veb_setup - Set up a VEB
14661  * @pf: board private structure
14662  * @flags: VEB setup flags
14663  * @uplink_seid: the switch element to link to
14664  * @vsi_seid: the initial VSI seid
14665  * @enabled_tc: Enabled TC bit-map
14666  *
14667  * This allocates the sw VEB structure and links it into the switch
14668  * It is possible and legal for this to be a duplicate of an already
14669  * existing VEB.  It is also possible for both uplink and vsi seids
14670  * to be zero, in order to create a floating VEB.
14671  *
14672  * Returns pointer to the successfully allocated VEB sw struct on
14673  * success, otherwise returns NULL on failure.
14674  **/
14675 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14676                                 u16 uplink_seid, u16 vsi_seid,
14677                                 u8 enabled_tc)
14678 {
14679         struct i40e_veb *veb, *uplink_veb = NULL;
14680         int vsi_idx, veb_idx;
14681         int ret;
14682
14683         /* if one seid is 0, the other must be 0 to create a floating relay */
14684         if ((uplink_seid == 0 || vsi_seid == 0) &&
14685             (uplink_seid + vsi_seid != 0)) {
14686                 dev_info(&pf->pdev->dev,
14687                          "one, not both seid's are 0: uplink=%d vsi=%d\n",
14688                          uplink_seid, vsi_seid);
14689                 return NULL;
14690         }
14691
14692         /* make sure there is such a vsi and uplink */
14693         for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14694                 if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14695                         break;
14696         if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14697                 dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14698                          vsi_seid);
14699                 return NULL;
14700         }
14701
14702         if (uplink_seid && uplink_seid != pf->mac_seid) {
14703                 for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14704                         if (pf->veb[veb_idx] &&
14705                             pf->veb[veb_idx]->seid == uplink_seid) {
14706                                 uplink_veb = pf->veb[veb_idx];
14707                                 break;
14708                         }
14709                 }
14710                 if (!uplink_veb) {
14711                         dev_info(&pf->pdev->dev,
14712                                  "uplink seid %d not found\n", uplink_seid);
14713                         return NULL;
14714                 }
14715         }
14716
14717         /* get veb sw struct */
14718         veb_idx = i40e_veb_mem_alloc(pf);
14719         if (veb_idx < 0)
14720                 goto err_alloc;
14721         veb = pf->veb[veb_idx];
14722         veb->flags = flags;
14723         veb->uplink_seid = uplink_seid;
14724         veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14725         veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14726
14727         /* create the VEB in the switch */
14728         ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14729         if (ret)
14730                 goto err_veb;
14731         if (vsi_idx == pf->lan_vsi)
14732                 pf->lan_veb = veb->idx;
14733
14734         return veb;
14735
14736 err_veb:
14737         i40e_veb_clear(veb);
14738 err_alloc:
14739         return NULL;
14740 }
14741
14742 /**
14743  * i40e_setup_pf_switch_element - set PF vars based on switch type
14744  * @pf: board private structure
14745  * @ele: element we are building info from
14746  * @num_reported: total number of elements
14747  * @printconfig: should we print the contents
14748  *
14749  * helper function to assist in extracting a few useful SEID values.
14750  **/
14751 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14752                                 struct i40e_aqc_switch_config_element_resp *ele,
14753                                 u16 num_reported, bool printconfig)
14754 {
14755         u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14756         u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14757         u8 element_type = ele->element_type;
14758         u16 seid = le16_to_cpu(ele->seid);
14759
14760         if (printconfig)
14761                 dev_info(&pf->pdev->dev,
14762                          "type=%d seid=%d uplink=%d downlink=%d\n",
14763                          element_type, seid, uplink_seid, downlink_seid);
14764
14765         switch (element_type) {
14766         case I40E_SWITCH_ELEMENT_TYPE_MAC:
14767                 pf->mac_seid = seid;
14768                 break;
14769         case I40E_SWITCH_ELEMENT_TYPE_VEB:
14770                 /* Main VEB? */
14771                 if (uplink_seid != pf->mac_seid)
14772                         break;
14773                 if (pf->lan_veb >= I40E_MAX_VEB) {
14774                         int v;
14775
14776                         /* find existing or else empty VEB */
14777                         for (v = 0; v < I40E_MAX_VEB; v++) {
14778                                 if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14779                                         pf->lan_veb = v;
14780                                         break;
14781                                 }
14782                         }
14783                         if (pf->lan_veb >= I40E_MAX_VEB) {
14784                                 v = i40e_veb_mem_alloc(pf);
14785                                 if (v < 0)
14786                                         break;
14787                                 pf->lan_veb = v;
14788                         }
14789                 }
14790                 if (pf->lan_veb >= I40E_MAX_VEB)
14791                         break;
14792
14793                 pf->veb[pf->lan_veb]->seid = seid;
14794                 pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14795                 pf->veb[pf->lan_veb]->pf = pf;
14796                 pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14797                 break;
14798         case I40E_SWITCH_ELEMENT_TYPE_VSI:
14799                 if (num_reported != 1)
14800                         break;
14801                 /* This is immediately after a reset so we can assume this is
14802                  * the PF's VSI
14803                  */
14804                 pf->mac_seid = uplink_seid;
14805                 pf->pf_seid = downlink_seid;
14806                 pf->main_vsi_seid = seid;
14807                 if (printconfig)
14808                         dev_info(&pf->pdev->dev,
14809                                  "pf_seid=%d main_vsi_seid=%d\n",
14810                                  pf->pf_seid, pf->main_vsi_seid);
14811                 break;
14812         case I40E_SWITCH_ELEMENT_TYPE_PF:
14813         case I40E_SWITCH_ELEMENT_TYPE_VF:
14814         case I40E_SWITCH_ELEMENT_TYPE_EMP:
14815         case I40E_SWITCH_ELEMENT_TYPE_BMC:
14816         case I40E_SWITCH_ELEMENT_TYPE_PE:
14817         case I40E_SWITCH_ELEMENT_TYPE_PA:
14818                 /* ignore these for now */
14819                 break;
14820         default:
14821                 dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14822                          element_type, seid);
14823                 break;
14824         }
14825 }
14826
14827 /**
14828  * i40e_fetch_switch_configuration - Get switch config from firmware
14829  * @pf: board private structure
14830  * @printconfig: should we print the contents
14831  *
14832  * Get the current switch configuration from the device and
14833  * extract a few useful SEID values.
14834  **/
14835 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14836 {
14837         struct i40e_aqc_get_switch_config_resp *sw_config;
14838         u16 next_seid = 0;
14839         int ret = 0;
14840         u8 *aq_buf;
14841         int i;
14842
14843         aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14844         if (!aq_buf)
14845                 return -ENOMEM;
14846
14847         sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14848         do {
14849                 u16 num_reported, num_total;
14850
14851                 ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14852                                                 I40E_AQ_LARGE_BUF,
14853                                                 &next_seid, NULL);
14854                 if (ret) {
14855                         dev_info(&pf->pdev->dev,
14856                                  "get switch config failed err %s aq_err %s\n",
14857                                  i40e_stat_str(&pf->hw, ret),
14858                                  i40e_aq_str(&pf->hw,
14859                                              pf->hw.aq.asq_last_status));
14860                         kfree(aq_buf);
14861                         return -ENOENT;
14862                 }
14863
14864                 num_reported = le16_to_cpu(sw_config->header.num_reported);
14865                 num_total = le16_to_cpu(sw_config->header.num_total);
14866
14867                 if (printconfig)
14868                         dev_info(&pf->pdev->dev,
14869                                  "header: %d reported %d total\n",
14870                                  num_reported, num_total);
14871
14872                 for (i = 0; i < num_reported; i++) {
14873                         struct i40e_aqc_switch_config_element_resp *ele =
14874                                 &sw_config->element[i];
14875
14876                         i40e_setup_pf_switch_element(pf, ele, num_reported,
14877                                                      printconfig);
14878                 }
14879         } while (next_seid != 0);
14880
14881         kfree(aq_buf);
14882         return ret;
14883 }
14884
14885 /**
14886  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14887  * @pf: board private structure
14888  * @reinit: if the Main VSI needs to re-initialized.
14889  * @lock_acquired: indicates whether or not the lock has been acquired
14890  *
14891  * Returns 0 on success, negative value on failure
14892  **/
14893 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
14894 {
14895         u16 flags = 0;
14896         int ret;
14897
14898         /* find out what's out there already */
14899         ret = i40e_fetch_switch_configuration(pf, false);
14900         if (ret) {
14901                 dev_info(&pf->pdev->dev,
14902                          "couldn't fetch switch config, err %s aq_err %s\n",
14903                          i40e_stat_str(&pf->hw, ret),
14904                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14905                 return ret;
14906         }
14907         i40e_pf_reset_stats(pf);
14908
14909         /* set the switch config bit for the whole device to
14910          * support limited promisc or true promisc
14911          * when user requests promisc. The default is limited
14912          * promisc.
14913         */
14914
14915         if ((pf->hw.pf_id == 0) &&
14916             !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
14917                 flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14918                 pf->last_sw_conf_flags = flags;
14919         }
14920
14921         if (pf->hw.pf_id == 0) {
14922                 u16 valid_flags;
14923
14924                 valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14925                 ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
14926                                                 NULL);
14927                 if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
14928                         dev_info(&pf->pdev->dev,
14929                                  "couldn't set switch config bits, err %s aq_err %s\n",
14930                                  i40e_stat_str(&pf->hw, ret),
14931                                  i40e_aq_str(&pf->hw,
14932                                              pf->hw.aq.asq_last_status));
14933                         /* not a fatal problem, just keep going */
14934                 }
14935                 pf->last_sw_conf_valid_flags = valid_flags;
14936         }
14937
14938         /* first time setup */
14939         if (pf->lan_vsi == I40E_NO_VSI || reinit) {
14940                 struct i40e_vsi *vsi = NULL;
14941                 u16 uplink_seid;
14942
14943                 /* Set up the PF VSI associated with the PF's main VSI
14944                  * that is already in the HW switch
14945                  */
14946                 if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
14947                         uplink_seid = pf->veb[pf->lan_veb]->seid;
14948                 else
14949                         uplink_seid = pf->mac_seid;
14950                 if (pf->lan_vsi == I40E_NO_VSI)
14951                         vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
14952                 else if (reinit)
14953                         vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
14954                 if (!vsi) {
14955                         dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
14956                         i40e_cloud_filter_exit(pf);
14957                         i40e_fdir_teardown(pf);
14958                         return -EAGAIN;
14959                 }
14960         } else {
14961                 /* force a reset of TC and queue layout configurations */
14962                 u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14963
14964                 pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14965                 pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14966                 i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14967         }
14968         i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
14969
14970         i40e_fdir_sb_setup(pf);
14971
14972         /* Setup static PF queue filter control settings */
14973         ret = i40e_setup_pf_filter_control(pf);
14974         if (ret) {
14975                 dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
14976                          ret);
14977                 /* Failure here should not stop continuing other steps */
14978         }
14979
14980         /* enable RSS in the HW, even for only one queue, as the stack can use
14981          * the hash
14982          */
14983         if ((pf->flags & I40E_FLAG_RSS_ENABLED))
14984                 i40e_pf_config_rss(pf);
14985
14986         /* fill in link information and enable LSE reporting */
14987         i40e_link_event(pf);
14988
14989         /* Initialize user-specific link properties */
14990         pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
14991                                   I40E_AQ_AN_COMPLETED) ? true : false);
14992
14993         i40e_ptp_init(pf);
14994
14995         if (!lock_acquired)
14996                 rtnl_lock();
14997
14998         /* repopulate tunnel port filters */
14999         udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
15000
15001         if (!lock_acquired)
15002                 rtnl_unlock();
15003
15004         return ret;
15005 }
15006
15007 /**
15008  * i40e_determine_queue_usage - Work out queue distribution
15009  * @pf: board private structure
15010  **/
15011 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15012 {
15013         int queues_left;
15014         int q_max;
15015
15016         pf->num_lan_qps = 0;
15017
15018         /* Find the max queues to be put into basic use.  We'll always be
15019          * using TC0, whether or not DCB is running, and TC0 will get the
15020          * big RSS set.
15021          */
15022         queues_left = pf->hw.func_caps.num_tx_qp;
15023
15024         if ((queues_left == 1) ||
15025             !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
15026                 /* one qp for PF, no queues for anything else */
15027                 queues_left = 0;
15028                 pf->alloc_rss_size = pf->num_lan_qps = 1;
15029
15030                 /* make sure all the fancies are disabled */
15031                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
15032                                I40E_FLAG_IWARP_ENABLED  |
15033                                I40E_FLAG_FD_SB_ENABLED  |
15034                                I40E_FLAG_FD_ATR_ENABLED |
15035                                I40E_FLAG_DCB_CAPABLE    |
15036                                I40E_FLAG_DCB_ENABLED    |
15037                                I40E_FLAG_SRIOV_ENABLED  |
15038                                I40E_FLAG_VMDQ_ENABLED);
15039                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15040         } else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
15041                                   I40E_FLAG_FD_SB_ENABLED |
15042                                   I40E_FLAG_FD_ATR_ENABLED |
15043                                   I40E_FLAG_DCB_CAPABLE))) {
15044                 /* one qp for PF */
15045                 pf->alloc_rss_size = pf->num_lan_qps = 1;
15046                 queues_left -= pf->num_lan_qps;
15047
15048                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
15049                                I40E_FLAG_IWARP_ENABLED  |
15050                                I40E_FLAG_FD_SB_ENABLED  |
15051                                I40E_FLAG_FD_ATR_ENABLED |
15052                                I40E_FLAG_DCB_ENABLED    |
15053                                I40E_FLAG_VMDQ_ENABLED);
15054                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15055         } else {
15056                 /* Not enough queues for all TCs */
15057                 if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
15058                     (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
15059                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
15060                                         I40E_FLAG_DCB_ENABLED);
15061                         dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15062                 }
15063
15064                 /* limit lan qps to the smaller of qps, cpus or msix */
15065                 q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15066                 q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15067                 q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15068                 pf->num_lan_qps = q_max;
15069
15070                 queues_left -= pf->num_lan_qps;
15071         }
15072
15073         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15074                 if (queues_left > 1) {
15075                         queues_left -= 1; /* save 1 queue for FD */
15076                 } else {
15077                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
15078                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15079                         dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15080                 }
15081         }
15082
15083         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15084             pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15085                 pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15086                                         (queues_left / pf->num_vf_qps));
15087                 queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15088         }
15089
15090         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
15091             pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15092                 pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15093                                           (queues_left / pf->num_vmdq_qps));
15094                 queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15095         }
15096
15097         pf->queues_left = queues_left;
15098         dev_dbg(&pf->pdev->dev,
15099                 "qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15100                 pf->hw.func_caps.num_tx_qp,
15101                 !!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
15102                 pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15103                 pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15104                 queues_left);
15105 }
15106
15107 /**
15108  * i40e_setup_pf_filter_control - Setup PF static filter control
15109  * @pf: PF to be setup
15110  *
15111  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15112  * settings. If PE/FCoE are enabled then it will also set the per PF
15113  * based filter sizes required for them. It also enables Flow director,
15114  * ethertype and macvlan type filter settings for the pf.
15115  *
15116  * Returns 0 on success, negative on failure
15117  **/
15118 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15119 {
15120         struct i40e_filter_control_settings *settings = &pf->filter_settings;
15121
15122         settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15123
15124         /* Flow Director is enabled */
15125         if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
15126                 settings->enable_fdir = true;
15127
15128         /* Ethtype and MACVLAN filters enabled for PF */
15129         settings->enable_ethtype = true;
15130         settings->enable_macvlan = true;
15131
15132         if (i40e_set_filter_control(&pf->hw, settings))
15133                 return -ENOENT;
15134
15135         return 0;
15136 }
15137
15138 #define INFO_STRING_LEN 255
15139 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15140 static void i40e_print_features(struct i40e_pf *pf)
15141 {
15142         struct i40e_hw *hw = &pf->hw;
15143         char *buf;
15144         int i;
15145
15146         buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15147         if (!buf)
15148                 return;
15149
15150         i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15151 #ifdef CONFIG_PCI_IOV
15152         i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15153 #endif
15154         i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15155                       pf->hw.func_caps.num_vsis,
15156                       pf->vsi[pf->lan_vsi]->num_queue_pairs);
15157         if (pf->flags & I40E_FLAG_RSS_ENABLED)
15158                 i += scnprintf(&buf[i], REMAIN(i), " RSS");
15159         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
15160                 i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15161         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15162                 i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15163                 i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15164         }
15165         if (pf->flags & I40E_FLAG_DCB_CAPABLE)
15166                 i += scnprintf(&buf[i], REMAIN(i), " DCB");
15167         i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15168         i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15169         if (pf->flags & I40E_FLAG_PTP)
15170                 i += scnprintf(&buf[i], REMAIN(i), " PTP");
15171         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
15172                 i += scnprintf(&buf[i], REMAIN(i), " VEB");
15173         else
15174                 i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15175
15176         dev_info(&pf->pdev->dev, "%s\n", buf);
15177         kfree(buf);
15178         WARN_ON(i > INFO_STRING_LEN);
15179 }
15180
15181 /**
15182  * i40e_get_platform_mac_addr - get platform-specific MAC address
15183  * @pdev: PCI device information struct
15184  * @pf: board private structure
15185  *
15186  * Look up the MAC address for the device. First we'll try
15187  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15188  * specific fallback. Otherwise, we'll default to the stored value in
15189  * firmware.
15190  **/
15191 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15192 {
15193         if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15194                 i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15195 }
15196
15197 /**
15198  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15199  * @fec_cfg: FEC option to set in flags
15200  * @flags: ptr to flags in which we set FEC option
15201  **/
15202 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
15203 {
15204         if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
15205                 *flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
15206         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15207             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15208                 *flags |= I40E_FLAG_RS_FEC;
15209                 *flags &= ~I40E_FLAG_BASE_R_FEC;
15210         }
15211         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15212             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15213                 *flags |= I40E_FLAG_BASE_R_FEC;
15214                 *flags &= ~I40E_FLAG_RS_FEC;
15215         }
15216         if (fec_cfg == 0)
15217                 *flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
15218 }
15219
15220 /**
15221  * i40e_check_recovery_mode - check if we are running transition firmware
15222  * @pf: board private structure
15223  *
15224  * Check registers indicating the firmware runs in recovery mode. Sets the
15225  * appropriate driver state.
15226  *
15227  * Returns true if the recovery mode was detected, false otherwise
15228  **/
15229 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15230 {
15231         u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15232
15233         if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15234                 dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15235                 dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15236                 set_bit(__I40E_RECOVERY_MODE, pf->state);
15237
15238                 return true;
15239         }
15240         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15241                 dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15242
15243         return false;
15244 }
15245
15246 /**
15247  * i40e_pf_loop_reset - perform reset in a loop.
15248  * @pf: board private structure
15249  *
15250  * This function is useful when a NIC is about to enter recovery mode.
15251  * When a NIC's internal data structures are corrupted the NIC's
15252  * firmware is going to enter recovery mode.
15253  * Right after a POR it takes about 7 minutes for firmware to enter
15254  * recovery mode. Until that time a NIC is in some kind of intermediate
15255  * state. After that time period the NIC almost surely enters
15256  * recovery mode. The only way for a driver to detect intermediate
15257  * state is to issue a series of pf-resets and check a return value.
15258  * If a PF reset returns success then the firmware could be in recovery
15259  * mode so the caller of this code needs to check for recovery mode
15260  * if this function returns success. There is a little chance that
15261  * firmware will hang in intermediate state forever.
15262  * Since waiting 7 minutes is quite a lot of time this function waits
15263  * 10 seconds and then gives up by returning an error.
15264  *
15265  * Return 0 on success, negative on failure.
15266  **/
15267 static i40e_status i40e_pf_loop_reset(struct i40e_pf *pf)
15268 {
15269         /* wait max 10 seconds for PF reset to succeed */
15270         const unsigned long time_end = jiffies + 10 * HZ;
15271
15272         struct i40e_hw *hw = &pf->hw;
15273         i40e_status ret;
15274
15275         ret = i40e_pf_reset(hw);
15276         while (ret != I40E_SUCCESS && time_before(jiffies, time_end)) {
15277                 usleep_range(10000, 20000);
15278                 ret = i40e_pf_reset(hw);
15279         }
15280
15281         if (ret == I40E_SUCCESS)
15282                 pf->pfr_count++;
15283         else
15284                 dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15285
15286         return ret;
15287 }
15288
15289 /**
15290  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15291  * @pf: board private structure
15292  *
15293  * Check FW registers to determine if FW issued unexpected EMP Reset.
15294  * Every time when unexpected EMP Reset occurs the FW increments
15295  * a counter of unexpected EMP Resets. When the counter reaches 10
15296  * the FW should enter the Recovery mode
15297  *
15298  * Returns true if FW issued unexpected EMP Reset
15299  **/
15300 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15301 {
15302         const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15303                            I40E_GL_FWSTS_FWS1B_MASK;
15304         return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15305                (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15306 }
15307
15308 /**
15309  * i40e_handle_resets - handle EMP resets and PF resets
15310  * @pf: board private structure
15311  *
15312  * Handle both EMP resets and PF resets and conclude whether there are
15313  * any issues regarding these resets. If there are any issues then
15314  * generate log entry.
15315  *
15316  * Return 0 if NIC is healthy or negative value when there are issues
15317  * with resets
15318  **/
15319 static i40e_status i40e_handle_resets(struct i40e_pf *pf)
15320 {
15321         const i40e_status pfr = i40e_pf_loop_reset(pf);
15322         const bool is_empr = i40e_check_fw_empr(pf);
15323
15324         if (is_empr || pfr != I40E_SUCCESS)
15325                 dev_crit(&pf->pdev->dev, "Entering recovery mode due to repeated FW resets. This may take several minutes. Refer to the Intel(R) Ethernet Adapters and Devices User Guide.\n");
15326
15327         return is_empr ? I40E_ERR_RESET_FAILED : pfr;
15328 }
15329
15330 /**
15331  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15332  * @pf: board private structure
15333  * @hw: ptr to the hardware info
15334  *
15335  * This function does a minimal setup of all subsystems needed for running
15336  * recovery mode.
15337  *
15338  * Returns 0 on success, negative on failure
15339  **/
15340 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15341 {
15342         struct i40e_vsi *vsi;
15343         int err;
15344         int v_idx;
15345
15346         pci_save_state(pf->pdev);
15347
15348         /* set up periodic task facility */
15349         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15350         pf->service_timer_period = HZ;
15351
15352         INIT_WORK(&pf->service_task, i40e_service_task);
15353         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15354
15355         err = i40e_init_interrupt_scheme(pf);
15356         if (err)
15357                 goto err_switch_setup;
15358
15359         /* The number of VSIs reported by the FW is the minimum guaranteed
15360          * to us; HW supports far more and we share the remaining pool with
15361          * the other PFs. We allocate space for more than the guarantee with
15362          * the understanding that we might not get them all later.
15363          */
15364         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15365                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15366         else
15367                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15368
15369         /* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15370         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15371                           GFP_KERNEL);
15372         if (!pf->vsi) {
15373                 err = -ENOMEM;
15374                 goto err_switch_setup;
15375         }
15376
15377         /* We allocate one VSI which is needed as absolute minimum
15378          * in order to register the netdev
15379          */
15380         v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15381         if (v_idx < 0) {
15382                 err = v_idx;
15383                 goto err_switch_setup;
15384         }
15385         pf->lan_vsi = v_idx;
15386         vsi = pf->vsi[v_idx];
15387         if (!vsi) {
15388                 err = -EFAULT;
15389                 goto err_switch_setup;
15390         }
15391         vsi->alloc_queue_pairs = 1;
15392         err = i40e_config_netdev(vsi);
15393         if (err)
15394                 goto err_switch_setup;
15395         err = register_netdev(vsi->netdev);
15396         if (err)
15397                 goto err_switch_setup;
15398         vsi->netdev_registered = true;
15399         i40e_dbg_pf_init(pf);
15400
15401         err = i40e_setup_misc_vector_for_recovery_mode(pf);
15402         if (err)
15403                 goto err_switch_setup;
15404
15405         /* tell the firmware that we're starting */
15406         i40e_send_version(pf);
15407
15408         /* since everything's happy, start the service_task timer */
15409         mod_timer(&pf->service_timer,
15410                   round_jiffies(jiffies + pf->service_timer_period));
15411
15412         return 0;
15413
15414 err_switch_setup:
15415         i40e_reset_interrupt_capability(pf);
15416         del_timer_sync(&pf->service_timer);
15417         i40e_shutdown_adminq(hw);
15418         iounmap(hw->hw_addr);
15419         pci_disable_pcie_error_reporting(pf->pdev);
15420         pci_release_mem_regions(pf->pdev);
15421         pci_disable_device(pf->pdev);
15422         kfree(pf);
15423
15424         return err;
15425 }
15426
15427 /**
15428  * i40e_set_subsystem_device_id - set subsystem device id
15429  * @hw: pointer to the hardware info
15430  *
15431  * Set PCI subsystem device id either from a pci_dev structure or
15432  * a specific FW register.
15433  **/
15434 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15435 {
15436         struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15437
15438         hw->subsystem_device_id = pdev->subsystem_device ?
15439                 pdev->subsystem_device :
15440                 (ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15441 }
15442
15443 /**
15444  * i40e_probe - Device initialization routine
15445  * @pdev: PCI device information struct
15446  * @ent: entry in i40e_pci_tbl
15447  *
15448  * i40e_probe initializes a PF identified by a pci_dev structure.
15449  * The OS initialization, configuring of the PF private structure,
15450  * and a hardware reset occur.
15451  *
15452  * Returns 0 on success, negative on failure
15453  **/
15454 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15455 {
15456         struct i40e_aq_get_phy_abilities_resp abilities;
15457 #ifdef CONFIG_I40E_DCB
15458         enum i40e_get_fw_lldp_status_resp lldp_status;
15459         i40e_status status;
15460 #endif /* CONFIG_I40E_DCB */
15461         struct i40e_pf *pf;
15462         struct i40e_hw *hw;
15463         static u16 pfs_found;
15464         u16 wol_nvm_bits;
15465         u16 link_status;
15466         int err;
15467         u32 val;
15468         u32 i;
15469
15470         err = pci_enable_device_mem(pdev);
15471         if (err)
15472                 return err;
15473
15474         /* set up for high or low dma */
15475         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15476         if (err) {
15477                 dev_err(&pdev->dev,
15478                         "DMA configuration failed: 0x%x\n", err);
15479                 goto err_dma;
15480         }
15481
15482         /* set up pci connections */
15483         err = pci_request_mem_regions(pdev, i40e_driver_name);
15484         if (err) {
15485                 dev_info(&pdev->dev,
15486                          "pci_request_selected_regions failed %d\n", err);
15487                 goto err_pci_reg;
15488         }
15489
15490         pci_enable_pcie_error_reporting(pdev);
15491         pci_set_master(pdev);
15492
15493         /* Now that we have a PCI connection, we need to do the
15494          * low level device setup.  This is primarily setting up
15495          * the Admin Queue structures and then querying for the
15496          * device's current profile information.
15497          */
15498         pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15499         if (!pf) {
15500                 err = -ENOMEM;
15501                 goto err_pf_alloc;
15502         }
15503         pf->next_vsi = 0;
15504         pf->pdev = pdev;
15505         set_bit(__I40E_DOWN, pf->state);
15506
15507         hw = &pf->hw;
15508         hw->back = pf;
15509
15510         pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15511                                 I40E_MAX_CSR_SPACE);
15512         /* We believe that the highest register to read is
15513          * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15514          * is not less than that before mapping to prevent a
15515          * kernel panic.
15516          */
15517         if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15518                 dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15519                         pf->ioremap_len);
15520                 err = -ENOMEM;
15521                 goto err_ioremap;
15522         }
15523         hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15524         if (!hw->hw_addr) {
15525                 err = -EIO;
15526                 dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15527                          (unsigned int)pci_resource_start(pdev, 0),
15528                          pf->ioremap_len, err);
15529                 goto err_ioremap;
15530         }
15531         hw->vendor_id = pdev->vendor;
15532         hw->device_id = pdev->device;
15533         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15534         hw->subsystem_vendor_id = pdev->subsystem_vendor;
15535         i40e_set_subsystem_device_id(hw);
15536         hw->bus.device = PCI_SLOT(pdev->devfn);
15537         hw->bus.func = PCI_FUNC(pdev->devfn);
15538         hw->bus.bus_id = pdev->bus->number;
15539         pf->instance = pfs_found;
15540
15541         /* Select something other than the 802.1ad ethertype for the
15542          * switch to use internally and drop on ingress.
15543          */
15544         hw->switch_tag = 0xffff;
15545         hw->first_tag = ETH_P_8021AD;
15546         hw->second_tag = ETH_P_8021Q;
15547
15548         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15549         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15550         INIT_LIST_HEAD(&pf->ddp_old_prof);
15551
15552         /* set up the locks for the AQ, do this only once in probe
15553          * and destroy them only once in remove
15554          */
15555         mutex_init(&hw->aq.asq_mutex);
15556         mutex_init(&hw->aq.arq_mutex);
15557
15558         pf->msg_enable = netif_msg_init(debug,
15559                                         NETIF_MSG_DRV |
15560                                         NETIF_MSG_PROBE |
15561                                         NETIF_MSG_LINK);
15562         if (debug < -1)
15563                 pf->hw.debug_mask = debug;
15564
15565         /* do a special CORER for clearing PXE mode once at init */
15566         if (hw->revision_id == 0 &&
15567             (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15568                 wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15569                 i40e_flush(hw);
15570                 msleep(200);
15571                 pf->corer_count++;
15572
15573                 i40e_clear_pxe_mode(hw);
15574         }
15575
15576         /* Reset here to make sure all is clean and to define PF 'n' */
15577         i40e_clear_hw(hw);
15578
15579         err = i40e_set_mac_type(hw);
15580         if (err) {
15581                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15582                          err);
15583                 goto err_pf_reset;
15584         }
15585
15586         err = i40e_handle_resets(pf);
15587         if (err)
15588                 goto err_pf_reset;
15589
15590         i40e_check_recovery_mode(pf);
15591
15592         if (is_kdump_kernel()) {
15593                 hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15594                 hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15595         } else {
15596                 hw->aq.num_arq_entries = I40E_AQ_LEN;
15597                 hw->aq.num_asq_entries = I40E_AQ_LEN;
15598         }
15599         hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15600         hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15601         pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15602
15603         snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15604                  "%s-%s:misc",
15605                  dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15606
15607         err = i40e_init_shared_code(hw);
15608         if (err) {
15609                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15610                          err);
15611                 goto err_pf_reset;
15612         }
15613
15614         /* set up a default setting for link flow control */
15615         pf->hw.fc.requested_mode = I40E_FC_NONE;
15616
15617         err = i40e_init_adminq(hw);
15618         if (err) {
15619                 if (err == I40E_ERR_FIRMWARE_API_VERSION)
15620                         dev_info(&pdev->dev,
15621                                  "The driver for the device stopped because the NVM image v%u.%u is newer than expected v%u.%u. You must install the most recent version of the network driver.\n",
15622                                  hw->aq.api_maj_ver,
15623                                  hw->aq.api_min_ver,
15624                                  I40E_FW_API_VERSION_MAJOR,
15625                                  I40E_FW_MINOR_VERSION(hw));
15626                 else
15627                         dev_info(&pdev->dev,
15628                                  "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15629
15630                 goto err_pf_reset;
15631         }
15632         i40e_get_oem_version(hw);
15633
15634         /* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15635         dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15636                  hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15637                  hw->aq.api_maj_ver, hw->aq.api_min_ver,
15638                  i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15639                  hw->subsystem_vendor_id, hw->subsystem_device_id);
15640
15641         if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15642             hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15643                 dev_dbg(&pdev->dev,
15644                         "The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15645                          hw->aq.api_maj_ver,
15646                          hw->aq.api_min_ver,
15647                          I40E_FW_API_VERSION_MAJOR,
15648                          I40E_FW_MINOR_VERSION(hw));
15649         else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15650                 dev_info(&pdev->dev,
15651                          "The driver for the device detected an older version of the NVM image v%u.%u than expected v%u.%u. Please update the NVM image.\n",
15652                          hw->aq.api_maj_ver,
15653                          hw->aq.api_min_ver,
15654                          I40E_FW_API_VERSION_MAJOR,
15655                          I40E_FW_MINOR_VERSION(hw));
15656
15657         i40e_verify_eeprom(pf);
15658
15659         /* Rev 0 hardware was never productized */
15660         if (hw->revision_id < 1)
15661                 dev_warn(&pdev->dev, "This device is a pre-production adapter/LOM. Please be aware there may be issues with your hardware. If you are experiencing problems please contact your Intel or hardware representative who provided you with this hardware.\n");
15662
15663         i40e_clear_pxe_mode(hw);
15664
15665         err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15666         if (err)
15667                 goto err_adminq_setup;
15668
15669         err = i40e_sw_init(pf);
15670         if (err) {
15671                 dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15672                 goto err_sw_init;
15673         }
15674
15675         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15676                 return i40e_init_recovery_mode(pf, hw);
15677
15678         err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15679                                 hw->func_caps.num_rx_qp, 0, 0);
15680         if (err) {
15681                 dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15682                 goto err_init_lan_hmc;
15683         }
15684
15685         err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15686         if (err) {
15687                 dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15688                 err = -ENOENT;
15689                 goto err_configure_lan_hmc;
15690         }
15691
15692         /* Disable LLDP for NICs that have firmware versions lower than v4.3.
15693          * Ignore error return codes because if it was already disabled via
15694          * hardware settings this will fail
15695          */
15696         if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15697                 dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15698                 i40e_aq_stop_lldp(hw, true, false, NULL);
15699         }
15700
15701         /* allow a platform config to override the HW addr */
15702         i40e_get_platform_mac_addr(pdev, pf);
15703
15704         if (!is_valid_ether_addr(hw->mac.addr)) {
15705                 dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15706                 err = -EIO;
15707                 goto err_mac_addr;
15708         }
15709         dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15710         ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15711         i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15712         if (is_valid_ether_addr(hw->mac.port_addr))
15713                 pf->hw_features |= I40E_HW_PORT_ID_VALID;
15714
15715         i40e_ptp_alloc_pins(pf);
15716         pci_set_drvdata(pdev, pf);
15717         pci_save_state(pdev);
15718
15719 #ifdef CONFIG_I40E_DCB
15720         status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15721         (!status &&
15722          lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15723                 (pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15724                 (pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15725         dev_info(&pdev->dev,
15726                  (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15727                         "FW LLDP is disabled\n" :
15728                         "FW LLDP is enabled\n");
15729
15730         /* Enable FW to write default DCB config on link-up */
15731         i40e_aq_set_dcb_parameters(hw, true, NULL);
15732
15733         err = i40e_init_pf_dcb(pf);
15734         if (err) {
15735                 dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15736                 pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15737                 /* Continue without DCB enabled */
15738         }
15739 #endif /* CONFIG_I40E_DCB */
15740
15741         /* set up periodic task facility */
15742         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15743         pf->service_timer_period = HZ;
15744
15745         INIT_WORK(&pf->service_task, i40e_service_task);
15746         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15747
15748         /* NVM bit on means WoL disabled for the port */
15749         i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15750         if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15751                 pf->wol_en = false;
15752         else
15753                 pf->wol_en = true;
15754         device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15755
15756         /* set up the main switch operations */
15757         i40e_determine_queue_usage(pf);
15758         err = i40e_init_interrupt_scheme(pf);
15759         if (err)
15760                 goto err_switch_setup;
15761
15762         /* Reduce Tx and Rx pairs for kdump
15763          * When MSI-X is enabled, it's not allowed to use more TC queue
15764          * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15765          * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15766          */
15767         if (is_kdump_kernel())
15768                 pf->num_lan_msix = 1;
15769
15770         pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15771         pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15772         pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15773         pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15774         pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15775         pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15776                                                     UDP_TUNNEL_TYPE_GENEVE;
15777
15778         /* The number of VSIs reported by the FW is the minimum guaranteed
15779          * to us; HW supports far more and we share the remaining pool with
15780          * the other PFs. We allocate space for more than the guarantee with
15781          * the understanding that we might not get them all later.
15782          */
15783         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15784                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15785         else
15786                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15787         if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15788                 dev_warn(&pf->pdev->dev,
15789                          "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15790                          pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15791                 pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15792         }
15793
15794         /* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15795         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15796                           GFP_KERNEL);
15797         if (!pf->vsi) {
15798                 err = -ENOMEM;
15799                 goto err_switch_setup;
15800         }
15801
15802 #ifdef CONFIG_PCI_IOV
15803         /* prep for VF support */
15804         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15805             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15806             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15807                 if (pci_num_vf(pdev))
15808                         pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
15809         }
15810 #endif
15811         err = i40e_setup_pf_switch(pf, false, false);
15812         if (err) {
15813                 dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15814                 goto err_vsis;
15815         }
15816         INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
15817
15818         /* if FDIR VSI was set up, start it now */
15819         for (i = 0; i < pf->num_alloc_vsi; i++) {
15820                 if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
15821                         i40e_vsi_open(pf->vsi[i]);
15822                         break;
15823                 }
15824         }
15825
15826         /* The driver only wants link up/down and module qualification
15827          * reports from firmware.  Note the negative logic.
15828          */
15829         err = i40e_aq_set_phy_int_mask(&pf->hw,
15830                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
15831                                          I40E_AQ_EVENT_MEDIA_NA |
15832                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15833         if (err)
15834                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
15835                          i40e_stat_str(&pf->hw, err),
15836                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15837
15838         /* Reconfigure hardware for allowing smaller MSS in the case
15839          * of TSO, so that we avoid the MDD being fired and causing
15840          * a reset in the case of small MSS+TSO.
15841          */
15842         val = rd32(hw, I40E_REG_MSS);
15843         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15844                 val &= ~I40E_REG_MSS_MIN_MASK;
15845                 val |= I40E_64BYTE_MSS;
15846                 wr32(hw, I40E_REG_MSS, val);
15847         }
15848
15849         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
15850                 msleep(75);
15851                 err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15852                 if (err)
15853                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
15854                                  i40e_stat_str(&pf->hw, err),
15855                                  i40e_aq_str(&pf->hw,
15856                                              pf->hw.aq.asq_last_status));
15857         }
15858         /* The main driver is (mostly) up and happy. We need to set this state
15859          * before setting up the misc vector or we get a race and the vector
15860          * ends up disabled forever.
15861          */
15862         clear_bit(__I40E_DOWN, pf->state);
15863
15864         /* In case of MSIX we are going to setup the misc vector right here
15865          * to handle admin queue events etc. In case of legacy and MSI
15866          * the misc functionality and queue processing is combined in
15867          * the same vector and that gets setup at open.
15868          */
15869         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
15870                 err = i40e_setup_misc_vector(pf);
15871                 if (err) {
15872                         dev_info(&pdev->dev,
15873                                  "setup of misc vector failed: %d\n", err);
15874                         i40e_cloud_filter_exit(pf);
15875                         i40e_fdir_teardown(pf);
15876                         goto err_vsis;
15877                 }
15878         }
15879
15880 #ifdef CONFIG_PCI_IOV
15881         /* prep for VF support */
15882         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15883             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15884             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15885                 /* disable link interrupts for VFs */
15886                 val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15887                 val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15888                 wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15889                 i40e_flush(hw);
15890
15891                 if (pci_num_vf(pdev)) {
15892                         dev_info(&pdev->dev,
15893                                  "Active VFs found, allocating resources.\n");
15894                         err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15895                         if (err)
15896                                 dev_info(&pdev->dev,
15897                                          "Error %d allocating resources for existing VFs\n",
15898                                          err);
15899                 }
15900         }
15901 #endif /* CONFIG_PCI_IOV */
15902
15903         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15904                 pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
15905                                                       pf->num_iwarp_msix,
15906                                                       I40E_IWARP_IRQ_PILE_ID);
15907                 if (pf->iwarp_base_vector < 0) {
15908                         dev_info(&pdev->dev,
15909                                  "failed to get tracking for %d vectors for IWARP err=%d\n",
15910                                  pf->num_iwarp_msix, pf->iwarp_base_vector);
15911                         pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
15912                 }
15913         }
15914
15915         i40e_dbg_pf_init(pf);
15916
15917         /* tell the firmware that we're starting */
15918         i40e_send_version(pf);
15919
15920         /* since everything's happy, start the service_task timer */
15921         mod_timer(&pf->service_timer,
15922                   round_jiffies(jiffies + pf->service_timer_period));
15923
15924         /* add this PF to client device list and launch a client service task */
15925         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15926                 err = i40e_lan_add_device(pf);
15927                 if (err)
15928                         dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
15929                                  err);
15930         }
15931
15932 #define PCI_SPEED_SIZE 8
15933 #define PCI_WIDTH_SIZE 8
15934         /* Devices on the IOSF bus do not have this information
15935          * and will report PCI Gen 1 x 1 by default so don't bother
15936          * checking them.
15937          */
15938         if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
15939                 char speed[PCI_SPEED_SIZE] = "Unknown";
15940                 char width[PCI_WIDTH_SIZE] = "Unknown";
15941
15942                 /* Get the negotiated link width and speed from PCI config
15943                  * space
15944                  */
15945                 pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
15946                                           &link_status);
15947
15948                 i40e_set_pci_config_data(hw, link_status);
15949
15950                 switch (hw->bus.speed) {
15951                 case i40e_bus_speed_8000:
15952                         strlcpy(speed, "8.0", PCI_SPEED_SIZE); break;
15953                 case i40e_bus_speed_5000:
15954                         strlcpy(speed, "5.0", PCI_SPEED_SIZE); break;
15955                 case i40e_bus_speed_2500:
15956                         strlcpy(speed, "2.5", PCI_SPEED_SIZE); break;
15957                 default:
15958                         break;
15959                 }
15960                 switch (hw->bus.width) {
15961                 case i40e_bus_width_pcie_x8:
15962                         strlcpy(width, "8", PCI_WIDTH_SIZE); break;
15963                 case i40e_bus_width_pcie_x4:
15964                         strlcpy(width, "4", PCI_WIDTH_SIZE); break;
15965                 case i40e_bus_width_pcie_x2:
15966                         strlcpy(width, "2", PCI_WIDTH_SIZE); break;
15967                 case i40e_bus_width_pcie_x1:
15968                         strlcpy(width, "1", PCI_WIDTH_SIZE); break;
15969                 default:
15970                         break;
15971                 }
15972
15973                 dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
15974                          speed, width);
15975
15976                 if (hw->bus.width < i40e_bus_width_pcie_x8 ||
15977                     hw->bus.speed < i40e_bus_speed_8000) {
15978                         dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
15979                         dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
15980                 }
15981         }
15982
15983         /* get the requested speeds from the fw */
15984         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
15985         if (err)
15986                 dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
15987                         i40e_stat_str(&pf->hw, err),
15988                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15989         pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
15990
15991         /* set the FEC config due to the board capabilities */
15992         i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
15993
15994         /* get the supported phy types from the fw */
15995         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
15996         if (err)
15997                 dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
15998                         i40e_stat_str(&pf->hw, err),
15999                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16000
16001         /* make sure the MFS hasn't been set lower than the default */
16002 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16003         val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
16004                I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
16005         if (val < MAX_FRAME_SIZE_DEFAULT)
16006                 dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
16007                          i, val);
16008
16009         /* Add a filter to drop all Flow control frames from any VSI from being
16010          * transmitted. By doing so we stop a malicious VF from sending out
16011          * PAUSE or PFC frames and potentially controlling traffic for other
16012          * PF/VF VSIs.
16013          * The FW can still send Flow control frames if enabled.
16014          */
16015         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16016                                                        pf->main_vsi_seid);
16017
16018         if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16019                 (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16020                 pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
16021         if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16022                 pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
16023         /* print a string summarizing features */
16024         i40e_print_features(pf);
16025
16026         return 0;
16027
16028         /* Unwind what we've done if something failed in the setup */
16029 err_vsis:
16030         set_bit(__I40E_DOWN, pf->state);
16031         i40e_clear_interrupt_scheme(pf);
16032         kfree(pf->vsi);
16033 err_switch_setup:
16034         i40e_reset_interrupt_capability(pf);
16035         del_timer_sync(&pf->service_timer);
16036 err_mac_addr:
16037 err_configure_lan_hmc:
16038         (void)i40e_shutdown_lan_hmc(hw);
16039 err_init_lan_hmc:
16040         kfree(pf->qp_pile);
16041 err_sw_init:
16042 err_adminq_setup:
16043 err_pf_reset:
16044         iounmap(hw->hw_addr);
16045 err_ioremap:
16046         kfree(pf);
16047 err_pf_alloc:
16048         pci_disable_pcie_error_reporting(pdev);
16049         pci_release_mem_regions(pdev);
16050 err_pci_reg:
16051 err_dma:
16052         pci_disable_device(pdev);
16053         return err;
16054 }
16055
16056 /**
16057  * i40e_remove - Device removal routine
16058  * @pdev: PCI device information struct
16059  *
16060  * i40e_remove is called by the PCI subsystem to alert the driver
16061  * that is should release a PCI device.  This could be caused by a
16062  * Hot-Plug event, or because the driver is going to be removed from
16063  * memory.
16064  **/
16065 static void i40e_remove(struct pci_dev *pdev)
16066 {
16067         struct i40e_pf *pf = pci_get_drvdata(pdev);
16068         struct i40e_hw *hw = &pf->hw;
16069         i40e_status ret_code;
16070         int i;
16071
16072         i40e_dbg_pf_exit(pf);
16073
16074         i40e_ptp_stop(pf);
16075
16076         /* Disable RSS in hw */
16077         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16078         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16079
16080         /* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16081          * flags, once they are set, i40e_rebuild should not be called as
16082          * i40e_prep_for_reset always returns early.
16083          */
16084         while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16085                 usleep_range(1000, 2000);
16086         set_bit(__I40E_IN_REMOVE, pf->state);
16087
16088         if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
16089                 set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16090                 i40e_free_vfs(pf);
16091                 pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
16092         }
16093         /* no more scheduling of any task */
16094         set_bit(__I40E_SUSPENDED, pf->state);
16095         set_bit(__I40E_DOWN, pf->state);
16096         if (pf->service_timer.function)
16097                 del_timer_sync(&pf->service_timer);
16098         if (pf->service_task.func)
16099                 cancel_work_sync(&pf->service_task);
16100
16101         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16102                 struct i40e_vsi *vsi = pf->vsi[0];
16103
16104                 /* We know that we have allocated only one vsi for this PF,
16105                  * it was just for registering netdevice, so the interface
16106                  * could be visible in the 'ifconfig' output
16107                  */
16108                 unregister_netdev(vsi->netdev);
16109                 free_netdev(vsi->netdev);
16110
16111                 goto unmap;
16112         }
16113
16114         /* Client close must be called explicitly here because the timer
16115          * has been stopped.
16116          */
16117         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16118
16119         i40e_fdir_teardown(pf);
16120
16121         /* If there is a switch structure or any orphans, remove them.
16122          * This will leave only the PF's VSI remaining.
16123          */
16124         for (i = 0; i < I40E_MAX_VEB; i++) {
16125                 if (!pf->veb[i])
16126                         continue;
16127
16128                 if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16129                     pf->veb[i]->uplink_seid == 0)
16130                         i40e_switch_branch_release(pf->veb[i]);
16131         }
16132
16133         /* Now we can shutdown the PF's VSI, just before we kill
16134          * adminq and hmc.
16135          */
16136         if (pf->vsi[pf->lan_vsi])
16137                 i40e_vsi_release(pf->vsi[pf->lan_vsi]);
16138
16139         i40e_cloud_filter_exit(pf);
16140
16141         /* remove attached clients */
16142         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16143                 ret_code = i40e_lan_del_device(pf);
16144                 if (ret_code)
16145                         dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16146                                  ret_code);
16147         }
16148
16149         /* shutdown and destroy the HMC */
16150         if (hw->hmc.hmc_obj) {
16151                 ret_code = i40e_shutdown_lan_hmc(hw);
16152                 if (ret_code)
16153                         dev_warn(&pdev->dev,
16154                                  "Failed to destroy the HMC resources: %d\n",
16155                                  ret_code);
16156         }
16157
16158 unmap:
16159         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16160         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16161             !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16162                 free_irq(pf->pdev->irq, pf);
16163
16164         /* shutdown the adminq */
16165         i40e_shutdown_adminq(hw);
16166
16167         /* destroy the locks only once, here */
16168         mutex_destroy(&hw->aq.arq_mutex);
16169         mutex_destroy(&hw->aq.asq_mutex);
16170
16171         /* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16172         rtnl_lock();
16173         i40e_clear_interrupt_scheme(pf);
16174         for (i = 0; i < pf->num_alloc_vsi; i++) {
16175                 if (pf->vsi[i]) {
16176                         if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16177                                 i40e_vsi_clear_rings(pf->vsi[i]);
16178                         i40e_vsi_clear(pf->vsi[i]);
16179                         pf->vsi[i] = NULL;
16180                 }
16181         }
16182         rtnl_unlock();
16183
16184         for (i = 0; i < I40E_MAX_VEB; i++) {
16185                 kfree(pf->veb[i]);
16186                 pf->veb[i] = NULL;
16187         }
16188
16189         kfree(pf->qp_pile);
16190         kfree(pf->vsi);
16191
16192         iounmap(hw->hw_addr);
16193         kfree(pf);
16194         pci_release_mem_regions(pdev);
16195
16196         pci_disable_pcie_error_reporting(pdev);
16197         pci_disable_device(pdev);
16198 }
16199
16200 /**
16201  * i40e_pci_error_detected - warning that something funky happened in PCI land
16202  * @pdev: PCI device information struct
16203  * @error: the type of PCI error
16204  *
16205  * Called to warn that something happened and the error handling steps
16206  * are in progress.  Allows the driver to quiesce things, be ready for
16207  * remediation.
16208  **/
16209 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16210                                                 pci_channel_state_t error)
16211 {
16212         struct i40e_pf *pf = pci_get_drvdata(pdev);
16213
16214         dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16215
16216         if (!pf) {
16217                 dev_info(&pdev->dev,
16218                          "Cannot recover - error happened during device probe\n");
16219                 return PCI_ERS_RESULT_DISCONNECT;
16220         }
16221
16222         /* shutdown all operations */
16223         if (!test_bit(__I40E_SUSPENDED, pf->state))
16224                 i40e_prep_for_reset(pf);
16225
16226         /* Request a slot reset */
16227         return PCI_ERS_RESULT_NEED_RESET;
16228 }
16229
16230 /**
16231  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16232  * @pdev: PCI device information struct
16233  *
16234  * Called to find if the driver can work with the device now that
16235  * the pci slot has been reset.  If a basic connection seems good
16236  * (registers are readable and have sane content) then return a
16237  * happy little PCI_ERS_RESULT_xxx.
16238  **/
16239 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16240 {
16241         struct i40e_pf *pf = pci_get_drvdata(pdev);
16242         pci_ers_result_t result;
16243         u32 reg;
16244
16245         dev_dbg(&pdev->dev, "%s\n", __func__);
16246         if (pci_enable_device_mem(pdev)) {
16247                 dev_info(&pdev->dev,
16248                          "Cannot re-enable PCI device after reset.\n");
16249                 result = PCI_ERS_RESULT_DISCONNECT;
16250         } else {
16251                 pci_set_master(pdev);
16252                 pci_restore_state(pdev);
16253                 pci_save_state(pdev);
16254                 pci_wake_from_d3(pdev, false);
16255
16256                 reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16257                 if (reg == 0)
16258                         result = PCI_ERS_RESULT_RECOVERED;
16259                 else
16260                         result = PCI_ERS_RESULT_DISCONNECT;
16261         }
16262
16263         return result;
16264 }
16265
16266 /**
16267  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16268  * @pdev: PCI device information struct
16269  */
16270 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16271 {
16272         struct i40e_pf *pf = pci_get_drvdata(pdev);
16273
16274         i40e_prep_for_reset(pf);
16275 }
16276
16277 /**
16278  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16279  * @pdev: PCI device information struct
16280  */
16281 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16282 {
16283         struct i40e_pf *pf = pci_get_drvdata(pdev);
16284
16285         if (test_bit(__I40E_IN_REMOVE, pf->state))
16286                 return;
16287
16288         i40e_reset_and_rebuild(pf, false, false);
16289 }
16290
16291 /**
16292  * i40e_pci_error_resume - restart operations after PCI error recovery
16293  * @pdev: PCI device information struct
16294  *
16295  * Called to allow the driver to bring things back up after PCI error
16296  * and/or reset recovery has finished.
16297  **/
16298 static void i40e_pci_error_resume(struct pci_dev *pdev)
16299 {
16300         struct i40e_pf *pf = pci_get_drvdata(pdev);
16301
16302         dev_dbg(&pdev->dev, "%s\n", __func__);
16303         if (test_bit(__I40E_SUSPENDED, pf->state))
16304                 return;
16305
16306         i40e_handle_reset_warning(pf, false);
16307 }
16308
16309 /**
16310  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16311  * using the mac_address_write admin q function
16312  * @pf: pointer to i40e_pf struct
16313  **/
16314 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16315 {
16316         struct i40e_hw *hw = &pf->hw;
16317         i40e_status ret;
16318         u8 mac_addr[6];
16319         u16 flags = 0;
16320
16321         /* Get current MAC address in case it's an LAA */
16322         if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16323                 ether_addr_copy(mac_addr,
16324                                 pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16325         } else {
16326                 dev_err(&pf->pdev->dev,
16327                         "Failed to retrieve MAC address; using default\n");
16328                 ether_addr_copy(mac_addr, hw->mac.addr);
16329         }
16330
16331         /* The FW expects the mac address write cmd to first be called with
16332          * one of these flags before calling it again with the multicast
16333          * enable flags.
16334          */
16335         flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16336
16337         if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16338                 flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16339
16340         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16341         if (ret) {
16342                 dev_err(&pf->pdev->dev,
16343                         "Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16344                 return;
16345         }
16346
16347         flags = I40E_AQC_MC_MAG_EN
16348                         | I40E_AQC_WOL_PRESERVE_ON_PFR
16349                         | I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16350         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16351         if (ret)
16352                 dev_err(&pf->pdev->dev,
16353                         "Failed to enable Multicast Magic Packet wake up\n");
16354 }
16355
16356 /**
16357  * i40e_shutdown - PCI callback for shutting down
16358  * @pdev: PCI device information struct
16359  **/
16360 static void i40e_shutdown(struct pci_dev *pdev)
16361 {
16362         struct i40e_pf *pf = pci_get_drvdata(pdev);
16363         struct i40e_hw *hw = &pf->hw;
16364
16365         set_bit(__I40E_SUSPENDED, pf->state);
16366         set_bit(__I40E_DOWN, pf->state);
16367
16368         del_timer_sync(&pf->service_timer);
16369         cancel_work_sync(&pf->service_task);
16370         i40e_cloud_filter_exit(pf);
16371         i40e_fdir_teardown(pf);
16372
16373         /* Client close must be called explicitly here because the timer
16374          * has been stopped.
16375          */
16376         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16377
16378         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16379                 i40e_enable_mc_magic_wake(pf);
16380
16381         i40e_prep_for_reset(pf);
16382
16383         wr32(hw, I40E_PFPM_APM,
16384              (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16385         wr32(hw, I40E_PFPM_WUFC,
16386              (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16387
16388         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16389         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16390             !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16391                 free_irq(pf->pdev->irq, pf);
16392
16393         /* Since we're going to destroy queues during the
16394          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16395          * whole section
16396          */
16397         rtnl_lock();
16398         i40e_clear_interrupt_scheme(pf);
16399         rtnl_unlock();
16400
16401         if (system_state == SYSTEM_POWER_OFF) {
16402                 pci_wake_from_d3(pdev, pf->wol_en);
16403                 pci_set_power_state(pdev, PCI_D3hot);
16404         }
16405 }
16406
16407 /**
16408  * i40e_suspend - PM callback for moving to D3
16409  * @dev: generic device information structure
16410  **/
16411 static int __maybe_unused i40e_suspend(struct device *dev)
16412 {
16413         struct i40e_pf *pf = dev_get_drvdata(dev);
16414         struct i40e_hw *hw = &pf->hw;
16415
16416         /* If we're already suspended, then there is nothing to do */
16417         if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16418                 return 0;
16419
16420         set_bit(__I40E_DOWN, pf->state);
16421
16422         /* Ensure service task will not be running */
16423         del_timer_sync(&pf->service_timer);
16424         cancel_work_sync(&pf->service_task);
16425
16426         /* Client close must be called explicitly here because the timer
16427          * has been stopped.
16428          */
16429         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16430
16431         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16432                 i40e_enable_mc_magic_wake(pf);
16433
16434         /* Since we're going to destroy queues during the
16435          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16436          * whole section
16437          */
16438         rtnl_lock();
16439
16440         i40e_prep_for_reset(pf);
16441
16442         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16443         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16444
16445         /* Clear the interrupt scheme and release our IRQs so that the system
16446          * can safely hibernate even when there are a large number of CPUs.
16447          * Otherwise hibernation might fail when mapping all the vectors back
16448          * to CPU0.
16449          */
16450         i40e_clear_interrupt_scheme(pf);
16451
16452         rtnl_unlock();
16453
16454         return 0;
16455 }
16456
16457 /**
16458  * i40e_resume - PM callback for waking up from D3
16459  * @dev: generic device information structure
16460  **/
16461 static int __maybe_unused i40e_resume(struct device *dev)
16462 {
16463         struct i40e_pf *pf = dev_get_drvdata(dev);
16464         int err;
16465
16466         /* If we're not suspended, then there is nothing to do */
16467         if (!test_bit(__I40E_SUSPENDED, pf->state))
16468                 return 0;
16469
16470         /* We need to hold the RTNL lock prior to restoring interrupt schemes,
16471          * since we're going to be restoring queues
16472          */
16473         rtnl_lock();
16474
16475         /* We cleared the interrupt scheme when we suspended, so we need to
16476          * restore it now to resume device functionality.
16477          */
16478         err = i40e_restore_interrupt_scheme(pf);
16479         if (err) {
16480                 dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16481                         err);
16482         }
16483
16484         clear_bit(__I40E_DOWN, pf->state);
16485         i40e_reset_and_rebuild(pf, false, true);
16486
16487         rtnl_unlock();
16488
16489         /* Clear suspended state last after everything is recovered */
16490         clear_bit(__I40E_SUSPENDED, pf->state);
16491
16492         /* Restart the service task */
16493         mod_timer(&pf->service_timer,
16494                   round_jiffies(jiffies + pf->service_timer_period));
16495
16496         return 0;
16497 }
16498
16499 static const struct pci_error_handlers i40e_err_handler = {
16500         .error_detected = i40e_pci_error_detected,
16501         .slot_reset = i40e_pci_error_slot_reset,
16502         .reset_prepare = i40e_pci_error_reset_prepare,
16503         .reset_done = i40e_pci_error_reset_done,
16504         .resume = i40e_pci_error_resume,
16505 };
16506
16507 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16508
16509 static struct pci_driver i40e_driver = {
16510         .name     = i40e_driver_name,
16511         .id_table = i40e_pci_tbl,
16512         .probe    = i40e_probe,
16513         .remove   = i40e_remove,
16514         .driver   = {
16515                 .pm = &i40e_pm_ops,
16516         },
16517         .shutdown = i40e_shutdown,
16518         .err_handler = &i40e_err_handler,
16519         .sriov_configure = i40e_pci_sriov_configure,
16520 };
16521
16522 /**
16523  * i40e_init_module - Driver registration routine
16524  *
16525  * i40e_init_module is the first routine called when the driver is
16526  * loaded. All it does is register with the PCI subsystem.
16527  **/
16528 static int __init i40e_init_module(void)
16529 {
16530         pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16531         pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16532
16533         /* There is no need to throttle the number of active tasks because
16534          * each device limits its own task using a state bit for scheduling
16535          * the service task, and the device tasks do not interfere with each
16536          * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16537          * since we need to be able to guarantee forward progress even under
16538          * memory pressure.
16539          */
16540         i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16541         if (!i40e_wq) {
16542                 pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16543                 return -ENOMEM;
16544         }
16545
16546         i40e_dbg_init();
16547         return pci_register_driver(&i40e_driver);
16548 }
16549 module_init(i40e_init_module);
16550
16551 /**
16552  * i40e_exit_module - Driver exit cleanup routine
16553  *
16554  * i40e_exit_module is called just before the driver is removed
16555  * from memory.
16556  **/
16557 static void __exit i40e_exit_module(void)
16558 {
16559         pci_unregister_driver(&i40e_driver);
16560         destroy_workqueue(i40e_wq);
16561         ida_destroy(&i40e_client_ida);
16562         i40e_dbg_exit();
16563 }
16564 module_exit(i40e_exit_module);