GNU Linux-libre 6.8.9-gnu
[releases.git] / 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 <generated/utsrelease.h>
5 #include <linux/crash_dump.h>
6 #include <linux/if_bridge.h>
7 #include <linux/if_macvlan.h>
8 #include <linux/module.h>
9 #include <net/pkt_cls.h>
10 #include <net/xdp_sock_drv.h>
11
12 /* Local includes */
13 #include "i40e.h"
14 #include "i40e_devids.h"
15 #include "i40e_diag.h"
16 #include "i40e_lan_hmc.h"
17 #include "i40e_virtchnl_pf.h"
18 #include "i40e_xsk.h"
19
20 /* All i40e tracepoints are defined by the include below, which
21  * must be included exactly once across the whole kernel with
22  * CREATE_TRACE_POINTS defined
23  */
24 #define CREATE_TRACE_POINTS
25 #include "i40e_trace.h"
26
27 const char i40e_driver_name[] = "i40e";
28 static const char i40e_driver_string[] =
29                         "Intel(R) Ethernet Connection XL710 Network Driver";
30
31 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
32
33 /* a bit of forward declarations */
34 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
35 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
36 static int i40e_add_vsi(struct i40e_vsi *vsi);
37 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
38 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
39 static int i40e_setup_misc_vector(struct i40e_pf *pf);
40 static void i40e_determine_queue_usage(struct i40e_pf *pf);
41 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
42 static void i40e_prep_for_reset(struct i40e_pf *pf);
43 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
44                                    bool lock_acquired);
45 static int i40e_reset(struct i40e_pf *pf);
46 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
47 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
48 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
49 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
50 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
51 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
52 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
53 static int i40e_get_capabilities(struct i40e_pf *pf,
54                                  enum i40e_admin_queue_opc list_type);
55 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
56
57 /* i40e_pci_tbl - PCI Device ID Table
58  *
59  * Last entry must be all 0s
60  *
61  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
62  *   Class, Class Mask, private data (not used) }
63  */
64 static const struct pci_device_id i40e_pci_tbl[] = {
65         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
66         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
67         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
68         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
69         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
70         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
71         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
72         {PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_BC), 0},
73         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
74         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
75         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
76         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
77         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
78         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
79         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
80         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
81         {PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
82         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
83         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
84         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
85         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
86         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
87         {PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
88         {PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
89         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
90         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
91         /* required last entry */
92         {0, }
93 };
94 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
95
96 #define I40E_MAX_VF_COUNT 128
97 static int debug = -1;
98 module_param(debug, uint, 0);
99 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
100
101 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
102 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
103 MODULE_LICENSE("GPL v2");
104
105 static struct workqueue_struct *i40e_wq;
106
107 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
108                                   struct net_device *netdev, int delta)
109 {
110         struct netdev_hw_addr_list *ha_list;
111         struct netdev_hw_addr *ha;
112
113         if (!f || !netdev)
114                 return;
115
116         if (is_unicast_ether_addr(f->macaddr) || is_link_local_ether_addr(f->macaddr))
117                 ha_list = &netdev->uc;
118         else
119                 ha_list = &netdev->mc;
120
121         netdev_hw_addr_list_for_each(ha, ha_list) {
122                 if (ether_addr_equal(ha->addr, f->macaddr)) {
123                         ha->refcount += delta;
124                         if (ha->refcount <= 0)
125                                 ha->refcount = 1;
126                         break;
127                 }
128         }
129 }
130
131 /**
132  * i40e_hw_to_dev - get device pointer from the hardware structure
133  * @hw: pointer to the device HW structure
134  **/
135 struct device *i40e_hw_to_dev(struct i40e_hw *hw)
136 {
137         struct i40e_pf *pf = i40e_hw_to_pf(hw);
138
139         return &pf->pdev->dev;
140 }
141
142 /**
143  * i40e_allocate_dma_mem - OS specific memory alloc for shared code
144  * @hw:   pointer to the HW structure
145  * @mem:  ptr to mem struct to fill out
146  * @size: size of memory requested
147  * @alignment: what to align the allocation to
148  **/
149 int i40e_allocate_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem,
150                           u64 size, u32 alignment)
151 {
152         struct i40e_pf *pf = i40e_hw_to_pf(hw);
153
154         mem->size = ALIGN(size, alignment);
155         mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
156                                      GFP_KERNEL);
157         if (!mem->va)
158                 return -ENOMEM;
159
160         return 0;
161 }
162
163 /**
164  * i40e_free_dma_mem - OS specific memory free for shared code
165  * @hw:   pointer to the HW structure
166  * @mem:  ptr to mem struct to free
167  **/
168 int i40e_free_dma_mem(struct i40e_hw *hw, struct i40e_dma_mem *mem)
169 {
170         struct i40e_pf *pf = i40e_hw_to_pf(hw);
171
172         dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
173         mem->va = NULL;
174         mem->pa = 0;
175         mem->size = 0;
176
177         return 0;
178 }
179
180 /**
181  * i40e_allocate_virt_mem - OS specific memory alloc for shared code
182  * @hw:   pointer to the HW structure
183  * @mem:  ptr to mem struct to fill out
184  * @size: size of memory requested
185  **/
186 int i40e_allocate_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem,
187                            u32 size)
188 {
189         mem->size = size;
190         mem->va = kzalloc(size, GFP_KERNEL);
191
192         if (!mem->va)
193                 return -ENOMEM;
194
195         return 0;
196 }
197
198 /**
199  * i40e_free_virt_mem - OS specific memory free for shared code
200  * @hw:   pointer to the HW structure
201  * @mem:  ptr to mem struct to free
202  **/
203 int i40e_free_virt_mem(struct i40e_hw *hw, struct i40e_virt_mem *mem)
204 {
205         /* it's ok to kfree a NULL pointer */
206         kfree(mem->va);
207         mem->va = NULL;
208         mem->size = 0;
209
210         return 0;
211 }
212
213 /**
214  * i40e_get_lump - find a lump of free generic resource
215  * @pf: board private structure
216  * @pile: the pile of resource to search
217  * @needed: the number of items needed
218  * @id: an owner id to stick on the items assigned
219  *
220  * Returns the base item index of the lump, or negative for error
221  **/
222 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
223                          u16 needed, u16 id)
224 {
225         int ret = -ENOMEM;
226         int i, j;
227
228         if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
229                 dev_info(&pf->pdev->dev,
230                          "param err: pile=%s needed=%d id=0x%04x\n",
231                          pile ? "<valid>" : "<null>", needed, id);
232                 return -EINVAL;
233         }
234
235         /* Allocate last queue in the pile for FDIR VSI queue
236          * so it doesn't fragment the qp_pile
237          */
238         if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
239                 if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
240                         dev_err(&pf->pdev->dev,
241                                 "Cannot allocate queue %d for I40E_VSI_FDIR\n",
242                                 pile->num_entries - 1);
243                         return -ENOMEM;
244                 }
245                 pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
246                 return pile->num_entries - 1;
247         }
248
249         i = 0;
250         while (i < pile->num_entries) {
251                 /* skip already allocated entries */
252                 if (pile->list[i] & I40E_PILE_VALID_BIT) {
253                         i++;
254                         continue;
255                 }
256
257                 /* do we have enough in this lump? */
258                 for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
259                         if (pile->list[i+j] & I40E_PILE_VALID_BIT)
260                                 break;
261                 }
262
263                 if (j == needed) {
264                         /* there was enough, so assign it to the requestor */
265                         for (j = 0; j < needed; j++)
266                                 pile->list[i+j] = id | I40E_PILE_VALID_BIT;
267                         ret = i;
268                         break;
269                 }
270
271                 /* not enough, so skip over it and continue looking */
272                 i += j;
273         }
274
275         return ret;
276 }
277
278 /**
279  * i40e_put_lump - return a lump of generic resource
280  * @pile: the pile of resource to search
281  * @index: the base item index
282  * @id: the owner id of the items assigned
283  *
284  * Returns the count of items in the lump
285  **/
286 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
287 {
288         int valid_id = (id | I40E_PILE_VALID_BIT);
289         int count = 0;
290         u16 i;
291
292         if (!pile || index >= pile->num_entries)
293                 return -EINVAL;
294
295         for (i = index;
296              i < pile->num_entries && pile->list[i] == valid_id;
297              i++) {
298                 pile->list[i] = 0;
299                 count++;
300         }
301
302
303         return count;
304 }
305
306 /**
307  * i40e_find_vsi_from_id - searches for the vsi with the given id
308  * @pf: the pf structure to search for the vsi
309  * @id: id of the vsi it is searching for
310  **/
311 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
312 {
313         int i;
314
315         for (i = 0; i < pf->num_alloc_vsi; i++)
316                 if (pf->vsi[i] && (pf->vsi[i]->id == id))
317                         return pf->vsi[i];
318
319         return NULL;
320 }
321
322 /**
323  * i40e_service_event_schedule - Schedule the service task to wake up
324  * @pf: board private structure
325  *
326  * If not already scheduled, this puts the task into the work queue
327  **/
328 void i40e_service_event_schedule(struct i40e_pf *pf)
329 {
330         if ((!test_bit(__I40E_DOWN, pf->state) &&
331              !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
332               test_bit(__I40E_RECOVERY_MODE, pf->state))
333                 queue_work(i40e_wq, &pf->service_task);
334 }
335
336 /**
337  * i40e_tx_timeout - Respond to a Tx Hang
338  * @netdev: network interface device structure
339  * @txqueue: queue number timing out
340  *
341  * If any port has noticed a Tx timeout, it is likely that the whole
342  * device is munged, not just the one netdev port, so go for the full
343  * reset.
344  **/
345 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
346 {
347         struct i40e_netdev_priv *np = netdev_priv(netdev);
348         struct i40e_vsi *vsi = np->vsi;
349         struct i40e_pf *pf = vsi->back;
350         struct i40e_ring *tx_ring = NULL;
351         unsigned int i;
352         u32 head, val;
353
354         pf->tx_timeout_count++;
355
356         /* with txqueue index, find the tx_ring struct */
357         for (i = 0; i < vsi->num_queue_pairs; i++) {
358                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
359                         if (txqueue ==
360                             vsi->tx_rings[i]->queue_index) {
361                                 tx_ring = vsi->tx_rings[i];
362                                 break;
363                         }
364                 }
365         }
366
367         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
368                 pf->tx_timeout_recovery_level = 1;  /* reset after some time */
369         else if (time_before(jiffies,
370                       (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
371                 return;   /* don't do any new action before the next timeout */
372
373         /* don't kick off another recovery if one is already pending */
374         if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
375                 return;
376
377         if (tx_ring) {
378                 head = i40e_get_head(tx_ring);
379                 /* Read interrupt register */
380                 if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
381                         val = rd32(&pf->hw,
382                              I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
383                                                 tx_ring->vsi->base_vector - 1));
384                 else
385                         val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
386
387                 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",
388                             vsi->seid, txqueue, tx_ring->next_to_clean,
389                             head, tx_ring->next_to_use,
390                             readl(tx_ring->tail), val);
391         }
392
393         pf->tx_timeout_last_recovery = jiffies;
394         netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
395                     pf->tx_timeout_recovery_level, txqueue);
396
397         switch (pf->tx_timeout_recovery_level) {
398         case 1:
399                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
400                 break;
401         case 2:
402                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
403                 break;
404         case 3:
405                 set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
406                 break;
407         default:
408                 netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
409                 set_bit(__I40E_DOWN_REQUESTED, pf->state);
410                 set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
411                 break;
412         }
413
414         i40e_service_event_schedule(pf);
415         pf->tx_timeout_recovery_level++;
416 }
417
418 /**
419  * i40e_get_vsi_stats_struct - Get System Network Statistics
420  * @vsi: the VSI we care about
421  *
422  * Returns the address of the device statistics structure.
423  * The statistics are actually updated from the service task.
424  **/
425 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
426 {
427         return &vsi->net_stats;
428 }
429
430 /**
431  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
432  * @ring: Tx ring to get statistics from
433  * @stats: statistics entry to be updated
434  **/
435 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
436                                             struct rtnl_link_stats64 *stats)
437 {
438         u64 bytes, packets;
439         unsigned int start;
440
441         do {
442                 start = u64_stats_fetch_begin(&ring->syncp);
443                 packets = ring->stats.packets;
444                 bytes   = ring->stats.bytes;
445         } while (u64_stats_fetch_retry(&ring->syncp, start));
446
447         stats->tx_packets += packets;
448         stats->tx_bytes   += bytes;
449 }
450
451 /**
452  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
453  * @netdev: network interface device structure
454  * @stats: data structure to store statistics
455  *
456  * Returns the address of the device statistics structure.
457  * The statistics are actually updated from the service task.
458  **/
459 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
460                                   struct rtnl_link_stats64 *stats)
461 {
462         struct i40e_netdev_priv *np = netdev_priv(netdev);
463         struct i40e_vsi *vsi = np->vsi;
464         struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
465         struct i40e_ring *ring;
466         int i;
467
468         if (test_bit(__I40E_VSI_DOWN, vsi->state))
469                 return;
470
471         if (!vsi->tx_rings)
472                 return;
473
474         rcu_read_lock();
475         for (i = 0; i < vsi->num_queue_pairs; i++) {
476                 u64 bytes, packets;
477                 unsigned int start;
478
479                 ring = READ_ONCE(vsi->tx_rings[i]);
480                 if (!ring)
481                         continue;
482                 i40e_get_netdev_stats_struct_tx(ring, stats);
483
484                 if (i40e_enabled_xdp_vsi(vsi)) {
485                         ring = READ_ONCE(vsi->xdp_rings[i]);
486                         if (!ring)
487                                 continue;
488                         i40e_get_netdev_stats_struct_tx(ring, stats);
489                 }
490
491                 ring = READ_ONCE(vsi->rx_rings[i]);
492                 if (!ring)
493                         continue;
494                 do {
495                         start   = u64_stats_fetch_begin(&ring->syncp);
496                         packets = ring->stats.packets;
497                         bytes   = ring->stats.bytes;
498                 } while (u64_stats_fetch_retry(&ring->syncp, start));
499
500                 stats->rx_packets += packets;
501                 stats->rx_bytes   += bytes;
502
503         }
504         rcu_read_unlock();
505
506         /* following stats updated by i40e_watchdog_subtask() */
507         stats->multicast        = vsi_stats->multicast;
508         stats->tx_errors        = vsi_stats->tx_errors;
509         stats->tx_dropped       = vsi_stats->tx_dropped;
510         stats->rx_errors        = vsi_stats->rx_errors;
511         stats->rx_dropped       = vsi_stats->rx_dropped;
512         stats->rx_missed_errors = vsi_stats->rx_missed_errors;
513         stats->rx_crc_errors    = vsi_stats->rx_crc_errors;
514         stats->rx_length_errors = vsi_stats->rx_length_errors;
515 }
516
517 /**
518  * i40e_vsi_reset_stats - Resets all stats of the given vsi
519  * @vsi: the VSI to have its stats reset
520  **/
521 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
522 {
523         struct rtnl_link_stats64 *ns;
524         int i;
525
526         if (!vsi)
527                 return;
528
529         ns = i40e_get_vsi_stats_struct(vsi);
530         memset(ns, 0, sizeof(*ns));
531         memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
532         memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
533         memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
534         if (vsi->rx_rings && vsi->rx_rings[0]) {
535                 for (i = 0; i < vsi->num_queue_pairs; i++) {
536                         memset(&vsi->rx_rings[i]->stats, 0,
537                                sizeof(vsi->rx_rings[i]->stats));
538                         memset(&vsi->rx_rings[i]->rx_stats, 0,
539                                sizeof(vsi->rx_rings[i]->rx_stats));
540                         memset(&vsi->tx_rings[i]->stats, 0,
541                                sizeof(vsi->tx_rings[i]->stats));
542                         memset(&vsi->tx_rings[i]->tx_stats, 0,
543                                sizeof(vsi->tx_rings[i]->tx_stats));
544                 }
545         }
546         vsi->stat_offsets_loaded = false;
547 }
548
549 /**
550  * i40e_pf_reset_stats - Reset all of the stats for the given PF
551  * @pf: the PF to be reset
552  **/
553 void i40e_pf_reset_stats(struct i40e_pf *pf)
554 {
555         int i;
556
557         memset(&pf->stats, 0, sizeof(pf->stats));
558         memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
559         pf->stat_offsets_loaded = false;
560
561         for (i = 0; i < I40E_MAX_VEB; i++) {
562                 if (pf->veb[i]) {
563                         memset(&pf->veb[i]->stats, 0,
564                                sizeof(pf->veb[i]->stats));
565                         memset(&pf->veb[i]->stats_offsets, 0,
566                                sizeof(pf->veb[i]->stats_offsets));
567                         memset(&pf->veb[i]->tc_stats, 0,
568                                sizeof(pf->veb[i]->tc_stats));
569                         memset(&pf->veb[i]->tc_stats_offsets, 0,
570                                sizeof(pf->veb[i]->tc_stats_offsets));
571                         pf->veb[i]->stat_offsets_loaded = false;
572                 }
573         }
574         pf->hw_csum_rx_error = 0;
575 }
576
577 /**
578  * i40e_compute_pci_to_hw_id - compute index form PCI function.
579  * @vsi: ptr to the VSI to read from.
580  * @hw: ptr to the hardware info.
581  **/
582 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
583 {
584         int pf_count = i40e_get_pf_count(hw);
585
586         if (vsi->type == I40E_VSI_SRIOV)
587                 return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
588
589         return hw->port + BIT(7);
590 }
591
592 /**
593  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
594  * @hw: ptr to the hardware info.
595  * @hireg: the high 32 bit reg to read.
596  * @loreg: the low 32 bit reg to read.
597  * @offset_loaded: has the initial offset been loaded yet.
598  * @offset: ptr to current offset value.
599  * @stat: ptr to the stat.
600  *
601  * Since the device stats are not reset at PFReset, they will not
602  * be zeroed when the driver starts.  We'll save the first values read
603  * and use them as offsets to be subtracted from the raw values in order
604  * to report stats that count from zero.
605  **/
606 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
607                                bool offset_loaded, u64 *offset, u64 *stat)
608 {
609         u64 new_data;
610
611         new_data = rd64(hw, loreg);
612
613         if (!offset_loaded || new_data < *offset)
614                 *offset = new_data;
615         *stat = new_data - *offset;
616 }
617
618 /**
619  * i40e_stat_update48 - read and update a 48 bit stat from the chip
620  * @hw: ptr to the hardware info
621  * @hireg: the high 32 bit reg to read
622  * @loreg: the low 32 bit reg to read
623  * @offset_loaded: has the initial offset been loaded yet
624  * @offset: ptr to current offset value
625  * @stat: ptr to the stat
626  *
627  * Since the device stats are not reset at PFReset, they likely will not
628  * be zeroed when the driver starts.  We'll save the first values read
629  * and use them as offsets to be subtracted from the raw values in order
630  * to report stats that count from zero.  In the process, we also manage
631  * the potential roll-over.
632  **/
633 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
634                                bool offset_loaded, u64 *offset, u64 *stat)
635 {
636         u64 new_data;
637
638         if (hw->device_id == I40E_DEV_ID_QEMU) {
639                 new_data = rd32(hw, loreg);
640                 new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
641         } else {
642                 new_data = rd64(hw, loreg);
643         }
644         if (!offset_loaded)
645                 *offset = new_data;
646         if (likely(new_data >= *offset))
647                 *stat = new_data - *offset;
648         else
649                 *stat = (new_data + BIT_ULL(48)) - *offset;
650         *stat &= 0xFFFFFFFFFFFFULL;
651 }
652
653 /**
654  * i40e_stat_update32 - read and update a 32 bit stat from the chip
655  * @hw: ptr to the hardware info
656  * @reg: the hw reg to read
657  * @offset_loaded: has the initial offset been loaded yet
658  * @offset: ptr to current offset value
659  * @stat: ptr to the stat
660  **/
661 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
662                                bool offset_loaded, u64 *offset, u64 *stat)
663 {
664         u32 new_data;
665
666         new_data = rd32(hw, reg);
667         if (!offset_loaded)
668                 *offset = new_data;
669         if (likely(new_data >= *offset))
670                 *stat = (u32)(new_data - *offset);
671         else
672                 *stat = (u32)((new_data + BIT_ULL(32)) - *offset);
673 }
674
675 /**
676  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
677  * @hw: ptr to the hardware info
678  * @reg: the hw reg to read and clear
679  * @stat: ptr to the stat
680  **/
681 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
682 {
683         u32 new_data = rd32(hw, reg);
684
685         wr32(hw, reg, 1); /* must write a nonzero value to clear register */
686         *stat += new_data;
687 }
688
689 /**
690  * i40e_stats_update_rx_discards - update rx_discards.
691  * @vsi: ptr to the VSI to be updated.
692  * @hw: ptr to the hardware info.
693  * @stat_idx: VSI's stat_counter_idx.
694  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
695  * @stat_offset: ptr to stat_offset to store first read of specific register.
696  * @stat: ptr to VSI's stat to be updated.
697  **/
698 static void
699 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
700                               int stat_idx, bool offset_loaded,
701                               struct i40e_eth_stats *stat_offset,
702                               struct i40e_eth_stats *stat)
703 {
704         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
705                            &stat_offset->rx_discards, &stat->rx_discards);
706         i40e_stat_update64(hw,
707                            I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
708                            I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
709                            offset_loaded, &stat_offset->rx_discards_other,
710                            &stat->rx_discards_other);
711 }
712
713 /**
714  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
715  * @vsi: the VSI to be updated
716  **/
717 void i40e_update_eth_stats(struct i40e_vsi *vsi)
718 {
719         int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
720         struct i40e_pf *pf = vsi->back;
721         struct i40e_hw *hw = &pf->hw;
722         struct i40e_eth_stats *oes;
723         struct i40e_eth_stats *es;     /* device's eth stats */
724
725         es = &vsi->eth_stats;
726         oes = &vsi->eth_stats_offsets;
727
728         /* Gather up the stats that the hw collects */
729         i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
730                            vsi->stat_offsets_loaded,
731                            &oes->tx_errors, &es->tx_errors);
732         i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
733                            vsi->stat_offsets_loaded,
734                            &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
735
736         i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
737                            I40E_GLV_GORCL(stat_idx),
738                            vsi->stat_offsets_loaded,
739                            &oes->rx_bytes, &es->rx_bytes);
740         i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
741                            I40E_GLV_UPRCL(stat_idx),
742                            vsi->stat_offsets_loaded,
743                            &oes->rx_unicast, &es->rx_unicast);
744         i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
745                            I40E_GLV_MPRCL(stat_idx),
746                            vsi->stat_offsets_loaded,
747                            &oes->rx_multicast, &es->rx_multicast);
748         i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
749                            I40E_GLV_BPRCL(stat_idx),
750                            vsi->stat_offsets_loaded,
751                            &oes->rx_broadcast, &es->rx_broadcast);
752
753         i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
754                            I40E_GLV_GOTCL(stat_idx),
755                            vsi->stat_offsets_loaded,
756                            &oes->tx_bytes, &es->tx_bytes);
757         i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
758                            I40E_GLV_UPTCL(stat_idx),
759                            vsi->stat_offsets_loaded,
760                            &oes->tx_unicast, &es->tx_unicast);
761         i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
762                            I40E_GLV_MPTCL(stat_idx),
763                            vsi->stat_offsets_loaded,
764                            &oes->tx_multicast, &es->tx_multicast);
765         i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
766                            I40E_GLV_BPTCL(stat_idx),
767                            vsi->stat_offsets_loaded,
768                            &oes->tx_broadcast, &es->tx_broadcast);
769
770         i40e_stats_update_rx_discards(vsi, hw, stat_idx,
771                                       vsi->stat_offsets_loaded, oes, es);
772
773         vsi->stat_offsets_loaded = true;
774 }
775
776 /**
777  * i40e_update_veb_stats - Update Switch component statistics
778  * @veb: the VEB being updated
779  **/
780 void i40e_update_veb_stats(struct i40e_veb *veb)
781 {
782         struct i40e_pf *pf = veb->pf;
783         struct i40e_hw *hw = &pf->hw;
784         struct i40e_eth_stats *oes;
785         struct i40e_eth_stats *es;     /* device's eth stats */
786         struct i40e_veb_tc_stats *veb_oes;
787         struct i40e_veb_tc_stats *veb_es;
788         int i, idx = 0;
789
790         idx = veb->stats_idx;
791         es = &veb->stats;
792         oes = &veb->stats_offsets;
793         veb_es = &veb->tc_stats;
794         veb_oes = &veb->tc_stats_offsets;
795
796         /* Gather up the stats that the hw collects */
797         i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
798                            veb->stat_offsets_loaded,
799                            &oes->tx_discards, &es->tx_discards);
800         if (hw->revision_id > 0)
801                 i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
802                                    veb->stat_offsets_loaded,
803                                    &oes->rx_unknown_protocol,
804                                    &es->rx_unknown_protocol);
805         i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
806                            veb->stat_offsets_loaded,
807                            &oes->rx_bytes, &es->rx_bytes);
808         i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
809                            veb->stat_offsets_loaded,
810                            &oes->rx_unicast, &es->rx_unicast);
811         i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
812                            veb->stat_offsets_loaded,
813                            &oes->rx_multicast, &es->rx_multicast);
814         i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
815                            veb->stat_offsets_loaded,
816                            &oes->rx_broadcast, &es->rx_broadcast);
817
818         i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
819                            veb->stat_offsets_loaded,
820                            &oes->tx_bytes, &es->tx_bytes);
821         i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
822                            veb->stat_offsets_loaded,
823                            &oes->tx_unicast, &es->tx_unicast);
824         i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
825                            veb->stat_offsets_loaded,
826                            &oes->tx_multicast, &es->tx_multicast);
827         i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
828                            veb->stat_offsets_loaded,
829                            &oes->tx_broadcast, &es->tx_broadcast);
830         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
831                 i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
832                                    I40E_GLVEBTC_RPCL(i, idx),
833                                    veb->stat_offsets_loaded,
834                                    &veb_oes->tc_rx_packets[i],
835                                    &veb_es->tc_rx_packets[i]);
836                 i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
837                                    I40E_GLVEBTC_RBCL(i, idx),
838                                    veb->stat_offsets_loaded,
839                                    &veb_oes->tc_rx_bytes[i],
840                                    &veb_es->tc_rx_bytes[i]);
841                 i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
842                                    I40E_GLVEBTC_TPCL(i, idx),
843                                    veb->stat_offsets_loaded,
844                                    &veb_oes->tc_tx_packets[i],
845                                    &veb_es->tc_tx_packets[i]);
846                 i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
847                                    I40E_GLVEBTC_TBCL(i, idx),
848                                    veb->stat_offsets_loaded,
849                                    &veb_oes->tc_tx_bytes[i],
850                                    &veb_es->tc_tx_bytes[i]);
851         }
852         veb->stat_offsets_loaded = true;
853 }
854
855 /**
856  * i40e_update_vsi_stats - Update the vsi statistics counters.
857  * @vsi: the VSI to be updated
858  *
859  * There are a few instances where we store the same stat in a
860  * couple of different structs.  This is partly because we have
861  * the netdev stats that need to be filled out, which is slightly
862  * different from the "eth_stats" defined by the chip and used in
863  * VF communications.  We sort it out here.
864  **/
865 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
866 {
867         u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
868         struct i40e_pf *pf = vsi->back;
869         struct rtnl_link_stats64 *ons;
870         struct rtnl_link_stats64 *ns;   /* netdev stats */
871         struct i40e_eth_stats *oes;
872         struct i40e_eth_stats *es;     /* device's eth stats */
873         u64 tx_restart, tx_busy;
874         struct i40e_ring *p;
875         u64 bytes, packets;
876         unsigned int start;
877         u64 tx_linearize;
878         u64 tx_force_wb;
879         u64 tx_stopped;
880         u64 rx_p, rx_b;
881         u64 tx_p, tx_b;
882         u16 q;
883
884         if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
885             test_bit(__I40E_CONFIG_BUSY, pf->state))
886                 return;
887
888         ns = i40e_get_vsi_stats_struct(vsi);
889         ons = &vsi->net_stats_offsets;
890         es = &vsi->eth_stats;
891         oes = &vsi->eth_stats_offsets;
892
893         /* Gather up the netdev and vsi stats that the driver collects
894          * on the fly during packet processing
895          */
896         rx_b = rx_p = 0;
897         tx_b = tx_p = 0;
898         tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
899         tx_stopped = 0;
900         rx_page = 0;
901         rx_buf = 0;
902         rx_reuse = 0;
903         rx_alloc = 0;
904         rx_waive = 0;
905         rx_busy = 0;
906         rcu_read_lock();
907         for (q = 0; q < vsi->num_queue_pairs; q++) {
908                 /* locate Tx ring */
909                 p = READ_ONCE(vsi->tx_rings[q]);
910                 if (!p)
911                         continue;
912
913                 do {
914                         start = u64_stats_fetch_begin(&p->syncp);
915                         packets = p->stats.packets;
916                         bytes = p->stats.bytes;
917                 } while (u64_stats_fetch_retry(&p->syncp, start));
918                 tx_b += bytes;
919                 tx_p += packets;
920                 tx_restart += p->tx_stats.restart_queue;
921                 tx_busy += p->tx_stats.tx_busy;
922                 tx_linearize += p->tx_stats.tx_linearize;
923                 tx_force_wb += p->tx_stats.tx_force_wb;
924                 tx_stopped += p->tx_stats.tx_stopped;
925
926                 /* locate Rx ring */
927                 p = READ_ONCE(vsi->rx_rings[q]);
928                 if (!p)
929                         continue;
930
931                 do {
932                         start = u64_stats_fetch_begin(&p->syncp);
933                         packets = p->stats.packets;
934                         bytes = p->stats.bytes;
935                 } while (u64_stats_fetch_retry(&p->syncp, start));
936                 rx_b += bytes;
937                 rx_p += packets;
938                 rx_buf += p->rx_stats.alloc_buff_failed;
939                 rx_page += p->rx_stats.alloc_page_failed;
940                 rx_reuse += p->rx_stats.page_reuse_count;
941                 rx_alloc += p->rx_stats.page_alloc_count;
942                 rx_waive += p->rx_stats.page_waive_count;
943                 rx_busy += p->rx_stats.page_busy_count;
944
945                 if (i40e_enabled_xdp_vsi(vsi)) {
946                         /* locate XDP ring */
947                         p = READ_ONCE(vsi->xdp_rings[q]);
948                         if (!p)
949                                 continue;
950
951                         do {
952                                 start = u64_stats_fetch_begin(&p->syncp);
953                                 packets = p->stats.packets;
954                                 bytes = p->stats.bytes;
955                         } while (u64_stats_fetch_retry(&p->syncp, start));
956                         tx_b += bytes;
957                         tx_p += packets;
958                         tx_restart += p->tx_stats.restart_queue;
959                         tx_busy += p->tx_stats.tx_busy;
960                         tx_linearize += p->tx_stats.tx_linearize;
961                         tx_force_wb += p->tx_stats.tx_force_wb;
962                 }
963         }
964         rcu_read_unlock();
965         vsi->tx_restart = tx_restart;
966         vsi->tx_busy = tx_busy;
967         vsi->tx_linearize = tx_linearize;
968         vsi->tx_force_wb = tx_force_wb;
969         vsi->tx_stopped = tx_stopped;
970         vsi->rx_page_failed = rx_page;
971         vsi->rx_buf_failed = rx_buf;
972         vsi->rx_page_reuse = rx_reuse;
973         vsi->rx_page_alloc = rx_alloc;
974         vsi->rx_page_waive = rx_waive;
975         vsi->rx_page_busy = rx_busy;
976
977         ns->rx_packets = rx_p;
978         ns->rx_bytes = rx_b;
979         ns->tx_packets = tx_p;
980         ns->tx_bytes = tx_b;
981
982         /* update netdev stats from eth stats */
983         i40e_update_eth_stats(vsi);
984         ons->tx_errors = oes->tx_errors;
985         ns->tx_errors = es->tx_errors;
986         ons->multicast = oes->rx_multicast;
987         ns->multicast = es->rx_multicast;
988         ons->rx_dropped = oes->rx_discards_other;
989         ns->rx_dropped = es->rx_discards_other;
990         ons->rx_missed_errors = oes->rx_discards;
991         ns->rx_missed_errors = es->rx_discards;
992         ons->tx_dropped = oes->tx_discards;
993         ns->tx_dropped = es->tx_discards;
994
995         /* pull in a couple PF stats if this is the main vsi */
996         if (vsi == pf->vsi[pf->lan_vsi]) {
997                 ns->rx_crc_errors = pf->stats.crc_errors;
998                 ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
999                 ns->rx_length_errors = pf->stats.rx_length_errors;
1000         }
1001 }
1002
1003 /**
1004  * i40e_update_pf_stats - Update the PF statistics counters.
1005  * @pf: the PF to be updated
1006  **/
1007 static void i40e_update_pf_stats(struct i40e_pf *pf)
1008 {
1009         struct i40e_hw_port_stats *osd = &pf->stats_offsets;
1010         struct i40e_hw_port_stats *nsd = &pf->stats;
1011         struct i40e_hw *hw = &pf->hw;
1012         u32 val;
1013         int i;
1014
1015         i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
1016                            I40E_GLPRT_GORCL(hw->port),
1017                            pf->stat_offsets_loaded,
1018                            &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1019         i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1020                            I40E_GLPRT_GOTCL(hw->port),
1021                            pf->stat_offsets_loaded,
1022                            &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1023         i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1024                            pf->stat_offsets_loaded,
1025                            &osd->eth.rx_discards,
1026                            &nsd->eth.rx_discards);
1027         i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1028                            I40E_GLPRT_UPRCL(hw->port),
1029                            pf->stat_offsets_loaded,
1030                            &osd->eth.rx_unicast,
1031                            &nsd->eth.rx_unicast);
1032         i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1033                            I40E_GLPRT_MPRCL(hw->port),
1034                            pf->stat_offsets_loaded,
1035                            &osd->eth.rx_multicast,
1036                            &nsd->eth.rx_multicast);
1037         i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1038                            I40E_GLPRT_BPRCL(hw->port),
1039                            pf->stat_offsets_loaded,
1040                            &osd->eth.rx_broadcast,
1041                            &nsd->eth.rx_broadcast);
1042         i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1043                            I40E_GLPRT_UPTCL(hw->port),
1044                            pf->stat_offsets_loaded,
1045                            &osd->eth.tx_unicast,
1046                            &nsd->eth.tx_unicast);
1047         i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1048                            I40E_GLPRT_MPTCL(hw->port),
1049                            pf->stat_offsets_loaded,
1050                            &osd->eth.tx_multicast,
1051                            &nsd->eth.tx_multicast);
1052         i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1053                            I40E_GLPRT_BPTCL(hw->port),
1054                            pf->stat_offsets_loaded,
1055                            &osd->eth.tx_broadcast,
1056                            &nsd->eth.tx_broadcast);
1057
1058         i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1059                            pf->stat_offsets_loaded,
1060                            &osd->tx_dropped_link_down,
1061                            &nsd->tx_dropped_link_down);
1062
1063         i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1064                            pf->stat_offsets_loaded,
1065                            &osd->crc_errors, &nsd->crc_errors);
1066
1067         i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1068                            pf->stat_offsets_loaded,
1069                            &osd->illegal_bytes, &nsd->illegal_bytes);
1070
1071         i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1072                            pf->stat_offsets_loaded,
1073                            &osd->mac_local_faults,
1074                            &nsd->mac_local_faults);
1075         i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1076                            pf->stat_offsets_loaded,
1077                            &osd->mac_remote_faults,
1078                            &nsd->mac_remote_faults);
1079
1080         i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1081                            pf->stat_offsets_loaded,
1082                            &osd->rx_length_errors,
1083                            &nsd->rx_length_errors);
1084
1085         i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1086                            pf->stat_offsets_loaded,
1087                            &osd->link_xon_rx, &nsd->link_xon_rx);
1088         i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1089                            pf->stat_offsets_loaded,
1090                            &osd->link_xon_tx, &nsd->link_xon_tx);
1091         i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1092                            pf->stat_offsets_loaded,
1093                            &osd->link_xoff_rx, &nsd->link_xoff_rx);
1094         i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1095                            pf->stat_offsets_loaded,
1096                            &osd->link_xoff_tx, &nsd->link_xoff_tx);
1097
1098         for (i = 0; i < 8; i++) {
1099                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1100                                    pf->stat_offsets_loaded,
1101                                    &osd->priority_xoff_rx[i],
1102                                    &nsd->priority_xoff_rx[i]);
1103                 i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1104                                    pf->stat_offsets_loaded,
1105                                    &osd->priority_xon_rx[i],
1106                                    &nsd->priority_xon_rx[i]);
1107                 i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1108                                    pf->stat_offsets_loaded,
1109                                    &osd->priority_xon_tx[i],
1110                                    &nsd->priority_xon_tx[i]);
1111                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1112                                    pf->stat_offsets_loaded,
1113                                    &osd->priority_xoff_tx[i],
1114                                    &nsd->priority_xoff_tx[i]);
1115                 i40e_stat_update32(hw,
1116                                    I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1117                                    pf->stat_offsets_loaded,
1118                                    &osd->priority_xon_2_xoff[i],
1119                                    &nsd->priority_xon_2_xoff[i]);
1120         }
1121
1122         i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1123                            I40E_GLPRT_PRC64L(hw->port),
1124                            pf->stat_offsets_loaded,
1125                            &osd->rx_size_64, &nsd->rx_size_64);
1126         i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1127                            I40E_GLPRT_PRC127L(hw->port),
1128                            pf->stat_offsets_loaded,
1129                            &osd->rx_size_127, &nsd->rx_size_127);
1130         i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1131                            I40E_GLPRT_PRC255L(hw->port),
1132                            pf->stat_offsets_loaded,
1133                            &osd->rx_size_255, &nsd->rx_size_255);
1134         i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1135                            I40E_GLPRT_PRC511L(hw->port),
1136                            pf->stat_offsets_loaded,
1137                            &osd->rx_size_511, &nsd->rx_size_511);
1138         i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1139                            I40E_GLPRT_PRC1023L(hw->port),
1140                            pf->stat_offsets_loaded,
1141                            &osd->rx_size_1023, &nsd->rx_size_1023);
1142         i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1143                            I40E_GLPRT_PRC1522L(hw->port),
1144                            pf->stat_offsets_loaded,
1145                            &osd->rx_size_1522, &nsd->rx_size_1522);
1146         i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1147                            I40E_GLPRT_PRC9522L(hw->port),
1148                            pf->stat_offsets_loaded,
1149                            &osd->rx_size_big, &nsd->rx_size_big);
1150
1151         i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1152                            I40E_GLPRT_PTC64L(hw->port),
1153                            pf->stat_offsets_loaded,
1154                            &osd->tx_size_64, &nsd->tx_size_64);
1155         i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1156                            I40E_GLPRT_PTC127L(hw->port),
1157                            pf->stat_offsets_loaded,
1158                            &osd->tx_size_127, &nsd->tx_size_127);
1159         i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1160                            I40E_GLPRT_PTC255L(hw->port),
1161                            pf->stat_offsets_loaded,
1162                            &osd->tx_size_255, &nsd->tx_size_255);
1163         i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1164                            I40E_GLPRT_PTC511L(hw->port),
1165                            pf->stat_offsets_loaded,
1166                            &osd->tx_size_511, &nsd->tx_size_511);
1167         i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1168                            I40E_GLPRT_PTC1023L(hw->port),
1169                            pf->stat_offsets_loaded,
1170                            &osd->tx_size_1023, &nsd->tx_size_1023);
1171         i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1172                            I40E_GLPRT_PTC1522L(hw->port),
1173                            pf->stat_offsets_loaded,
1174                            &osd->tx_size_1522, &nsd->tx_size_1522);
1175         i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1176                            I40E_GLPRT_PTC9522L(hw->port),
1177                            pf->stat_offsets_loaded,
1178                            &osd->tx_size_big, &nsd->tx_size_big);
1179
1180         i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1181                            pf->stat_offsets_loaded,
1182                            &osd->rx_undersize, &nsd->rx_undersize);
1183         i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1184                            pf->stat_offsets_loaded,
1185                            &osd->rx_fragments, &nsd->rx_fragments);
1186         i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1187                            pf->stat_offsets_loaded,
1188                            &osd->rx_oversize, &nsd->rx_oversize);
1189         i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1190                            pf->stat_offsets_loaded,
1191                            &osd->rx_jabber, &nsd->rx_jabber);
1192
1193         /* FDIR stats */
1194         i40e_stat_update_and_clear32(hw,
1195                         I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1196                         &nsd->fd_atr_match);
1197         i40e_stat_update_and_clear32(hw,
1198                         I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1199                         &nsd->fd_sb_match);
1200         i40e_stat_update_and_clear32(hw,
1201                         I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1202                         &nsd->fd_atr_tunnel_match);
1203
1204         val = rd32(hw, I40E_PRTPM_EEE_STAT);
1205         nsd->tx_lpi_status =
1206                        FIELD_GET(I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK, val);
1207         nsd->rx_lpi_status =
1208                        FIELD_GET(I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK, val);
1209         i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1210                            pf->stat_offsets_loaded,
1211                            &osd->tx_lpi_count, &nsd->tx_lpi_count);
1212         i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1213                            pf->stat_offsets_loaded,
1214                            &osd->rx_lpi_count, &nsd->rx_lpi_count);
1215
1216         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
1217             !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1218                 nsd->fd_sb_status = true;
1219         else
1220                 nsd->fd_sb_status = false;
1221
1222         if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
1223             !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1224                 nsd->fd_atr_status = true;
1225         else
1226                 nsd->fd_atr_status = false;
1227
1228         pf->stat_offsets_loaded = true;
1229 }
1230
1231 /**
1232  * i40e_update_stats - Update the various statistics counters.
1233  * @vsi: the VSI to be updated
1234  *
1235  * Update the various stats for this VSI and its related entities.
1236  **/
1237 void i40e_update_stats(struct i40e_vsi *vsi)
1238 {
1239         struct i40e_pf *pf = vsi->back;
1240
1241         if (vsi == pf->vsi[pf->lan_vsi])
1242                 i40e_update_pf_stats(pf);
1243
1244         i40e_update_vsi_stats(vsi);
1245 }
1246
1247 /**
1248  * i40e_count_filters - counts VSI mac filters
1249  * @vsi: the VSI to be searched
1250  *
1251  * Returns count of mac filters
1252  **/
1253 int i40e_count_filters(struct i40e_vsi *vsi)
1254 {
1255         struct i40e_mac_filter *f;
1256         struct hlist_node *h;
1257         int bkt;
1258         int cnt = 0;
1259
1260         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1261                 if (f->state == I40E_FILTER_NEW ||
1262                     f->state == I40E_FILTER_ACTIVE)
1263                         ++cnt;
1264         }
1265
1266         return cnt;
1267 }
1268
1269 /**
1270  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1271  * @vsi: the VSI to be searched
1272  * @macaddr: the MAC address
1273  * @vlan: the vlan
1274  *
1275  * Returns ptr to the filter object or NULL
1276  **/
1277 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1278                                                 const u8 *macaddr, s16 vlan)
1279 {
1280         struct i40e_mac_filter *f;
1281         u64 key;
1282
1283         if (!vsi || !macaddr)
1284                 return NULL;
1285
1286         key = i40e_addr_to_hkey(macaddr);
1287         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1288                 if ((ether_addr_equal(macaddr, f->macaddr)) &&
1289                     (vlan == f->vlan))
1290                         return f;
1291         }
1292         return NULL;
1293 }
1294
1295 /**
1296  * i40e_find_mac - Find a mac addr in the macvlan filters list
1297  * @vsi: the VSI to be searched
1298  * @macaddr: the MAC address we are searching for
1299  *
1300  * Returns the first filter with the provided MAC address or NULL if
1301  * MAC address was not found
1302  **/
1303 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1304 {
1305         struct i40e_mac_filter *f;
1306         u64 key;
1307
1308         if (!vsi || !macaddr)
1309                 return NULL;
1310
1311         key = i40e_addr_to_hkey(macaddr);
1312         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1313                 if ((ether_addr_equal(macaddr, f->macaddr)))
1314                         return f;
1315         }
1316         return NULL;
1317 }
1318
1319 /**
1320  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1321  * @vsi: the VSI to be searched
1322  *
1323  * Returns true if VSI is in vlan mode or false otherwise
1324  **/
1325 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1326 {
1327         /* If we have a PVID, always operate in VLAN mode */
1328         if (vsi->info.pvid)
1329                 return true;
1330
1331         /* We need to operate in VLAN mode whenever we have any filters with
1332          * a VLAN other than I40E_VLAN_ALL. We could check the table each
1333          * time, incurring search cost repeatedly. However, we can notice two
1334          * things:
1335          *
1336          * 1) the only place where we can gain a VLAN filter is in
1337          *    i40e_add_filter.
1338          *
1339          * 2) the only place where filters are actually removed is in
1340          *    i40e_sync_filters_subtask.
1341          *
1342          * Thus, we can simply use a boolean value, has_vlan_filters which we
1343          * will set to true when we add a VLAN filter in i40e_add_filter. Then
1344          * we have to perform the full search after deleting filters in
1345          * i40e_sync_filters_subtask, but we already have to search
1346          * filters here and can perform the check at the same time. This
1347          * results in avoiding embedding a loop for VLAN mode inside another
1348          * loop over all the filters, and should maintain correctness as noted
1349          * above.
1350          */
1351         return vsi->has_vlan_filter;
1352 }
1353
1354 /**
1355  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1356  * @vsi: the VSI to configure
1357  * @tmp_add_list: list of filters ready to be added
1358  * @tmp_del_list: list of filters ready to be deleted
1359  * @vlan_filters: the number of active VLAN filters
1360  *
1361  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1362  * behave as expected. If we have any active VLAN filters remaining or about
1363  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1364  * so that they only match against untagged traffic. If we no longer have any
1365  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1366  * so that they match against both tagged and untagged traffic. In this way,
1367  * we ensure that we correctly receive the desired traffic. This ensures that
1368  * when we have an active VLAN we will receive only untagged traffic and
1369  * traffic matching active VLANs. If we have no active VLANs then we will
1370  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1371  *
1372  * Finally, in a similar fashion, this function also corrects filters when
1373  * there is an active PVID assigned to this VSI.
1374  *
1375  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1376  *
1377  * This function is only expected to be called from within
1378  * i40e_sync_vsi_filters.
1379  *
1380  * NOTE: This function expects to be called while under the
1381  * mac_filter_hash_lock
1382  */
1383 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1384                                          struct hlist_head *tmp_add_list,
1385                                          struct hlist_head *tmp_del_list,
1386                                          int vlan_filters)
1387 {
1388         s16 pvid = le16_to_cpu(vsi->info.pvid);
1389         struct i40e_mac_filter *f, *add_head;
1390         struct i40e_new_mac_filter *new;
1391         struct hlist_node *h;
1392         int bkt, new_vlan;
1393
1394         /* To determine if a particular filter needs to be replaced we
1395          * have the three following conditions:
1396          *
1397          * a) if we have a PVID assigned, then all filters which are
1398          *    not marked as VLAN=PVID must be replaced with filters that
1399          *    are.
1400          * b) otherwise, if we have any active VLANS, all filters
1401          *    which are marked as VLAN=-1 must be replaced with
1402          *    filters marked as VLAN=0
1403          * c) finally, if we do not have any active VLANS, all filters
1404          *    which are marked as VLAN=0 must be replaced with filters
1405          *    marked as VLAN=-1
1406          */
1407
1408         /* Update the filters about to be added in place */
1409         hlist_for_each_entry(new, tmp_add_list, hlist) {
1410                 if (pvid && new->f->vlan != pvid)
1411                         new->f->vlan = pvid;
1412                 else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1413                         new->f->vlan = 0;
1414                 else if (!vlan_filters && new->f->vlan == 0)
1415                         new->f->vlan = I40E_VLAN_ANY;
1416         }
1417
1418         /* Update the remaining active filters */
1419         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1420                 /* Combine the checks for whether a filter needs to be changed
1421                  * and then determine the new VLAN inside the if block, in
1422                  * order to avoid duplicating code for adding the new filter
1423                  * then deleting the old filter.
1424                  */
1425                 if ((pvid && f->vlan != pvid) ||
1426                     (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1427                     (!vlan_filters && f->vlan == 0)) {
1428                         /* Determine the new vlan we will be adding */
1429                         if (pvid)
1430                                 new_vlan = pvid;
1431                         else if (vlan_filters)
1432                                 new_vlan = 0;
1433                         else
1434                                 new_vlan = I40E_VLAN_ANY;
1435
1436                         /* Create the new filter */
1437                         add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1438                         if (!add_head)
1439                                 return -ENOMEM;
1440
1441                         /* Create a temporary i40e_new_mac_filter */
1442                         new = kzalloc(sizeof(*new), GFP_ATOMIC);
1443                         if (!new)
1444                                 return -ENOMEM;
1445
1446                         new->f = add_head;
1447                         new->state = add_head->state;
1448
1449                         /* Add the new filter to the tmp list */
1450                         hlist_add_head(&new->hlist, tmp_add_list);
1451
1452                         /* Put the original filter into the delete list */
1453                         f->state = I40E_FILTER_REMOVE;
1454                         hash_del(&f->hlist);
1455                         hlist_add_head(&f->hlist, tmp_del_list);
1456                 }
1457         }
1458
1459         vsi->has_vlan_filter = !!vlan_filters;
1460
1461         return 0;
1462 }
1463
1464 /**
1465  * i40e_get_vf_new_vlan - Get new vlan id on a vf
1466  * @vsi: the vsi to configure
1467  * @new_mac: new mac filter to be added
1468  * @f: existing mac filter, replaced with new_mac->f if new_mac is not NULL
1469  * @vlan_filters: the number of active VLAN filters
1470  * @trusted: flag if the VF is trusted
1471  *
1472  * Get new VLAN id based on current VLAN filters, trust, PVID
1473  * and vf-vlan-prune-disable flag.
1474  *
1475  * Returns the value of the new vlan filter or
1476  * the old value if no new filter is needed.
1477  */
1478 static s16 i40e_get_vf_new_vlan(struct i40e_vsi *vsi,
1479                                 struct i40e_new_mac_filter *new_mac,
1480                                 struct i40e_mac_filter *f,
1481                                 int vlan_filters,
1482                                 bool trusted)
1483 {
1484         s16 pvid = le16_to_cpu(vsi->info.pvid);
1485         struct i40e_pf *pf = vsi->back;
1486         bool is_any;
1487
1488         if (new_mac)
1489                 f = new_mac->f;
1490
1491         if (pvid && f->vlan != pvid)
1492                 return pvid;
1493
1494         is_any = (trusted ||
1495                   !test_bit(I40E_FLAG_VF_VLAN_PRUNING_ENA, pf->flags));
1496
1497         if ((vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1498             (!is_any && !vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1499             (is_any && !vlan_filters && f->vlan == 0)) {
1500                 if (is_any)
1501                         return I40E_VLAN_ANY;
1502                 else
1503                         return 0;
1504         }
1505
1506         return f->vlan;
1507 }
1508
1509 /**
1510  * i40e_correct_vf_mac_vlan_filters - Correct non-VLAN VF filters if necessary
1511  * @vsi: the vsi to configure
1512  * @tmp_add_list: list of filters ready to be added
1513  * @tmp_del_list: list of filters ready to be deleted
1514  * @vlan_filters: the number of active VLAN filters
1515  * @trusted: flag if the VF is trusted
1516  *
1517  * Correct VF VLAN filters based on current VLAN filters, trust, PVID
1518  * and vf-vlan-prune-disable flag.
1519  *
1520  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1521  *
1522  * This function is only expected to be called from within
1523  * i40e_sync_vsi_filters.
1524  *
1525  * NOTE: This function expects to be called while under the
1526  * mac_filter_hash_lock
1527  */
1528 static int i40e_correct_vf_mac_vlan_filters(struct i40e_vsi *vsi,
1529                                             struct hlist_head *tmp_add_list,
1530                                             struct hlist_head *tmp_del_list,
1531                                             int vlan_filters,
1532                                             bool trusted)
1533 {
1534         struct i40e_mac_filter *f, *add_head;
1535         struct i40e_new_mac_filter *new_mac;
1536         struct hlist_node *h;
1537         int bkt, new_vlan;
1538
1539         hlist_for_each_entry(new_mac, tmp_add_list, hlist) {
1540                 new_mac->f->vlan = i40e_get_vf_new_vlan(vsi, new_mac, NULL,
1541                                                         vlan_filters, trusted);
1542         }
1543
1544         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1545                 new_vlan = i40e_get_vf_new_vlan(vsi, NULL, f, vlan_filters,
1546                                                 trusted);
1547                 if (new_vlan != f->vlan) {
1548                         add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1549                         if (!add_head)
1550                                 return -ENOMEM;
1551                         /* Create a temporary i40e_new_mac_filter */
1552                         new_mac = kzalloc(sizeof(*new_mac), GFP_ATOMIC);
1553                         if (!new_mac)
1554                                 return -ENOMEM;
1555                         new_mac->f = add_head;
1556                         new_mac->state = add_head->state;
1557
1558                         /* Add the new filter to the tmp list */
1559                         hlist_add_head(&new_mac->hlist, tmp_add_list);
1560
1561                         /* Put the original filter into the delete list */
1562                         f->state = I40E_FILTER_REMOVE;
1563                         hash_del(&f->hlist);
1564                         hlist_add_head(&f->hlist, tmp_del_list);
1565                 }
1566         }
1567
1568         vsi->has_vlan_filter = !!vlan_filters;
1569         return 0;
1570 }
1571
1572 /**
1573  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1574  * @vsi: the PF Main VSI - inappropriate for any other VSI
1575  * @macaddr: the MAC address
1576  *
1577  * Remove whatever filter the firmware set up so the driver can manage
1578  * its own filtering intelligently.
1579  **/
1580 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1581 {
1582         struct i40e_aqc_remove_macvlan_element_data element;
1583         struct i40e_pf *pf = vsi->back;
1584
1585         /* Only appropriate for the PF main VSI */
1586         if (vsi->type != I40E_VSI_MAIN)
1587                 return;
1588
1589         memset(&element, 0, sizeof(element));
1590         ether_addr_copy(element.mac_addr, macaddr);
1591         element.vlan_tag = 0;
1592         /* Ignore error returns, some firmware does it this way... */
1593         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1594         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1595
1596         memset(&element, 0, sizeof(element));
1597         ether_addr_copy(element.mac_addr, macaddr);
1598         element.vlan_tag = 0;
1599         /* ...and some firmware does it this way. */
1600         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1601                         I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1602         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1603 }
1604
1605 /**
1606  * i40e_add_filter - Add a mac/vlan filter to the VSI
1607  * @vsi: the VSI to be searched
1608  * @macaddr: the MAC address
1609  * @vlan: the vlan
1610  *
1611  * Returns ptr to the filter object or NULL when no memory available.
1612  *
1613  * NOTE: This function is expected to be called with mac_filter_hash_lock
1614  * being held.
1615  **/
1616 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1617                                         const u8 *macaddr, s16 vlan)
1618 {
1619         struct i40e_mac_filter *f;
1620         u64 key;
1621
1622         if (!vsi || !macaddr)
1623                 return NULL;
1624
1625         f = i40e_find_filter(vsi, macaddr, vlan);
1626         if (!f) {
1627                 f = kzalloc(sizeof(*f), GFP_ATOMIC);
1628                 if (!f)
1629                         return NULL;
1630
1631                 /* Update the boolean indicating if we need to function in
1632                  * VLAN mode.
1633                  */
1634                 if (vlan >= 0)
1635                         vsi->has_vlan_filter = true;
1636
1637                 ether_addr_copy(f->macaddr, macaddr);
1638                 f->vlan = vlan;
1639                 f->state = I40E_FILTER_NEW;
1640                 INIT_HLIST_NODE(&f->hlist);
1641
1642                 key = i40e_addr_to_hkey(macaddr);
1643                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
1644
1645                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1646                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1647         }
1648
1649         /* If we're asked to add a filter that has been marked for removal, it
1650          * is safe to simply restore it to active state. __i40e_del_filter
1651          * will have simply deleted any filters which were previously marked
1652          * NEW or FAILED, so if it is currently marked REMOVE it must have
1653          * previously been ACTIVE. Since we haven't yet run the sync filters
1654          * task, just restore this filter to the ACTIVE state so that the
1655          * sync task leaves it in place
1656          */
1657         if (f->state == I40E_FILTER_REMOVE)
1658                 f->state = I40E_FILTER_ACTIVE;
1659
1660         return f;
1661 }
1662
1663 /**
1664  * __i40e_del_filter - Remove a specific filter from the VSI
1665  * @vsi: VSI to remove from
1666  * @f: the filter to remove from the list
1667  *
1668  * This function should be called instead of i40e_del_filter only if you know
1669  * the exact filter you will remove already, such as via i40e_find_filter or
1670  * i40e_find_mac.
1671  *
1672  * NOTE: This function is expected to be called with mac_filter_hash_lock
1673  * being held.
1674  * ANOTHER NOTE: This function MUST be called from within the context of
1675  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1676  * instead of list_for_each_entry().
1677  **/
1678 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1679 {
1680         if (!f)
1681                 return;
1682
1683         /* If the filter was never added to firmware then we can just delete it
1684          * directly and we don't want to set the status to remove or else an
1685          * admin queue command will unnecessarily fire.
1686          */
1687         if ((f->state == I40E_FILTER_FAILED) ||
1688             (f->state == I40E_FILTER_NEW)) {
1689                 hash_del(&f->hlist);
1690                 kfree(f);
1691         } else {
1692                 f->state = I40E_FILTER_REMOVE;
1693         }
1694
1695         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1696         set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1697 }
1698
1699 /**
1700  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1701  * @vsi: the VSI to be searched
1702  * @macaddr: the MAC address
1703  * @vlan: the VLAN
1704  *
1705  * NOTE: This function is expected to be called with mac_filter_hash_lock
1706  * being held.
1707  * ANOTHER NOTE: This function MUST be called from within the context of
1708  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1709  * instead of list_for_each_entry().
1710  **/
1711 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1712 {
1713         struct i40e_mac_filter *f;
1714
1715         if (!vsi || !macaddr)
1716                 return;
1717
1718         f = i40e_find_filter(vsi, macaddr, vlan);
1719         __i40e_del_filter(vsi, f);
1720 }
1721
1722 /**
1723  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1724  * @vsi: the VSI to be searched
1725  * @macaddr: the mac address to be filtered
1726  *
1727  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1728  * go through all the macvlan filters and add a macvlan filter for each
1729  * unique vlan that already exists. If a PVID has been assigned, instead only
1730  * add the macaddr to that VLAN.
1731  *
1732  * Returns last filter added on success, else NULL
1733  **/
1734 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1735                                             const u8 *macaddr)
1736 {
1737         struct i40e_mac_filter *f, *add = NULL;
1738         struct hlist_node *h;
1739         int bkt;
1740
1741         if (vsi->info.pvid)
1742                 return i40e_add_filter(vsi, macaddr,
1743                                        le16_to_cpu(vsi->info.pvid));
1744
1745         if (!i40e_is_vsi_in_vlan(vsi))
1746                 return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1747
1748         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1749                 if (f->state == I40E_FILTER_REMOVE)
1750                         continue;
1751                 add = i40e_add_filter(vsi, macaddr, f->vlan);
1752                 if (!add)
1753                         return NULL;
1754         }
1755
1756         return add;
1757 }
1758
1759 /**
1760  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1761  * @vsi: the VSI to be searched
1762  * @macaddr: the mac address to be removed
1763  *
1764  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1765  * associated with.
1766  *
1767  * Returns 0 for success, or error
1768  **/
1769 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1770 {
1771         struct i40e_mac_filter *f;
1772         struct hlist_node *h;
1773         bool found = false;
1774         int bkt;
1775
1776         lockdep_assert_held(&vsi->mac_filter_hash_lock);
1777         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1778                 if (ether_addr_equal(macaddr, f->macaddr)) {
1779                         __i40e_del_filter(vsi, f);
1780                         found = true;
1781                 }
1782         }
1783
1784         if (found)
1785                 return 0;
1786         else
1787                 return -ENOENT;
1788 }
1789
1790 /**
1791  * i40e_set_mac - NDO callback to set mac address
1792  * @netdev: network interface device structure
1793  * @p: pointer to an address structure
1794  *
1795  * Returns 0 on success, negative on failure
1796  **/
1797 static int i40e_set_mac(struct net_device *netdev, void *p)
1798 {
1799         struct i40e_netdev_priv *np = netdev_priv(netdev);
1800         struct i40e_vsi *vsi = np->vsi;
1801         struct i40e_pf *pf = vsi->back;
1802         struct i40e_hw *hw = &pf->hw;
1803         struct sockaddr *addr = p;
1804
1805         if (!is_valid_ether_addr(addr->sa_data))
1806                 return -EADDRNOTAVAIL;
1807
1808         if (test_bit(__I40E_DOWN, pf->state) ||
1809             test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1810                 return -EADDRNOTAVAIL;
1811
1812         if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1813                 netdev_info(netdev, "returning to hw mac address %pM\n",
1814                             hw->mac.addr);
1815         else
1816                 netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1817
1818         /* Copy the address first, so that we avoid a possible race with
1819          * .set_rx_mode().
1820          * - Remove old address from MAC filter
1821          * - Copy new address
1822          * - Add new address to MAC filter
1823          */
1824         spin_lock_bh(&vsi->mac_filter_hash_lock);
1825         i40e_del_mac_filter(vsi, netdev->dev_addr);
1826         eth_hw_addr_set(netdev, addr->sa_data);
1827         i40e_add_mac_filter(vsi, netdev->dev_addr);
1828         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1829
1830         if (vsi->type == I40E_VSI_MAIN) {
1831                 int ret;
1832
1833                 ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1834                                                 addr->sa_data, NULL);
1835                 if (ret)
1836                         netdev_info(netdev, "Ignoring error from firmware on LAA update, status %pe, AQ ret %s\n",
1837                                     ERR_PTR(ret),
1838                                     i40e_aq_str(hw, hw->aq.asq_last_status));
1839         }
1840
1841         /* schedule our worker thread which will take care of
1842          * applying the new filter changes
1843          */
1844         i40e_service_event_schedule(pf);
1845         return 0;
1846 }
1847
1848 /**
1849  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1850  * @vsi: vsi structure
1851  * @seed: RSS hash seed
1852  * @lut: pointer to lookup table of lut_size
1853  * @lut_size: size of the lookup table
1854  **/
1855 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1856                               u8 *lut, u16 lut_size)
1857 {
1858         struct i40e_pf *pf = vsi->back;
1859         struct i40e_hw *hw = &pf->hw;
1860         int ret = 0;
1861
1862         if (seed) {
1863                 struct i40e_aqc_get_set_rss_key_data *seed_dw =
1864                         (struct i40e_aqc_get_set_rss_key_data *)seed;
1865                 ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1866                 if (ret) {
1867                         dev_info(&pf->pdev->dev,
1868                                  "Cannot set RSS key, err %pe aq_err %s\n",
1869                                  ERR_PTR(ret),
1870                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1871                         return ret;
1872                 }
1873         }
1874         if (lut) {
1875                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
1876
1877                 ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1878                 if (ret) {
1879                         dev_info(&pf->pdev->dev,
1880                                  "Cannot set RSS lut, err %pe aq_err %s\n",
1881                                  ERR_PTR(ret),
1882                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1883                         return ret;
1884                 }
1885         }
1886         return ret;
1887 }
1888
1889 /**
1890  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1891  * @vsi: VSI structure
1892  **/
1893 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1894 {
1895         struct i40e_pf *pf = vsi->back;
1896         u8 seed[I40E_HKEY_ARRAY_SIZE];
1897         u8 *lut;
1898         int ret;
1899
1900         if (!test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
1901                 return 0;
1902         if (!vsi->rss_size)
1903                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
1904                                       vsi->num_queue_pairs);
1905         if (!vsi->rss_size)
1906                 return -EINVAL;
1907         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1908         if (!lut)
1909                 return -ENOMEM;
1910
1911         /* Use the user configured hash keys and lookup table if there is one,
1912          * otherwise use default
1913          */
1914         if (vsi->rss_lut_user)
1915                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1916         else
1917                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1918         if (vsi->rss_hkey_user)
1919                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1920         else
1921                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1922         ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1923         kfree(lut);
1924         return ret;
1925 }
1926
1927 /**
1928  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1929  * @vsi: the VSI being configured,
1930  * @ctxt: VSI context structure
1931  * @enabled_tc: number of traffic classes to enable
1932  *
1933  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1934  **/
1935 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1936                                            struct i40e_vsi_context *ctxt,
1937                                            u8 enabled_tc)
1938 {
1939         u16 qcount = 0, max_qcount, qmap, sections = 0;
1940         int i, override_q, pow, num_qps, ret;
1941         u8 netdev_tc = 0, offset = 0;
1942
1943         if (vsi->type != I40E_VSI_MAIN)
1944                 return -EINVAL;
1945         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1946         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1947         vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1948         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1949         num_qps = vsi->mqprio_qopt.qopt.count[0];
1950
1951         /* find the next higher power-of-2 of num queue pairs */
1952         pow = ilog2(num_qps);
1953         if (!is_power_of_2(num_qps))
1954                 pow++;
1955         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1956                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1957
1958         /* Setup queue offset/count for all TCs for given VSI */
1959         max_qcount = vsi->mqprio_qopt.qopt.count[0];
1960         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1961                 /* See if the given TC is enabled for the given VSI */
1962                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1963                         offset = vsi->mqprio_qopt.qopt.offset[i];
1964                         qcount = vsi->mqprio_qopt.qopt.count[i];
1965                         if (qcount > max_qcount)
1966                                 max_qcount = qcount;
1967                         vsi->tc_config.tc_info[i].qoffset = offset;
1968                         vsi->tc_config.tc_info[i].qcount = qcount;
1969                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1970                 } else {
1971                         /* TC is not enabled so set the offset to
1972                          * default queue and allocate one queue
1973                          * for the given TC.
1974                          */
1975                         vsi->tc_config.tc_info[i].qoffset = 0;
1976                         vsi->tc_config.tc_info[i].qcount = 1;
1977                         vsi->tc_config.tc_info[i].netdev_tc = 0;
1978                 }
1979         }
1980
1981         /* Set actual Tx/Rx queue pairs */
1982         vsi->num_queue_pairs = offset + qcount;
1983
1984         /* Setup queue TC[0].qmap for given VSI context */
1985         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1986         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1987         ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1988         ctxt->info.valid_sections |= cpu_to_le16(sections);
1989
1990         /* Reconfigure RSS for main VSI with max queue count */
1991         vsi->rss_size = max_qcount;
1992         ret = i40e_vsi_config_rss(vsi);
1993         if (ret) {
1994                 dev_info(&vsi->back->pdev->dev,
1995                          "Failed to reconfig rss for num_queues (%u)\n",
1996                          max_qcount);
1997                 return ret;
1998         }
1999         vsi->reconfig_rss = true;
2000         dev_dbg(&vsi->back->pdev->dev,
2001                 "Reconfigured rss with num_queues (%u)\n", max_qcount);
2002
2003         /* Find queue count available for channel VSIs and starting offset
2004          * for channel VSIs
2005          */
2006         override_q = vsi->mqprio_qopt.qopt.count[0];
2007         if (override_q && override_q < vsi->num_queue_pairs) {
2008                 vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
2009                 vsi->next_base_queue = override_q;
2010         }
2011         return 0;
2012 }
2013
2014 /**
2015  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
2016  * @vsi: the VSI being setup
2017  * @ctxt: VSI context structure
2018  * @enabled_tc: Enabled TCs bitmap
2019  * @is_add: True if called before Add VSI
2020  *
2021  * Setup VSI queue mapping for enabled traffic classes.
2022  **/
2023 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
2024                                      struct i40e_vsi_context *ctxt,
2025                                      u8 enabled_tc,
2026                                      bool is_add)
2027 {
2028         struct i40e_pf *pf = vsi->back;
2029         u16 num_tc_qps = 0;
2030         u16 sections = 0;
2031         u8 netdev_tc = 0;
2032         u16 numtc = 1;
2033         u16 qcount;
2034         u8 offset;
2035         u16 qmap;
2036         int i;
2037
2038         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
2039         offset = 0;
2040         /* zero out queue mapping, it will get updated on the end of the function */
2041         memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
2042
2043         if (vsi->type == I40E_VSI_MAIN) {
2044                 /* This code helps add more queue to the VSI if we have
2045                  * more cores than RSS can support, the higher cores will
2046                  * be served by ATR or other filters. Furthermore, the
2047                  * non-zero req_queue_pairs says that user requested a new
2048                  * queue count via ethtool's set_channels, so use this
2049                  * value for queues distribution across traffic classes
2050                  * We need at least one queue pair for the interface
2051                  * to be usable as we see in else statement.
2052                  */
2053                 if (vsi->req_queue_pairs > 0)
2054                         vsi->num_queue_pairs = vsi->req_queue_pairs;
2055                 else if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2056                         vsi->num_queue_pairs = pf->num_lan_msix;
2057                 else
2058                         vsi->num_queue_pairs = 1;
2059         }
2060
2061         /* Number of queues per enabled TC */
2062         if (vsi->type == I40E_VSI_MAIN ||
2063             (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
2064                 num_tc_qps = vsi->num_queue_pairs;
2065         else
2066                 num_tc_qps = vsi->alloc_queue_pairs;
2067
2068         if (enabled_tc && test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
2069                 /* Find numtc from enabled TC bitmap */
2070                 for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2071                         if (enabled_tc & BIT(i)) /* TC is enabled */
2072                                 numtc++;
2073                 }
2074                 if (!numtc) {
2075                         dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
2076                         numtc = 1;
2077                 }
2078                 num_tc_qps = num_tc_qps / numtc;
2079                 num_tc_qps = min_t(int, num_tc_qps,
2080                                    i40e_pf_get_max_q_per_tc(pf));
2081         }
2082
2083         vsi->tc_config.numtc = numtc;
2084         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
2085
2086         /* Do not allow use more TC queue pairs than MSI-X vectors exist */
2087         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
2088                 num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
2089
2090         /* Setup queue offset/count for all TCs for given VSI */
2091         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
2092                 /* See if the given TC is enabled for the given VSI */
2093                 if (vsi->tc_config.enabled_tc & BIT(i)) {
2094                         /* TC is enabled */
2095                         int pow, num_qps;
2096
2097                         switch (vsi->type) {
2098                         case I40E_VSI_MAIN:
2099                                 if ((!test_bit(I40E_FLAG_FD_SB_ENA,
2100                                                pf->flags) &&
2101                                      !test_bit(I40E_FLAG_FD_ATR_ENA,
2102                                                pf->flags)) ||
2103                                     vsi->tc_config.enabled_tc != 1) {
2104                                         qcount = min_t(int, pf->alloc_rss_size,
2105                                                        num_tc_qps);
2106                                         break;
2107                                 }
2108                                 fallthrough;
2109                         case I40E_VSI_FDIR:
2110                         case I40E_VSI_SRIOV:
2111                         case I40E_VSI_VMDQ2:
2112                         default:
2113                                 qcount = num_tc_qps;
2114                                 WARN_ON(i != 0);
2115                                 break;
2116                         }
2117                         vsi->tc_config.tc_info[i].qoffset = offset;
2118                         vsi->tc_config.tc_info[i].qcount = qcount;
2119
2120                         /* find the next higher power-of-2 of num queue pairs */
2121                         num_qps = qcount;
2122                         pow = 0;
2123                         while (num_qps && (BIT_ULL(pow) < qcount)) {
2124                                 pow++;
2125                                 num_qps >>= 1;
2126                         }
2127
2128                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2129                         qmap =
2130                             (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2131                             (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2132
2133                         offset += qcount;
2134                 } else {
2135                         /* TC is not enabled so set the offset to
2136                          * default queue and allocate one queue
2137                          * for the given TC.
2138                          */
2139                         vsi->tc_config.tc_info[i].qoffset = 0;
2140                         vsi->tc_config.tc_info[i].qcount = 1;
2141                         vsi->tc_config.tc_info[i].netdev_tc = 0;
2142
2143                         qmap = 0;
2144                 }
2145                 ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2146         }
2147         /* Do not change previously set num_queue_pairs for PFs and VFs*/
2148         if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2149             (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2150             (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2151                 vsi->num_queue_pairs = offset;
2152
2153         /* Scheduler section valid can only be set for ADD VSI */
2154         if (is_add) {
2155                 sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2156
2157                 ctxt->info.up_enable_bits = enabled_tc;
2158         }
2159         if (vsi->type == I40E_VSI_SRIOV) {
2160                 ctxt->info.mapping_flags |=
2161                                      cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2162                 for (i = 0; i < vsi->num_queue_pairs; i++)
2163                         ctxt->info.queue_mapping[i] =
2164                                                cpu_to_le16(vsi->base_queue + i);
2165         } else {
2166                 ctxt->info.mapping_flags |=
2167                                         cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2168                 ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2169         }
2170         ctxt->info.valid_sections |= cpu_to_le16(sections);
2171 }
2172
2173 /**
2174  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2175  * @netdev: the netdevice
2176  * @addr: address to add
2177  *
2178  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2179  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2180  */
2181 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2182 {
2183         struct i40e_netdev_priv *np = netdev_priv(netdev);
2184         struct i40e_vsi *vsi = np->vsi;
2185
2186         if (i40e_add_mac_filter(vsi, addr))
2187                 return 0;
2188         else
2189                 return -ENOMEM;
2190 }
2191
2192 /**
2193  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2194  * @netdev: the netdevice
2195  * @addr: address to add
2196  *
2197  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2198  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2199  */
2200 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2201 {
2202         struct i40e_netdev_priv *np = netdev_priv(netdev);
2203         struct i40e_vsi *vsi = np->vsi;
2204
2205         /* Under some circumstances, we might receive a request to delete
2206          * our own device address from our uc list. Because we store the
2207          * device address in the VSI's MAC/VLAN filter list, we need to ignore
2208          * such requests and not delete our device address from this list.
2209          */
2210         if (ether_addr_equal(addr, netdev->dev_addr))
2211                 return 0;
2212
2213         i40e_del_mac_filter(vsi, addr);
2214
2215         return 0;
2216 }
2217
2218 /**
2219  * i40e_set_rx_mode - NDO callback to set the netdev filters
2220  * @netdev: network interface device structure
2221  **/
2222 static void i40e_set_rx_mode(struct net_device *netdev)
2223 {
2224         struct i40e_netdev_priv *np = netdev_priv(netdev);
2225         struct i40e_vsi *vsi = np->vsi;
2226
2227         spin_lock_bh(&vsi->mac_filter_hash_lock);
2228
2229         __dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2230         __dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2231
2232         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2233
2234         /* check for other flag changes */
2235         if (vsi->current_netdev_flags != vsi->netdev->flags) {
2236                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2237                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2238         }
2239 }
2240
2241 /**
2242  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2243  * @vsi: Pointer to VSI struct
2244  * @from: Pointer to list which contains MAC filter entries - changes to
2245  *        those entries needs to be undone.
2246  *
2247  * MAC filter entries from this list were slated for deletion.
2248  **/
2249 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2250                                          struct hlist_head *from)
2251 {
2252         struct i40e_mac_filter *f;
2253         struct hlist_node *h;
2254
2255         hlist_for_each_entry_safe(f, h, from, hlist) {
2256                 u64 key = i40e_addr_to_hkey(f->macaddr);
2257
2258                 /* Move the element back into MAC filter list*/
2259                 hlist_del(&f->hlist);
2260                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
2261         }
2262 }
2263
2264 /**
2265  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2266  * @vsi: Pointer to vsi struct
2267  * @from: Pointer to list which contains MAC filter entries - changes to
2268  *        those entries needs to be undone.
2269  *
2270  * MAC filter entries from this list were slated for addition.
2271  **/
2272 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2273                                          struct hlist_head *from)
2274 {
2275         struct i40e_new_mac_filter *new;
2276         struct hlist_node *h;
2277
2278         hlist_for_each_entry_safe(new, h, from, hlist) {
2279                 /* We can simply free the wrapper structure */
2280                 hlist_del(&new->hlist);
2281                 netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2282                 kfree(new);
2283         }
2284 }
2285
2286 /**
2287  * i40e_next_filter - Get the next non-broadcast filter from a list
2288  * @next: pointer to filter in list
2289  *
2290  * Returns the next non-broadcast filter in the list. Required so that we
2291  * ignore broadcast filters within the list, since these are not handled via
2292  * the normal firmware update path.
2293  */
2294 static
2295 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2296 {
2297         hlist_for_each_entry_continue(next, hlist) {
2298                 if (!is_broadcast_ether_addr(next->f->macaddr))
2299                         return next;
2300         }
2301
2302         return NULL;
2303 }
2304
2305 /**
2306  * i40e_update_filter_state - Update filter state based on return data
2307  * from firmware
2308  * @count: Number of filters added
2309  * @add_list: return data from fw
2310  * @add_head: pointer to first filter in current batch
2311  *
2312  * MAC filter entries from list were slated to be added to device. Returns
2313  * number of successful filters. Note that 0 does NOT mean success!
2314  **/
2315 static int
2316 i40e_update_filter_state(int count,
2317                          struct i40e_aqc_add_macvlan_element_data *add_list,
2318                          struct i40e_new_mac_filter *add_head)
2319 {
2320         int retval = 0;
2321         int i;
2322
2323         for (i = 0; i < count; i++) {
2324                 /* Always check status of each filter. We don't need to check
2325                  * the firmware return status because we pre-set the filter
2326                  * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2327                  * request to the adminq. Thus, if it no longer matches then
2328                  * we know the filter is active.
2329                  */
2330                 if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2331                         add_head->state = I40E_FILTER_FAILED;
2332                 } else {
2333                         add_head->state = I40E_FILTER_ACTIVE;
2334                         retval++;
2335                 }
2336
2337                 add_head = i40e_next_filter(add_head);
2338                 if (!add_head)
2339                         break;
2340         }
2341
2342         return retval;
2343 }
2344
2345 /**
2346  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2347  * @vsi: ptr to the VSI
2348  * @vsi_name: name to display in messages
2349  * @list: the list of filters to send to firmware
2350  * @num_del: the number of filters to delete
2351  * @retval: Set to -EIO on failure to delete
2352  *
2353  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2354  * *retval instead of a return value so that success does not force ret_val to
2355  * be set to 0. This ensures that a sequence of calls to this function
2356  * preserve the previous value of *retval on successful delete.
2357  */
2358 static
2359 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2360                           struct i40e_aqc_remove_macvlan_element_data *list,
2361                           int num_del, int *retval)
2362 {
2363         struct i40e_hw *hw = &vsi->back->hw;
2364         enum i40e_admin_queue_err aq_status;
2365         int aq_ret;
2366
2367         aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2368                                            &aq_status);
2369
2370         /* Explicitly ignore and do not report when firmware returns ENOENT */
2371         if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2372                 *retval = -EIO;
2373                 dev_info(&vsi->back->pdev->dev,
2374                          "ignoring delete macvlan error on %s, err %pe, aq_err %s\n",
2375                          vsi_name, ERR_PTR(aq_ret),
2376                          i40e_aq_str(hw, aq_status));
2377         }
2378 }
2379
2380 /**
2381  * i40e_aqc_add_filters - Request firmware to add a set of filters
2382  * @vsi: ptr to the VSI
2383  * @vsi_name: name to display in messages
2384  * @list: the list of filters to send to firmware
2385  * @add_head: Position in the add hlist
2386  * @num_add: the number of filters to add
2387  *
2388  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2389  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2390  * space for more filters.
2391  */
2392 static
2393 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2394                           struct i40e_aqc_add_macvlan_element_data *list,
2395                           struct i40e_new_mac_filter *add_head,
2396                           int num_add)
2397 {
2398         struct i40e_hw *hw = &vsi->back->hw;
2399         enum i40e_admin_queue_err aq_status;
2400         int fcnt;
2401
2402         i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2403         fcnt = i40e_update_filter_state(num_add, list, add_head);
2404
2405         if (fcnt != num_add) {
2406                 if (vsi->type == I40E_VSI_MAIN) {
2407                         set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2408                         dev_warn(&vsi->back->pdev->dev,
2409                                  "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2410                                  i40e_aq_str(hw, aq_status), vsi_name);
2411                 } else if (vsi->type == I40E_VSI_SRIOV ||
2412                            vsi->type == I40E_VSI_VMDQ1 ||
2413                            vsi->type == I40E_VSI_VMDQ2) {
2414                         dev_warn(&vsi->back->pdev->dev,
2415                                  "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2416                                  i40e_aq_str(hw, aq_status), vsi_name,
2417                                              vsi_name);
2418                 } else {
2419                         dev_warn(&vsi->back->pdev->dev,
2420                                  "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2421                                  i40e_aq_str(hw, aq_status), vsi_name,
2422                                              vsi->type);
2423                 }
2424         }
2425 }
2426
2427 /**
2428  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2429  * @vsi: pointer to the VSI
2430  * @vsi_name: the VSI name
2431  * @f: filter data
2432  *
2433  * This function sets or clears the promiscuous broadcast flags for VLAN
2434  * filters in order to properly receive broadcast frames. Assumes that only
2435  * broadcast filters are passed.
2436  *
2437  * Returns status indicating success or failure;
2438  **/
2439 static int
2440 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2441                           struct i40e_mac_filter *f)
2442 {
2443         bool enable = f->state == I40E_FILTER_NEW;
2444         struct i40e_hw *hw = &vsi->back->hw;
2445         int aq_ret;
2446
2447         if (f->vlan == I40E_VLAN_ANY) {
2448                 aq_ret = i40e_aq_set_vsi_broadcast(hw,
2449                                                    vsi->seid,
2450                                                    enable,
2451                                                    NULL);
2452         } else {
2453                 aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2454                                                             vsi->seid,
2455                                                             enable,
2456                                                             f->vlan,
2457                                                             NULL);
2458         }
2459
2460         if (aq_ret) {
2461                 set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2462                 dev_warn(&vsi->back->pdev->dev,
2463                          "Error %s, forcing overflow promiscuous on %s\n",
2464                          i40e_aq_str(hw, hw->aq.asq_last_status),
2465                          vsi_name);
2466         }
2467
2468         return aq_ret;
2469 }
2470
2471 /**
2472  * i40e_set_promiscuous - set promiscuous mode
2473  * @pf: board private structure
2474  * @promisc: promisc on or off
2475  *
2476  * There are different ways of setting promiscuous mode on a PF depending on
2477  * what state/environment we're in.  This identifies and sets it appropriately.
2478  * Returns 0 on success.
2479  **/
2480 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2481 {
2482         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2483         struct i40e_hw *hw = &pf->hw;
2484         int aq_ret;
2485
2486         if (vsi->type == I40E_VSI_MAIN &&
2487             pf->lan_veb != I40E_NO_VEB &&
2488             !test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
2489                 /* set defport ON for Main VSI instead of true promisc
2490                  * this way we will get all unicast/multicast and VLAN
2491                  * promisc behavior but will not get VF or VMDq traffic
2492                  * replicated on the Main VSI.
2493                  */
2494                 if (promisc)
2495                         aq_ret = i40e_aq_set_default_vsi(hw,
2496                                                          vsi->seid,
2497                                                          NULL);
2498                 else
2499                         aq_ret = i40e_aq_clear_default_vsi(hw,
2500                                                            vsi->seid,
2501                                                            NULL);
2502                 if (aq_ret) {
2503                         dev_info(&pf->pdev->dev,
2504                                  "Set default VSI failed, err %pe, aq_err %s\n",
2505                                  ERR_PTR(aq_ret),
2506                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2507                 }
2508         } else {
2509                 aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2510                                                   hw,
2511                                                   vsi->seid,
2512                                                   promisc, NULL,
2513                                                   true);
2514                 if (aq_ret) {
2515                         dev_info(&pf->pdev->dev,
2516                                  "set unicast promisc failed, err %pe, aq_err %s\n",
2517                                  ERR_PTR(aq_ret),
2518                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2519                 }
2520                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2521                                                   hw,
2522                                                   vsi->seid,
2523                                                   promisc, NULL);
2524                 if (aq_ret) {
2525                         dev_info(&pf->pdev->dev,
2526                                  "set multicast promisc failed, err %pe, aq_err %s\n",
2527                                  ERR_PTR(aq_ret),
2528                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2529                 }
2530         }
2531
2532         if (!aq_ret)
2533                 pf->cur_promisc = promisc;
2534
2535         return aq_ret;
2536 }
2537
2538 /**
2539  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2540  * @vsi: ptr to the VSI
2541  *
2542  * Push any outstanding VSI filter changes through the AdminQ.
2543  *
2544  * Returns 0 or error value
2545  **/
2546 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2547 {
2548         struct hlist_head tmp_add_list, tmp_del_list;
2549         struct i40e_mac_filter *f;
2550         struct i40e_new_mac_filter *new, *add_head = NULL;
2551         struct i40e_hw *hw = &vsi->back->hw;
2552         bool old_overflow, new_overflow;
2553         unsigned int failed_filters = 0;
2554         unsigned int vlan_filters = 0;
2555         char vsi_name[16] = "PF";
2556         int filter_list_len = 0;
2557         u32 changed_flags = 0;
2558         struct hlist_node *h;
2559         struct i40e_pf *pf;
2560         int num_add = 0;
2561         int num_del = 0;
2562         int aq_ret = 0;
2563         int retval = 0;
2564         u16 cmd_flags;
2565         int list_size;
2566         int bkt;
2567
2568         /* empty array typed pointers, kcalloc later */
2569         struct i40e_aqc_add_macvlan_element_data *add_list;
2570         struct i40e_aqc_remove_macvlan_element_data *del_list;
2571
2572         while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2573                 usleep_range(1000, 2000);
2574         pf = vsi->back;
2575
2576         old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2577
2578         if (vsi->netdev) {
2579                 changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2580                 vsi->current_netdev_flags = vsi->netdev->flags;
2581         }
2582
2583         INIT_HLIST_HEAD(&tmp_add_list);
2584         INIT_HLIST_HEAD(&tmp_del_list);
2585
2586         if (vsi->type == I40E_VSI_SRIOV)
2587                 snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2588         else if (vsi->type != I40E_VSI_MAIN)
2589                 snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2590
2591         if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2592                 vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2593
2594                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2595                 /* Create a list of filters to delete. */
2596                 hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2597                         if (f->state == I40E_FILTER_REMOVE) {
2598                                 /* Move the element into temporary del_list */
2599                                 hash_del(&f->hlist);
2600                                 hlist_add_head(&f->hlist, &tmp_del_list);
2601
2602                                 /* Avoid counting removed filters */
2603                                 continue;
2604                         }
2605                         if (f->state == I40E_FILTER_NEW) {
2606                                 /* Create a temporary i40e_new_mac_filter */
2607                                 new = kzalloc(sizeof(*new), GFP_ATOMIC);
2608                                 if (!new)
2609                                         goto err_no_memory_locked;
2610
2611                                 /* Store pointer to the real filter */
2612                                 new->f = f;
2613                                 new->state = f->state;
2614
2615                                 /* Add it to the hash list */
2616                                 hlist_add_head(&new->hlist, &tmp_add_list);
2617                         }
2618
2619                         /* Count the number of active (current and new) VLAN
2620                          * filters we have now. Does not count filters which
2621                          * are marked for deletion.
2622                          */
2623                         if (f->vlan > 0)
2624                                 vlan_filters++;
2625                 }
2626
2627                 if (vsi->type != I40E_VSI_SRIOV)
2628                         retval = i40e_correct_mac_vlan_filters
2629                                 (vsi, &tmp_add_list, &tmp_del_list,
2630                                  vlan_filters);
2631                 else if (pf->vf)
2632                         retval = i40e_correct_vf_mac_vlan_filters
2633                                 (vsi, &tmp_add_list, &tmp_del_list,
2634                                  vlan_filters, pf->vf[vsi->vf_id].trusted);
2635
2636                 hlist_for_each_entry(new, &tmp_add_list, hlist)
2637                         netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2638
2639                 if (retval)
2640                         goto err_no_memory_locked;
2641
2642                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2643         }
2644
2645         /* Now process 'del_list' outside the lock */
2646         if (!hlist_empty(&tmp_del_list)) {
2647                 filter_list_len = hw->aq.asq_buf_size /
2648                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2649                 list_size = filter_list_len *
2650                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2651                 del_list = kzalloc(list_size, GFP_ATOMIC);
2652                 if (!del_list)
2653                         goto err_no_memory;
2654
2655                 hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2656                         cmd_flags = 0;
2657
2658                         /* handle broadcast filters by updating the broadcast
2659                          * promiscuous flag and release filter list.
2660                          */
2661                         if (is_broadcast_ether_addr(f->macaddr)) {
2662                                 i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2663
2664                                 hlist_del(&f->hlist);
2665                                 kfree(f);
2666                                 continue;
2667                         }
2668
2669                         /* add to delete list */
2670                         ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2671                         if (f->vlan == I40E_VLAN_ANY) {
2672                                 del_list[num_del].vlan_tag = 0;
2673                                 cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2674                         } else {
2675                                 del_list[num_del].vlan_tag =
2676                                         cpu_to_le16((u16)(f->vlan));
2677                         }
2678
2679                         cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2680                         del_list[num_del].flags = cmd_flags;
2681                         num_del++;
2682
2683                         /* flush a full buffer */
2684                         if (num_del == filter_list_len) {
2685                                 i40e_aqc_del_filters(vsi, vsi_name, del_list,
2686                                                      num_del, &retval);
2687                                 memset(del_list, 0, list_size);
2688                                 num_del = 0;
2689                         }
2690                         /* Release memory for MAC filter entries which were
2691                          * synced up with HW.
2692                          */
2693                         hlist_del(&f->hlist);
2694                         kfree(f);
2695                 }
2696
2697                 if (num_del) {
2698                         i40e_aqc_del_filters(vsi, vsi_name, del_list,
2699                                              num_del, &retval);
2700                 }
2701
2702                 kfree(del_list);
2703                 del_list = NULL;
2704         }
2705
2706         if (!hlist_empty(&tmp_add_list)) {
2707                 /* Do all the adds now. */
2708                 filter_list_len = hw->aq.asq_buf_size /
2709                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2710                 list_size = filter_list_len *
2711                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2712                 add_list = kzalloc(list_size, GFP_ATOMIC);
2713                 if (!add_list)
2714                         goto err_no_memory;
2715
2716                 num_add = 0;
2717                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2718                         /* handle broadcast filters by updating the broadcast
2719                          * promiscuous flag instead of adding a MAC filter.
2720                          */
2721                         if (is_broadcast_ether_addr(new->f->macaddr)) {
2722                                 if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2723                                                               new->f))
2724                                         new->state = I40E_FILTER_FAILED;
2725                                 else
2726                                         new->state = I40E_FILTER_ACTIVE;
2727                                 continue;
2728                         }
2729
2730                         /* add to add array */
2731                         if (num_add == 0)
2732                                 add_head = new;
2733                         cmd_flags = 0;
2734                         ether_addr_copy(add_list[num_add].mac_addr,
2735                                         new->f->macaddr);
2736                         if (new->f->vlan == I40E_VLAN_ANY) {
2737                                 add_list[num_add].vlan_tag = 0;
2738                                 cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2739                         } else {
2740                                 add_list[num_add].vlan_tag =
2741                                         cpu_to_le16((u16)(new->f->vlan));
2742                         }
2743                         add_list[num_add].queue_number = 0;
2744                         /* set invalid match method for later detection */
2745                         add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2746                         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2747                         add_list[num_add].flags = cpu_to_le16(cmd_flags);
2748                         num_add++;
2749
2750                         /* flush a full buffer */
2751                         if (num_add == filter_list_len) {
2752                                 i40e_aqc_add_filters(vsi, vsi_name, add_list,
2753                                                      add_head, num_add);
2754                                 memset(add_list, 0, list_size);
2755                                 num_add = 0;
2756                         }
2757                 }
2758                 if (num_add) {
2759                         i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2760                                              num_add);
2761                 }
2762                 /* Now move all of the filters from the temp add list back to
2763                  * the VSI's list.
2764                  */
2765                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2766                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2767                         /* Only update the state if we're still NEW */
2768                         if (new->f->state == I40E_FILTER_NEW)
2769                                 new->f->state = new->state;
2770                         hlist_del(&new->hlist);
2771                         netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2772                         kfree(new);
2773                 }
2774                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2775                 kfree(add_list);
2776                 add_list = NULL;
2777         }
2778
2779         /* Determine the number of active and failed filters. */
2780         spin_lock_bh(&vsi->mac_filter_hash_lock);
2781         vsi->active_filters = 0;
2782         hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2783                 if (f->state == I40E_FILTER_ACTIVE)
2784                         vsi->active_filters++;
2785                 else if (f->state == I40E_FILTER_FAILED)
2786                         failed_filters++;
2787         }
2788         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2789
2790         /* Check if we are able to exit overflow promiscuous mode. We can
2791          * safely exit if we didn't just enter, we no longer have any failed
2792          * filters, and we have reduced filters below the threshold value.
2793          */
2794         if (old_overflow && !failed_filters &&
2795             vsi->active_filters < vsi->promisc_threshold) {
2796                 dev_info(&pf->pdev->dev,
2797                          "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2798                          vsi_name);
2799                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2800                 vsi->promisc_threshold = 0;
2801         }
2802
2803         /* if the VF is not trusted do not do promisc */
2804         if (vsi->type == I40E_VSI_SRIOV && pf->vf &&
2805             !pf->vf[vsi->vf_id].trusted) {
2806                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2807                 goto out;
2808         }
2809
2810         new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2811
2812         /* If we are entering overflow promiscuous, we need to calculate a new
2813          * threshold for when we are safe to exit
2814          */
2815         if (!old_overflow && new_overflow)
2816                 vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2817
2818         /* check for changes in promiscuous modes */
2819         if (changed_flags & IFF_ALLMULTI) {
2820                 bool cur_multipromisc;
2821
2822                 cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2823                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2824                                                                vsi->seid,
2825                                                                cur_multipromisc,
2826                                                                NULL);
2827                 if (aq_ret) {
2828                         retval = i40e_aq_rc_to_posix(aq_ret,
2829                                                      hw->aq.asq_last_status);
2830                         dev_info(&pf->pdev->dev,
2831                                  "set multi promisc failed on %s, err %pe aq_err %s\n",
2832                                  vsi_name,
2833                                  ERR_PTR(aq_ret),
2834                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2835                 } else {
2836                         dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2837                                  cur_multipromisc ? "entering" : "leaving");
2838                 }
2839         }
2840
2841         if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2842                 bool cur_promisc;
2843
2844                 cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2845                                new_overflow);
2846                 aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2847                 if (aq_ret) {
2848                         retval = i40e_aq_rc_to_posix(aq_ret,
2849                                                      hw->aq.asq_last_status);
2850                         dev_info(&pf->pdev->dev,
2851                                  "Setting promiscuous %s failed on %s, err %pe aq_err %s\n",
2852                                  cur_promisc ? "on" : "off",
2853                                  vsi_name,
2854                                  ERR_PTR(aq_ret),
2855                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2856                 }
2857         }
2858 out:
2859         /* if something went wrong then set the changed flag so we try again */
2860         if (retval)
2861                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2862
2863         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2864         return retval;
2865
2866 err_no_memory:
2867         /* Restore elements on the temporary add and delete lists */
2868         spin_lock_bh(&vsi->mac_filter_hash_lock);
2869 err_no_memory_locked:
2870         i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2871         i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2872         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2873
2874         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2875         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2876         return -ENOMEM;
2877 }
2878
2879 /**
2880  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2881  * @pf: board private structure
2882  **/
2883 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2884 {
2885         int v;
2886
2887         if (!pf)
2888                 return;
2889         if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2890                 return;
2891         if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2892                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2893                 return;
2894         }
2895
2896         for (v = 0; v < pf->num_alloc_vsi; v++) {
2897                 if (pf->vsi[v] &&
2898                     (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2899                     !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2900                         int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2901
2902                         if (ret) {
2903                                 /* come back and try again later */
2904                                 set_bit(__I40E_MACVLAN_SYNC_PENDING,
2905                                         pf->state);
2906                                 break;
2907                         }
2908                 }
2909         }
2910 }
2911
2912 /**
2913  * i40e_calculate_vsi_rx_buf_len - Calculates buffer length
2914  *
2915  * @vsi: VSI to calculate rx_buf_len from
2916  */
2917 static u16 i40e_calculate_vsi_rx_buf_len(struct i40e_vsi *vsi)
2918 {
2919         if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags))
2920                 return SKB_WITH_OVERHEAD(I40E_RXBUFFER_2048);
2921
2922         return PAGE_SIZE < 8192 ? I40E_RXBUFFER_3072 : I40E_RXBUFFER_2048;
2923 }
2924
2925 /**
2926  * i40e_max_vsi_frame_size - returns the maximum allowed frame size for VSI
2927  * @vsi: the vsi
2928  * @xdp_prog: XDP program
2929  **/
2930 static int i40e_max_vsi_frame_size(struct i40e_vsi *vsi,
2931                                    struct bpf_prog *xdp_prog)
2932 {
2933         u16 rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
2934         u16 chain_len;
2935
2936         if (xdp_prog && !xdp_prog->aux->xdp_has_frags)
2937                 chain_len = 1;
2938         else
2939                 chain_len = I40E_MAX_CHAINED_RX_BUFFERS;
2940
2941         return min_t(u16, rx_buf_len * chain_len, I40E_MAX_RXBUFFER);
2942 }
2943
2944 /**
2945  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2946  * @netdev: network interface device structure
2947  * @new_mtu: new value for maximum frame size
2948  *
2949  * Returns 0 on success, negative on failure
2950  **/
2951 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2952 {
2953         struct i40e_netdev_priv *np = netdev_priv(netdev);
2954         struct i40e_vsi *vsi = np->vsi;
2955         struct i40e_pf *pf = vsi->back;
2956         int frame_size;
2957
2958         frame_size = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
2959         if (new_mtu > frame_size - I40E_PACKET_HDR_PAD) {
2960                 netdev_err(netdev, "Error changing mtu to %d, Max is %d\n",
2961                            new_mtu, frame_size - I40E_PACKET_HDR_PAD);
2962                 return -EINVAL;
2963         }
2964
2965         netdev_dbg(netdev, "changing MTU from %d to %d\n",
2966                    netdev->mtu, new_mtu);
2967         netdev->mtu = new_mtu;
2968         if (netif_running(netdev))
2969                 i40e_vsi_reinit_locked(vsi);
2970         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2971         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2972         return 0;
2973 }
2974
2975 /**
2976  * i40e_ioctl - Access the hwtstamp interface
2977  * @netdev: network interface device structure
2978  * @ifr: interface request data
2979  * @cmd: ioctl command
2980  **/
2981 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2982 {
2983         struct i40e_netdev_priv *np = netdev_priv(netdev);
2984         struct i40e_pf *pf = np->vsi->back;
2985
2986         switch (cmd) {
2987         case SIOCGHWTSTAMP:
2988                 return i40e_ptp_get_ts_config(pf, ifr);
2989         case SIOCSHWTSTAMP:
2990                 return i40e_ptp_set_ts_config(pf, ifr);
2991         default:
2992                 return -EOPNOTSUPP;
2993         }
2994 }
2995
2996 /**
2997  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2998  * @vsi: the vsi being adjusted
2999  **/
3000 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
3001 {
3002         struct i40e_vsi_context ctxt;
3003         int ret;
3004
3005         /* Don't modify stripping options if a port VLAN is active */
3006         if (vsi->info.pvid)
3007                 return;
3008
3009         if ((vsi->info.valid_sections &
3010              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3011             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
3012                 return;  /* already enabled */
3013
3014         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3015         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3016                                     I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
3017
3018         ctxt.seid = vsi->seid;
3019         ctxt.info = vsi->info;
3020         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3021         if (ret) {
3022                 dev_info(&vsi->back->pdev->dev,
3023                          "update vlan stripping failed, err %pe aq_err %s\n",
3024                          ERR_PTR(ret),
3025                          i40e_aq_str(&vsi->back->hw,
3026                                      vsi->back->hw.aq.asq_last_status));
3027         }
3028 }
3029
3030 /**
3031  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
3032  * @vsi: the vsi being adjusted
3033  **/
3034 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
3035 {
3036         struct i40e_vsi_context ctxt;
3037         int ret;
3038
3039         /* Don't modify stripping options if a port VLAN is active */
3040         if (vsi->info.pvid)
3041                 return;
3042
3043         if ((vsi->info.valid_sections &
3044              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
3045             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
3046              I40E_AQ_VSI_PVLAN_EMOD_MASK))
3047                 return;  /* already disabled */
3048
3049         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3050         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
3051                                     I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
3052
3053         ctxt.seid = vsi->seid;
3054         ctxt.info = vsi->info;
3055         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3056         if (ret) {
3057                 dev_info(&vsi->back->pdev->dev,
3058                          "update vlan stripping failed, err %pe aq_err %s\n",
3059                          ERR_PTR(ret),
3060                          i40e_aq_str(&vsi->back->hw,
3061                                      vsi->back->hw.aq.asq_last_status));
3062         }
3063 }
3064
3065 /**
3066  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
3067  * @vsi: the vsi being configured
3068  * @vid: vlan id to be added (0 = untagged only , -1 = any)
3069  *
3070  * This is a helper function for adding a new MAC/VLAN filter with the
3071  * specified VLAN for each existing MAC address already in the hash table.
3072  * This function does *not* perform any accounting to update filters based on
3073  * VLAN mode.
3074  *
3075  * NOTE: this function expects to be called while under the
3076  * mac_filter_hash_lock
3077  **/
3078 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3079 {
3080         struct i40e_mac_filter *f, *add_f;
3081         struct hlist_node *h;
3082         int bkt;
3083
3084         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3085                 /* If we're asked to add a filter that has been marked for
3086                  * removal, it is safe to simply restore it to active state.
3087                  * __i40e_del_filter will have simply deleted any filters which
3088                  * were previously marked NEW or FAILED, so if it is currently
3089                  * marked REMOVE it must have previously been ACTIVE. Since we
3090                  * haven't yet run the sync filters task, just restore this
3091                  * filter to the ACTIVE state so that the sync task leaves it
3092                  * in place.
3093                  */
3094                 if (f->state == I40E_FILTER_REMOVE && f->vlan == vid) {
3095                         f->state = I40E_FILTER_ACTIVE;
3096                         continue;
3097                 } else if (f->state == I40E_FILTER_REMOVE) {
3098                         continue;
3099                 }
3100                 add_f = i40e_add_filter(vsi, f->macaddr, vid);
3101                 if (!add_f) {
3102                         dev_info(&vsi->back->pdev->dev,
3103                                  "Could not add vlan filter %d for %pM\n",
3104                                  vid, f->macaddr);
3105                         return -ENOMEM;
3106                 }
3107         }
3108
3109         return 0;
3110 }
3111
3112 /**
3113  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
3114  * @vsi: the VSI being configured
3115  * @vid: VLAN id to be added
3116  **/
3117 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
3118 {
3119         int err;
3120
3121         if (vsi->info.pvid)
3122                 return -EINVAL;
3123
3124         /* The network stack will attempt to add VID=0, with the intention to
3125          * receive priority tagged packets with a VLAN of 0. Our HW receives
3126          * these packets by default when configured to receive untagged
3127          * packets, so we don't need to add a filter for this case.
3128          * Additionally, HW interprets adding a VID=0 filter as meaning to
3129          * receive *only* tagged traffic and stops receiving untagged traffic.
3130          * Thus, we do not want to actually add a filter for VID=0
3131          */
3132         if (!vid)
3133                 return 0;
3134
3135         /* Locked once because all functions invoked below iterates list*/
3136         spin_lock_bh(&vsi->mac_filter_hash_lock);
3137         err = i40e_add_vlan_all_mac(vsi, vid);
3138         spin_unlock_bh(&vsi->mac_filter_hash_lock);
3139         if (err)
3140                 return err;
3141
3142         /* schedule our worker thread which will take care of
3143          * applying the new filter changes
3144          */
3145         i40e_service_event_schedule(vsi->back);
3146         return 0;
3147 }
3148
3149 /**
3150  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
3151  * @vsi: the vsi being configured
3152  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
3153  *
3154  * This function should be used to remove all VLAN filters which match the
3155  * given VID. It does not schedule the service event and does not take the
3156  * mac_filter_hash_lock so it may be combined with other operations under
3157  * a single invocation of the mac_filter_hash_lock.
3158  *
3159  * NOTE: this function expects to be called while under the
3160  * mac_filter_hash_lock
3161  */
3162 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3163 {
3164         struct i40e_mac_filter *f;
3165         struct hlist_node *h;
3166         int bkt;
3167
3168         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3169                 if (f->vlan == vid)
3170                         __i40e_del_filter(vsi, f);
3171         }
3172 }
3173
3174 /**
3175  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3176  * @vsi: the VSI being configured
3177  * @vid: VLAN id to be removed
3178  **/
3179 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3180 {
3181         if (!vid || vsi->info.pvid)
3182                 return;
3183
3184         spin_lock_bh(&vsi->mac_filter_hash_lock);
3185         i40e_rm_vlan_all_mac(vsi, vid);
3186         spin_unlock_bh(&vsi->mac_filter_hash_lock);
3187
3188         /* schedule our worker thread which will take care of
3189          * applying the new filter changes
3190          */
3191         i40e_service_event_schedule(vsi->back);
3192 }
3193
3194 /**
3195  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3196  * @netdev: network interface to be adjusted
3197  * @proto: unused protocol value
3198  * @vid: vlan id to be added
3199  *
3200  * net_device_ops implementation for adding vlan ids
3201  **/
3202 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3203                                 __always_unused __be16 proto, u16 vid)
3204 {
3205         struct i40e_netdev_priv *np = netdev_priv(netdev);
3206         struct i40e_vsi *vsi = np->vsi;
3207         int ret = 0;
3208
3209         if (vid >= VLAN_N_VID)
3210                 return -EINVAL;
3211
3212         ret = i40e_vsi_add_vlan(vsi, vid);
3213         if (!ret)
3214                 set_bit(vid, vsi->active_vlans);
3215
3216         return ret;
3217 }
3218
3219 /**
3220  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3221  * @netdev: network interface to be adjusted
3222  * @proto: unused protocol value
3223  * @vid: vlan id to be added
3224  **/
3225 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3226                                     __always_unused __be16 proto, u16 vid)
3227 {
3228         struct i40e_netdev_priv *np = netdev_priv(netdev);
3229         struct i40e_vsi *vsi = np->vsi;
3230
3231         if (vid >= VLAN_N_VID)
3232                 return;
3233         set_bit(vid, vsi->active_vlans);
3234 }
3235
3236 /**
3237  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3238  * @netdev: network interface to be adjusted
3239  * @proto: unused protocol value
3240  * @vid: vlan id to be removed
3241  *
3242  * net_device_ops implementation for removing vlan ids
3243  **/
3244 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3245                                  __always_unused __be16 proto, u16 vid)
3246 {
3247         struct i40e_netdev_priv *np = netdev_priv(netdev);
3248         struct i40e_vsi *vsi = np->vsi;
3249
3250         /* return code is ignored as there is nothing a user
3251          * can do about failure to remove and a log message was
3252          * already printed from the other function
3253          */
3254         i40e_vsi_kill_vlan(vsi, vid);
3255
3256         clear_bit(vid, vsi->active_vlans);
3257
3258         return 0;
3259 }
3260
3261 /**
3262  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3263  * @vsi: the vsi being brought back up
3264  **/
3265 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3266 {
3267         u16 vid;
3268
3269         if (!vsi->netdev)
3270                 return;
3271
3272         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3273                 i40e_vlan_stripping_enable(vsi);
3274         else
3275                 i40e_vlan_stripping_disable(vsi);
3276
3277         for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3278                 i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3279                                         vid);
3280 }
3281
3282 /**
3283  * i40e_vsi_add_pvid - Add pvid for the VSI
3284  * @vsi: the vsi being adjusted
3285  * @vid: the vlan id to set as a PVID
3286  **/
3287 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3288 {
3289         struct i40e_vsi_context ctxt;
3290         int ret;
3291
3292         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3293         vsi->info.pvid = cpu_to_le16(vid);
3294         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3295                                     I40E_AQ_VSI_PVLAN_INSERT_PVID |
3296                                     I40E_AQ_VSI_PVLAN_EMOD_STR;
3297
3298         ctxt.seid = vsi->seid;
3299         ctxt.info = vsi->info;
3300         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3301         if (ret) {
3302                 dev_info(&vsi->back->pdev->dev,
3303                          "add pvid failed, err %pe aq_err %s\n",
3304                          ERR_PTR(ret),
3305                          i40e_aq_str(&vsi->back->hw,
3306                                      vsi->back->hw.aq.asq_last_status));
3307                 return -ENOENT;
3308         }
3309
3310         return 0;
3311 }
3312
3313 /**
3314  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3315  * @vsi: the vsi being adjusted
3316  *
3317  * Just use the vlan_rx_register() service to put it back to normal
3318  **/
3319 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3320 {
3321         vsi->info.pvid = 0;
3322
3323         i40e_vlan_stripping_disable(vsi);
3324 }
3325
3326 /**
3327  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3328  * @vsi: ptr to the VSI
3329  *
3330  * If this function returns with an error, then it's possible one or
3331  * more of the rings is populated (while the rest are not).  It is the
3332  * callers duty to clean those orphaned rings.
3333  *
3334  * Return 0 on success, negative on failure
3335  **/
3336 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3337 {
3338         int i, err = 0;
3339
3340         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3341                 err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3342
3343         if (!i40e_enabled_xdp_vsi(vsi))
3344                 return err;
3345
3346         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3347                 err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3348
3349         return err;
3350 }
3351
3352 /**
3353  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3354  * @vsi: ptr to the VSI
3355  *
3356  * Free VSI's transmit software resources
3357  **/
3358 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3359 {
3360         int i;
3361
3362         if (vsi->tx_rings) {
3363                 for (i = 0; i < vsi->num_queue_pairs; i++)
3364                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3365                                 i40e_free_tx_resources(vsi->tx_rings[i]);
3366         }
3367
3368         if (vsi->xdp_rings) {
3369                 for (i = 0; i < vsi->num_queue_pairs; i++)
3370                         if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3371                                 i40e_free_tx_resources(vsi->xdp_rings[i]);
3372         }
3373 }
3374
3375 /**
3376  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3377  * @vsi: ptr to the VSI
3378  *
3379  * If this function returns with an error, then it's possible one or
3380  * more of the rings is populated (while the rest are not).  It is the
3381  * callers duty to clean those orphaned rings.
3382  *
3383  * Return 0 on success, negative on failure
3384  **/
3385 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3386 {
3387         int i, err = 0;
3388
3389         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3390                 err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3391         return err;
3392 }
3393
3394 /**
3395  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3396  * @vsi: ptr to the VSI
3397  *
3398  * Free all receive software resources
3399  **/
3400 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3401 {
3402         int i;
3403
3404         if (!vsi->rx_rings)
3405                 return;
3406
3407         for (i = 0; i < vsi->num_queue_pairs; i++)
3408                 if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3409                         i40e_free_rx_resources(vsi->rx_rings[i]);
3410 }
3411
3412 /**
3413  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3414  * @ring: The Tx ring to configure
3415  *
3416  * This enables/disables XPS for a given Tx descriptor ring
3417  * based on the TCs enabled for the VSI that ring belongs to.
3418  **/
3419 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3420 {
3421         int cpu;
3422
3423         if (!ring->q_vector || !ring->netdev || ring->ch)
3424                 return;
3425
3426         /* We only initialize XPS once, so as not to overwrite user settings */
3427         if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3428                 return;
3429
3430         cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3431         netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3432                             ring->queue_index);
3433 }
3434
3435 /**
3436  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3437  * @ring: The Tx or Rx ring
3438  *
3439  * Returns the AF_XDP buffer pool or NULL.
3440  **/
3441 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3442 {
3443         bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3444         int qid = ring->queue_index;
3445
3446         if (ring_is_xdp(ring))
3447                 qid -= ring->vsi->alloc_queue_pairs;
3448
3449         if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3450                 return NULL;
3451
3452         return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3453 }
3454
3455 /**
3456  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3457  * @ring: The Tx ring to configure
3458  *
3459  * Configure the Tx descriptor ring in the HMC context.
3460  **/
3461 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3462 {
3463         struct i40e_vsi *vsi = ring->vsi;
3464         u16 pf_q = vsi->base_queue + ring->queue_index;
3465         struct i40e_hw *hw = &vsi->back->hw;
3466         struct i40e_hmc_obj_txq tx_ctx;
3467         u32 qtx_ctl = 0;
3468         int err = 0;
3469
3470         if (ring_is_xdp(ring))
3471                 ring->xsk_pool = i40e_xsk_pool(ring);
3472
3473         /* some ATR related tx ring init */
3474         if (test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags)) {
3475                 ring->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
3476                 ring->atr_count = 0;
3477         } else {
3478                 ring->atr_sample_rate = 0;
3479         }
3480
3481         /* configure XPS */
3482         i40e_config_xps_tx_ring(ring);
3483
3484         /* clear the context structure first */
3485         memset(&tx_ctx, 0, sizeof(tx_ctx));
3486
3487         tx_ctx.new_context = 1;
3488         tx_ctx.base = (ring->dma / 128);
3489         tx_ctx.qlen = ring->count;
3490         if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags) ||
3491             test_bit(I40E_FLAG_FD_ATR_ENA, vsi->back->flags))
3492                 tx_ctx.fd_ena = 1;
3493         if (test_bit(I40E_FLAG_PTP_ENA, vsi->back->flags))
3494                 tx_ctx.timesync_ena = 1;
3495         /* FDIR VSI tx ring can still use RS bit and writebacks */
3496         if (vsi->type != I40E_VSI_FDIR)
3497                 tx_ctx.head_wb_ena = 1;
3498         tx_ctx.head_wb_addr = ring->dma +
3499                               (ring->count * sizeof(struct i40e_tx_desc));
3500
3501         /* As part of VSI creation/update, FW allocates certain
3502          * Tx arbitration queue sets for each TC enabled for
3503          * the VSI. The FW returns the handles to these queue
3504          * sets as part of the response buffer to Add VSI,
3505          * Update VSI, etc. AQ commands. It is expected that
3506          * these queue set handles be associated with the Tx
3507          * queues by the driver as part of the TX queue context
3508          * initialization. This has to be done regardless of
3509          * DCB as by default everything is mapped to TC0.
3510          */
3511
3512         if (ring->ch)
3513                 tx_ctx.rdylist =
3514                         le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3515
3516         else
3517                 tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3518
3519         tx_ctx.rdylist_act = 0;
3520
3521         /* clear the context in the HMC */
3522         err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3523         if (err) {
3524                 dev_info(&vsi->back->pdev->dev,
3525                          "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3526                          ring->queue_index, pf_q, err);
3527                 return -ENOMEM;
3528         }
3529
3530         /* set the context in the HMC */
3531         err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3532         if (err) {
3533                 dev_info(&vsi->back->pdev->dev,
3534                          "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3535                          ring->queue_index, pf_q, err);
3536                 return -ENOMEM;
3537         }
3538
3539         /* Now associate this queue with this PCI function */
3540         if (ring->ch) {
3541                 if (ring->ch->type == I40E_VSI_VMDQ2)
3542                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3543                 else
3544                         return -EINVAL;
3545
3546                 qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3547                                       ring->ch->vsi_number);
3548         } else {
3549                 if (vsi->type == I40E_VSI_VMDQ2) {
3550                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3551                         qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_VFVM_INDX_MASK,
3552                                               vsi->id);
3553                 } else {
3554                         qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3555                 }
3556         }
3557
3558         qtx_ctl |= FIELD_PREP(I40E_QTX_CTL_PF_INDX_MASK, hw->pf_id);
3559         wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3560         i40e_flush(hw);
3561
3562         /* cache tail off for easier writes later */
3563         ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3564
3565         return 0;
3566 }
3567
3568 /**
3569  * i40e_rx_offset - Return expected offset into page to access data
3570  * @rx_ring: Ring we are requesting offset of
3571  *
3572  * Returns the offset value for ring into the data buffer.
3573  */
3574 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3575 {
3576         return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3577 }
3578
3579 /**
3580  * i40e_configure_rx_ring - Configure a receive ring context
3581  * @ring: The Rx ring to configure
3582  *
3583  * Configure the Rx descriptor ring in the HMC context.
3584  **/
3585 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3586 {
3587         struct i40e_vsi *vsi = ring->vsi;
3588         u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3589         u16 pf_q = vsi->base_queue + ring->queue_index;
3590         struct i40e_hw *hw = &vsi->back->hw;
3591         struct i40e_hmc_obj_rxq rx_ctx;
3592         int err = 0;
3593         bool ok;
3594
3595         bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3596
3597         /* clear the context structure first */
3598         memset(&rx_ctx, 0, sizeof(rx_ctx));
3599
3600         ring->rx_buf_len = vsi->rx_buf_len;
3601
3602         /* XDP RX-queue info only needed for RX rings exposed to XDP */
3603         if (ring->vsi->type != I40E_VSI_MAIN)
3604                 goto skip;
3605
3606         if (!xdp_rxq_info_is_reg(&ring->xdp_rxq)) {
3607                 err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3608                                          ring->queue_index,
3609                                          ring->q_vector->napi.napi_id,
3610                                          ring->rx_buf_len);
3611                 if (err)
3612                         return err;
3613         }
3614
3615         ring->xsk_pool = i40e_xsk_pool(ring);
3616         if (ring->xsk_pool) {
3617                 xdp_rxq_info_unreg(&ring->xdp_rxq);
3618                 ring->rx_buf_len = xsk_pool_get_rx_frame_size(ring->xsk_pool);
3619                 err = __xdp_rxq_info_reg(&ring->xdp_rxq, ring->netdev,
3620                                          ring->queue_index,
3621                                          ring->q_vector->napi.napi_id,
3622                                          ring->rx_buf_len);
3623                 if (err)
3624                         return err;
3625                 err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3626                                                  MEM_TYPE_XSK_BUFF_POOL,
3627                                                  NULL);
3628                 if (err)
3629                         return err;
3630                 dev_info(&vsi->back->pdev->dev,
3631                          "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3632                          ring->queue_index);
3633
3634         } else {
3635                 err = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3636                                                  MEM_TYPE_PAGE_SHARED,
3637                                                  NULL);
3638                 if (err)
3639                         return err;
3640         }
3641
3642 skip:
3643         xdp_init_buff(&ring->xdp, i40e_rx_pg_size(ring) / 2, &ring->xdp_rxq);
3644
3645         rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3646                                     BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3647
3648         rx_ctx.base = (ring->dma / 128);
3649         rx_ctx.qlen = ring->count;
3650
3651         /* use 16 byte descriptors */
3652         rx_ctx.dsize = 0;
3653
3654         /* descriptor type is always zero
3655          * rx_ctx.dtype = 0;
3656          */
3657         rx_ctx.hsplit_0 = 0;
3658
3659         rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3660         if (hw->revision_id == 0)
3661                 rx_ctx.lrxqthresh = 0;
3662         else
3663                 rx_ctx.lrxqthresh = 1;
3664         rx_ctx.crcstrip = 1;
3665         rx_ctx.l2tsel = 1;
3666         /* this controls whether VLAN is stripped from inner headers */
3667         rx_ctx.showiv = 0;
3668         /* set the prefena field to 1 because the manual says to */
3669         rx_ctx.prefena = 1;
3670
3671         /* clear the context in the HMC */
3672         err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3673         if (err) {
3674                 dev_info(&vsi->back->pdev->dev,
3675                          "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3676                          ring->queue_index, pf_q, err);
3677                 return -ENOMEM;
3678         }
3679
3680         /* set the context in the HMC */
3681         err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3682         if (err) {
3683                 dev_info(&vsi->back->pdev->dev,
3684                          "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3685                          ring->queue_index, pf_q, err);
3686                 return -ENOMEM;
3687         }
3688
3689         /* configure Rx buffer alignment */
3690         if (!vsi->netdev || test_bit(I40E_FLAG_LEGACY_RX_ENA, vsi->back->flags)) {
3691                 if (I40E_2K_TOO_SMALL_WITH_PADDING) {
3692                         dev_info(&vsi->back->pdev->dev,
3693                                  "2k Rx buffer is too small to fit standard MTU and skb_shared_info\n");
3694                         return -EOPNOTSUPP;
3695                 }
3696                 clear_ring_build_skb_enabled(ring);
3697         } else {
3698                 set_ring_build_skb_enabled(ring);
3699         }
3700
3701         ring->rx_offset = i40e_rx_offset(ring);
3702
3703         /* cache tail for quicker writes, and clear the reg before use */
3704         ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3705         writel(0, ring->tail);
3706
3707         if (ring->xsk_pool) {
3708                 xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3709                 ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3710         } else {
3711                 ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3712         }
3713         if (!ok) {
3714                 /* Log this in case the user has forgotten to give the kernel
3715                  * any buffers, even later in the application.
3716                  */
3717                 dev_info(&vsi->back->pdev->dev,
3718                          "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3719                          ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3720                          ring->queue_index, pf_q);
3721         }
3722
3723         return 0;
3724 }
3725
3726 /**
3727  * i40e_vsi_configure_tx - Configure the VSI for Tx
3728  * @vsi: VSI structure describing this set of rings and resources
3729  *
3730  * Configure the Tx VSI for operation.
3731  **/
3732 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3733 {
3734         int err = 0;
3735         u16 i;
3736
3737         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3738                 err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3739
3740         if (err || !i40e_enabled_xdp_vsi(vsi))
3741                 return err;
3742
3743         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3744                 err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3745
3746         return err;
3747 }
3748
3749 /**
3750  * i40e_vsi_configure_rx - Configure the VSI for Rx
3751  * @vsi: the VSI being configured
3752  *
3753  * Configure the Rx VSI for operation.
3754  **/
3755 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3756 {
3757         int err = 0;
3758         u16 i;
3759
3760         vsi->max_frame = i40e_max_vsi_frame_size(vsi, vsi->xdp_prog);
3761         vsi->rx_buf_len = i40e_calculate_vsi_rx_buf_len(vsi);
3762
3763 #if (PAGE_SIZE < 8192)
3764         if (vsi->netdev && !I40E_2K_TOO_SMALL_WITH_PADDING &&
3765             vsi->netdev->mtu <= ETH_DATA_LEN) {
3766                 vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3767                 vsi->max_frame = vsi->rx_buf_len;
3768         }
3769 #endif
3770
3771         /* set up individual rings */
3772         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3773                 err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3774
3775         return err;
3776 }
3777
3778 /**
3779  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3780  * @vsi: ptr to the VSI
3781  **/
3782 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3783 {
3784         struct i40e_ring *tx_ring, *rx_ring;
3785         u16 qoffset, qcount;
3786         int i, n;
3787
3788         if (!test_bit(I40E_FLAG_DCB_ENA, vsi->back->flags)) {
3789                 /* Reset the TC information */
3790                 for (i = 0; i < vsi->num_queue_pairs; i++) {
3791                         rx_ring = vsi->rx_rings[i];
3792                         tx_ring = vsi->tx_rings[i];
3793                         rx_ring->dcb_tc = 0;
3794                         tx_ring->dcb_tc = 0;
3795                 }
3796                 return;
3797         }
3798
3799         for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3800                 if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3801                         continue;
3802
3803                 qoffset = vsi->tc_config.tc_info[n].qoffset;
3804                 qcount = vsi->tc_config.tc_info[n].qcount;
3805                 for (i = qoffset; i < (qoffset + qcount); i++) {
3806                         rx_ring = vsi->rx_rings[i];
3807                         tx_ring = vsi->tx_rings[i];
3808                         rx_ring->dcb_tc = n;
3809                         tx_ring->dcb_tc = n;
3810                 }
3811         }
3812 }
3813
3814 /**
3815  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3816  * @vsi: ptr to the VSI
3817  **/
3818 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3819 {
3820         if (vsi->netdev)
3821                 i40e_set_rx_mode(vsi->netdev);
3822 }
3823
3824 /**
3825  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3826  * @pf: Pointer to the targeted PF
3827  *
3828  * Set all flow director counters to 0.
3829  */
3830 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3831 {
3832         pf->fd_tcp4_filter_cnt = 0;
3833         pf->fd_udp4_filter_cnt = 0;
3834         pf->fd_sctp4_filter_cnt = 0;
3835         pf->fd_ip4_filter_cnt = 0;
3836         pf->fd_tcp6_filter_cnt = 0;
3837         pf->fd_udp6_filter_cnt = 0;
3838         pf->fd_sctp6_filter_cnt = 0;
3839         pf->fd_ip6_filter_cnt = 0;
3840 }
3841
3842 /**
3843  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3844  * @vsi: Pointer to the targeted VSI
3845  *
3846  * This function replays the hlist on the hw where all the SB Flow Director
3847  * filters were saved.
3848  **/
3849 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3850 {
3851         struct i40e_fdir_filter *filter;
3852         struct i40e_pf *pf = vsi->back;
3853         struct hlist_node *node;
3854
3855         if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
3856                 return;
3857
3858         /* Reset FDir counters as we're replaying all existing filters */
3859         i40e_reset_fdir_filter_cnt(pf);
3860
3861         hlist_for_each_entry_safe(filter, node,
3862                                   &pf->fdir_filter_list, fdir_node) {
3863                 i40e_add_del_fdir(vsi, filter, true);
3864         }
3865 }
3866
3867 /**
3868  * i40e_vsi_configure - Set up the VSI for action
3869  * @vsi: the VSI being configured
3870  **/
3871 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3872 {
3873         int err;
3874
3875         i40e_set_vsi_rx_mode(vsi);
3876         i40e_restore_vlan(vsi);
3877         i40e_vsi_config_dcb_rings(vsi);
3878         err = i40e_vsi_configure_tx(vsi);
3879         if (!err)
3880                 err = i40e_vsi_configure_rx(vsi);
3881
3882         return err;
3883 }
3884
3885 /**
3886  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3887  * @vsi: the VSI being configured
3888  **/
3889 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3890 {
3891         bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3892         struct i40e_pf *pf = vsi->back;
3893         struct i40e_hw *hw = &pf->hw;
3894         u16 vector;
3895         int i, q;
3896         u32 qp;
3897
3898         /* The interrupt indexing is offset by 1 in the PFINT_ITRn
3899          * and PFINT_LNKLSTn registers, e.g.:
3900          *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3901          */
3902         qp = vsi->base_queue;
3903         vector = vsi->base_vector;
3904         for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3905                 struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3906
3907                 q_vector->rx.next_update = jiffies + 1;
3908                 q_vector->rx.target_itr =
3909                         ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3910                 wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3911                      q_vector->rx.target_itr >> 1);
3912                 q_vector->rx.current_itr = q_vector->rx.target_itr;
3913
3914                 q_vector->tx.next_update = jiffies + 1;
3915                 q_vector->tx.target_itr =
3916                         ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3917                 wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3918                      q_vector->tx.target_itr >> 1);
3919                 q_vector->tx.current_itr = q_vector->tx.target_itr;
3920
3921                 /* Set ITR for software interrupts triggered after exiting
3922                  * busy-loop polling.
3923                  */
3924                 wr32(hw, I40E_PFINT_ITRN(I40E_SW_ITR, vector - 1),
3925                      I40E_ITR_20K);
3926
3927                 wr32(hw, I40E_PFINT_RATEN(vector - 1),
3928                      i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3929
3930                 /* begin of linked list for RX queue assigned to this vector */
3931                 wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3932                 for (q = 0; q < q_vector->num_ringpairs; q++) {
3933                         u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3934                         u32 val;
3935
3936                         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3937                               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3938                               (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3939                               (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3940                               (I40E_QUEUE_TYPE_TX <<
3941                                I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3942
3943                         wr32(hw, I40E_QINT_RQCTL(qp), val);
3944
3945                         if (has_xdp) {
3946                                 /* TX queue with next queue set to TX */
3947                                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3948                                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3949                                       (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3950                                       (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3951                                       (I40E_QUEUE_TYPE_TX <<
3952                                        I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3953
3954                                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3955                         }
3956                         /* TX queue with next RX or end of linked list */
3957                         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3958                               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3959                               (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3960                               ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3961                               (I40E_QUEUE_TYPE_RX <<
3962                                I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3963
3964                         /* Terminate the linked list */
3965                         if (q == (q_vector->num_ringpairs - 1))
3966                                 val |= (I40E_QUEUE_END_OF_LIST <<
3967                                         I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3968
3969                         wr32(hw, I40E_QINT_TQCTL(qp), val);
3970                         qp++;
3971                 }
3972         }
3973
3974         i40e_flush(hw);
3975 }
3976
3977 /**
3978  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3979  * @pf: pointer to private device data structure
3980  **/
3981 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3982 {
3983         struct i40e_hw *hw = &pf->hw;
3984         u32 val;
3985
3986         /* clear things first */
3987         wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3988         rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3989
3990         val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3991               I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3992               I40E_PFINT_ICR0_ENA_GRST_MASK          |
3993               I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3994               I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3995               I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3996               I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3997               I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3998
3999         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
4000                 val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4001
4002         if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
4003                 val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4004
4005         wr32(hw, I40E_PFINT_ICR0_ENA, val);
4006
4007         /* SW_ITR_IDX = 0, but don't change INTENA */
4008         wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
4009                                         I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
4010
4011         /* OTHER_ITR_IDX = 0 */
4012         wr32(hw, I40E_PFINT_STAT_CTL0, 0);
4013 }
4014
4015 /**
4016  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
4017  * @vsi: the VSI being configured
4018  **/
4019 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
4020 {
4021         u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
4022         struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4023         struct i40e_pf *pf = vsi->back;
4024         struct i40e_hw *hw = &pf->hw;
4025
4026         /* set the ITR configuration */
4027         q_vector->rx.next_update = jiffies + 1;
4028         q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
4029         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
4030         q_vector->rx.current_itr = q_vector->rx.target_itr;
4031         q_vector->tx.next_update = jiffies + 1;
4032         q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
4033         wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
4034         q_vector->tx.current_itr = q_vector->tx.target_itr;
4035
4036         i40e_enable_misc_int_causes(pf);
4037
4038         /* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
4039         wr32(hw, I40E_PFINT_LNKLST0, 0);
4040
4041         /* Associate the queue pair to the vector and enable the queue
4042          * interrupt RX queue in linked list with next queue set to TX
4043          */
4044         wr32(hw, I40E_QINT_RQCTL(0), I40E_QINT_RQCTL_VAL(nextqp, 0, TX));
4045
4046         if (i40e_enabled_xdp_vsi(vsi)) {
4047                 /* TX queue in linked list with next queue set to TX */
4048                 wr32(hw, I40E_QINT_TQCTL(nextqp),
4049                      I40E_QINT_TQCTL_VAL(nextqp, 0, TX));
4050         }
4051
4052         /* last TX queue so the next RX queue doesn't matter */
4053         wr32(hw, I40E_QINT_TQCTL(0),
4054              I40E_QINT_TQCTL_VAL(I40E_QUEUE_END_OF_LIST, 0, RX));
4055         i40e_flush(hw);
4056 }
4057
4058 /**
4059  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
4060  * @pf: board private structure
4061  **/
4062 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
4063 {
4064         struct i40e_hw *hw = &pf->hw;
4065
4066         wr32(hw, I40E_PFINT_DYN_CTL0,
4067              I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
4068         i40e_flush(hw);
4069 }
4070
4071 /**
4072  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
4073  * @pf: board private structure
4074  **/
4075 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
4076 {
4077         struct i40e_hw *hw = &pf->hw;
4078         u32 val;
4079
4080         val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
4081               I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
4082               (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
4083
4084         wr32(hw, I40E_PFINT_DYN_CTL0, val);
4085         i40e_flush(hw);
4086 }
4087
4088 /**
4089  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
4090  * @irq: interrupt number
4091  * @data: pointer to a q_vector
4092  **/
4093 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
4094 {
4095         struct i40e_q_vector *q_vector = data;
4096
4097         if (!q_vector->tx.ring && !q_vector->rx.ring)
4098                 return IRQ_HANDLED;
4099
4100         napi_schedule_irqoff(&q_vector->napi);
4101
4102         return IRQ_HANDLED;
4103 }
4104
4105 /**
4106  * i40e_irq_affinity_notify - Callback for affinity changes
4107  * @notify: context as to what irq was changed
4108  * @mask: the new affinity mask
4109  *
4110  * This is a callback function used by the irq_set_affinity_notifier function
4111  * so that we may register to receive changes to the irq affinity masks.
4112  **/
4113 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
4114                                      const cpumask_t *mask)
4115 {
4116         struct i40e_q_vector *q_vector =
4117                 container_of(notify, struct i40e_q_vector, affinity_notify);
4118
4119         cpumask_copy(&q_vector->affinity_mask, mask);
4120 }
4121
4122 /**
4123  * i40e_irq_affinity_release - Callback for affinity notifier release
4124  * @ref: internal core kernel usage
4125  *
4126  * This is a callback function used by the irq_set_affinity_notifier function
4127  * to inform the current notification subscriber that they will no longer
4128  * receive notifications.
4129  **/
4130 static void i40e_irq_affinity_release(struct kref *ref) {}
4131
4132 /**
4133  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
4134  * @vsi: the VSI being configured
4135  * @basename: name for the vector
4136  *
4137  * Allocates MSI-X vectors and requests interrupts from the kernel.
4138  **/
4139 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
4140 {
4141         int q_vectors = vsi->num_q_vectors;
4142         struct i40e_pf *pf = vsi->back;
4143         int base = vsi->base_vector;
4144         int rx_int_idx = 0;
4145         int tx_int_idx = 0;
4146         int vector, err;
4147         int irq_num;
4148         int cpu;
4149
4150         for (vector = 0; vector < q_vectors; vector++) {
4151                 struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
4152
4153                 irq_num = pf->msix_entries[base + vector].vector;
4154
4155                 if (q_vector->tx.ring && q_vector->rx.ring) {
4156                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4157                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
4158                         tx_int_idx++;
4159                 } else if (q_vector->rx.ring) {
4160                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4161                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
4162                 } else if (q_vector->tx.ring) {
4163                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
4164                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
4165                 } else {
4166                         /* skip this unused q_vector */
4167                         continue;
4168                 }
4169                 err = request_irq(irq_num,
4170                                   vsi->irq_handler,
4171                                   0,
4172                                   q_vector->name,
4173                                   q_vector);
4174                 if (err) {
4175                         dev_info(&pf->pdev->dev,
4176                                  "MSIX request_irq failed, error: %d\n", err);
4177                         goto free_queue_irqs;
4178                 }
4179
4180                 /* register for affinity change notifications */
4181                 q_vector->irq_num = irq_num;
4182                 q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4183                 q_vector->affinity_notify.release = i40e_irq_affinity_release;
4184                 irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4185                 /* Spread affinity hints out across online CPUs.
4186                  *
4187                  * get_cpu_mask returns a static constant mask with
4188                  * a permanent lifetime so it's ok to pass to
4189                  * irq_update_affinity_hint without making a copy.
4190                  */
4191                 cpu = cpumask_local_spread(q_vector->v_idx, -1);
4192                 irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4193         }
4194
4195         vsi->irqs_ready = true;
4196         return 0;
4197
4198 free_queue_irqs:
4199         while (vector) {
4200                 vector--;
4201                 irq_num = pf->msix_entries[base + vector].vector;
4202                 irq_set_affinity_notifier(irq_num, NULL);
4203                 irq_update_affinity_hint(irq_num, NULL);
4204                 free_irq(irq_num, &vsi->q_vectors[vector]);
4205         }
4206         return err;
4207 }
4208
4209 /**
4210  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4211  * @vsi: the VSI being un-configured
4212  **/
4213 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4214 {
4215         struct i40e_pf *pf = vsi->back;
4216         struct i40e_hw *hw = &pf->hw;
4217         int base = vsi->base_vector;
4218         int i;
4219
4220         /* disable interrupt causation from each queue */
4221         for (i = 0; i < vsi->num_queue_pairs; i++) {
4222                 u32 val;
4223
4224                 val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4225                 val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4226                 wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4227
4228                 val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4229                 val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4230                 wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4231
4232                 if (!i40e_enabled_xdp_vsi(vsi))
4233                         continue;
4234                 wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4235         }
4236
4237         /* disable each interrupt */
4238         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4239                 for (i = vsi->base_vector;
4240                      i < (vsi->num_q_vectors + vsi->base_vector); i++)
4241                         wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4242
4243                 i40e_flush(hw);
4244                 for (i = 0; i < vsi->num_q_vectors; i++)
4245                         synchronize_irq(pf->msix_entries[i + base].vector);
4246         } else {
4247                 /* Legacy and MSI mode - this stops all interrupt handling */
4248                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4249                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4250                 i40e_flush(hw);
4251                 synchronize_irq(pf->pdev->irq);
4252         }
4253 }
4254
4255 /**
4256  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4257  * @vsi: the VSI being configured
4258  **/
4259 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4260 {
4261         struct i40e_pf *pf = vsi->back;
4262         int i;
4263
4264         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4265                 for (i = 0; i < vsi->num_q_vectors; i++)
4266                         i40e_irq_dynamic_enable(vsi, i);
4267         } else {
4268                 i40e_irq_dynamic_enable_icr0(pf);
4269         }
4270
4271         i40e_flush(&pf->hw);
4272         return 0;
4273 }
4274
4275 /**
4276  * i40e_free_misc_vector - Free the vector that handles non-queue events
4277  * @pf: board private structure
4278  **/
4279 static void i40e_free_misc_vector(struct i40e_pf *pf)
4280 {
4281         /* Disable ICR 0 */
4282         wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4283         i40e_flush(&pf->hw);
4284
4285         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags) && pf->msix_entries) {
4286                 free_irq(pf->msix_entries[0].vector, pf);
4287                 clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4288         }
4289 }
4290
4291 /**
4292  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4293  * @irq: interrupt number
4294  * @data: pointer to a q_vector
4295  *
4296  * This is the handler used for all MSI/Legacy interrupts, and deals
4297  * with both queue and non-queue interrupts.  This is also used in
4298  * MSIX mode to handle the non-queue interrupts.
4299  **/
4300 static irqreturn_t i40e_intr(int irq, void *data)
4301 {
4302         struct i40e_pf *pf = (struct i40e_pf *)data;
4303         struct i40e_hw *hw = &pf->hw;
4304         irqreturn_t ret = IRQ_NONE;
4305         u32 icr0, icr0_remaining;
4306         u32 val, ena_mask;
4307
4308         icr0 = rd32(hw, I40E_PFINT_ICR0);
4309         ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4310
4311         /* if sharing a legacy IRQ, we might get called w/o an intr pending */
4312         if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4313                 goto enable_intr;
4314
4315         /* if interrupt but no bits showing, must be SWINT */
4316         if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4317             (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4318                 pf->sw_int_count++;
4319
4320         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
4321             (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4322                 ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4323                 dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4324                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4325         }
4326
4327         /* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4328         if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4329                 struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4330                 struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4331
4332                 /* We do not have a way to disarm Queue causes while leaving
4333                  * interrupt enabled for all other causes, ideally
4334                  * interrupt should be disabled while we are in NAPI but
4335                  * this is not a performance path and napi_schedule()
4336                  * can deal with rescheduling.
4337                  */
4338                 if (!test_bit(__I40E_DOWN, pf->state))
4339                         napi_schedule_irqoff(&q_vector->napi);
4340         }
4341
4342         if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4343                 ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4344                 set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4345                 i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4346         }
4347
4348         if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4349                 ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4350                 set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4351         }
4352
4353         if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4354                 /* disable any further VFLR event notifications */
4355                 if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4356                         u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4357
4358                         reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4359                         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4360                 } else {
4361                         ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4362                         set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4363                 }
4364         }
4365
4366         if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4367                 if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4368                         set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4369                 ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4370                 val = rd32(hw, I40E_GLGEN_RSTAT);
4371                 val = FIELD_GET(I40E_GLGEN_RSTAT_RESET_TYPE_MASK, val);
4372                 if (val == I40E_RESET_CORER) {
4373                         pf->corer_count++;
4374                 } else if (val == I40E_RESET_GLOBR) {
4375                         pf->globr_count++;
4376                 } else if (val == I40E_RESET_EMPR) {
4377                         pf->empr_count++;
4378                         set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4379                 }
4380         }
4381
4382         if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4383                 icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4384                 dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4385                 dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4386                          rd32(hw, I40E_PFHMC_ERRORINFO),
4387                          rd32(hw, I40E_PFHMC_ERRORDATA));
4388         }
4389
4390         if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4391                 u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4392
4393                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4394                         schedule_work(&pf->ptp_extts0_work);
4395
4396                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4397                         i40e_ptp_tx_hwtstamp(pf);
4398
4399                 icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4400         }
4401
4402         /* If a critical error is pending we have no choice but to reset the
4403          * device.
4404          * Report and mask out any remaining unexpected interrupts.
4405          */
4406         icr0_remaining = icr0 & ena_mask;
4407         if (icr0_remaining) {
4408                 dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4409                          icr0_remaining);
4410                 if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4411                     (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4412                     (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4413                         dev_info(&pf->pdev->dev, "device will be reset\n");
4414                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4415                         i40e_service_event_schedule(pf);
4416                 }
4417                 ena_mask &= ~icr0_remaining;
4418         }
4419         ret = IRQ_HANDLED;
4420
4421 enable_intr:
4422         /* re-enable interrupt causes */
4423         wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4424         if (!test_bit(__I40E_DOWN, pf->state) ||
4425             test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4426                 i40e_service_event_schedule(pf);
4427                 i40e_irq_dynamic_enable_icr0(pf);
4428         }
4429
4430         return ret;
4431 }
4432
4433 /**
4434  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4435  * @tx_ring:  tx ring to clean
4436  * @budget:   how many cleans we're allowed
4437  *
4438  * Returns true if there's any budget left (e.g. the clean is finished)
4439  **/
4440 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4441 {
4442         struct i40e_vsi *vsi = tx_ring->vsi;
4443         u16 i = tx_ring->next_to_clean;
4444         struct i40e_tx_buffer *tx_buf;
4445         struct i40e_tx_desc *tx_desc;
4446
4447         tx_buf = &tx_ring->tx_bi[i];
4448         tx_desc = I40E_TX_DESC(tx_ring, i);
4449         i -= tx_ring->count;
4450
4451         do {
4452                 struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4453
4454                 /* if next_to_watch is not set then there is no work pending */
4455                 if (!eop_desc)
4456                         break;
4457
4458                 /* prevent any other reads prior to eop_desc */
4459                 smp_rmb();
4460
4461                 /* if the descriptor isn't done, no work yet to do */
4462                 if (!(eop_desc->cmd_type_offset_bsz &
4463                       cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4464                         break;
4465
4466                 /* clear next_to_watch to prevent false hangs */
4467                 tx_buf->next_to_watch = NULL;
4468
4469                 tx_desc->buffer_addr = 0;
4470                 tx_desc->cmd_type_offset_bsz = 0;
4471                 /* move past filter desc */
4472                 tx_buf++;
4473                 tx_desc++;
4474                 i++;
4475                 if (unlikely(!i)) {
4476                         i -= tx_ring->count;
4477                         tx_buf = tx_ring->tx_bi;
4478                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4479                 }
4480                 /* unmap skb header data */
4481                 dma_unmap_single(tx_ring->dev,
4482                                  dma_unmap_addr(tx_buf, dma),
4483                                  dma_unmap_len(tx_buf, len),
4484                                  DMA_TO_DEVICE);
4485                 if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4486                         kfree(tx_buf->raw_buf);
4487
4488                 tx_buf->raw_buf = NULL;
4489                 tx_buf->tx_flags = 0;
4490                 tx_buf->next_to_watch = NULL;
4491                 dma_unmap_len_set(tx_buf, len, 0);
4492                 tx_desc->buffer_addr = 0;
4493                 tx_desc->cmd_type_offset_bsz = 0;
4494
4495                 /* move us past the eop_desc for start of next FD desc */
4496                 tx_buf++;
4497                 tx_desc++;
4498                 i++;
4499                 if (unlikely(!i)) {
4500                         i -= tx_ring->count;
4501                         tx_buf = tx_ring->tx_bi;
4502                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4503                 }
4504
4505                 /* update budget accounting */
4506                 budget--;
4507         } while (likely(budget));
4508
4509         i += tx_ring->count;
4510         tx_ring->next_to_clean = i;
4511
4512         if (test_bit(I40E_FLAG_MSIX_ENA, vsi->back->flags))
4513                 i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4514
4515         return budget > 0;
4516 }
4517
4518 /**
4519  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4520  * @irq: interrupt number
4521  * @data: pointer to a q_vector
4522  **/
4523 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4524 {
4525         struct i40e_q_vector *q_vector = data;
4526         struct i40e_vsi *vsi;
4527
4528         if (!q_vector->tx.ring)
4529                 return IRQ_HANDLED;
4530
4531         vsi = q_vector->tx.ring->vsi;
4532         i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4533
4534         return IRQ_HANDLED;
4535 }
4536
4537 /**
4538  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4539  * @vsi: the VSI being configured
4540  * @v_idx: vector index
4541  * @qp_idx: queue pair index
4542  **/
4543 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4544 {
4545         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4546         struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4547         struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4548
4549         tx_ring->q_vector = q_vector;
4550         tx_ring->next = q_vector->tx.ring;
4551         q_vector->tx.ring = tx_ring;
4552         q_vector->tx.count++;
4553
4554         /* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4555         if (i40e_enabled_xdp_vsi(vsi)) {
4556                 struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4557
4558                 xdp_ring->q_vector = q_vector;
4559                 xdp_ring->next = q_vector->tx.ring;
4560                 q_vector->tx.ring = xdp_ring;
4561                 q_vector->tx.count++;
4562         }
4563
4564         rx_ring->q_vector = q_vector;
4565         rx_ring->next = q_vector->rx.ring;
4566         q_vector->rx.ring = rx_ring;
4567         q_vector->rx.count++;
4568 }
4569
4570 /**
4571  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4572  * @vsi: the VSI being configured
4573  *
4574  * This function maps descriptor rings to the queue-specific vectors
4575  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4576  * one vector per queue pair, but on a constrained vector budget, we
4577  * group the queue pairs as "efficiently" as possible.
4578  **/
4579 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4580 {
4581         int qp_remaining = vsi->num_queue_pairs;
4582         int q_vectors = vsi->num_q_vectors;
4583         int num_ringpairs;
4584         int v_start = 0;
4585         int qp_idx = 0;
4586
4587         /* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4588          * group them so there are multiple queues per vector.
4589          * It is also important to go through all the vectors available to be
4590          * sure that if we don't use all the vectors, that the remaining vectors
4591          * are cleared. This is especially important when decreasing the
4592          * number of queues in use.
4593          */
4594         for (; v_start < q_vectors; v_start++) {
4595                 struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4596
4597                 num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4598
4599                 q_vector->num_ringpairs = num_ringpairs;
4600                 q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4601
4602                 q_vector->rx.count = 0;
4603                 q_vector->tx.count = 0;
4604                 q_vector->rx.ring = NULL;
4605                 q_vector->tx.ring = NULL;
4606
4607                 while (num_ringpairs--) {
4608                         i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4609                         qp_idx++;
4610                         qp_remaining--;
4611                 }
4612         }
4613 }
4614
4615 /**
4616  * i40e_vsi_request_irq - Request IRQ from the OS
4617  * @vsi: the VSI being configured
4618  * @basename: name for the vector
4619  **/
4620 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4621 {
4622         struct i40e_pf *pf = vsi->back;
4623         int err;
4624
4625         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
4626                 err = i40e_vsi_request_irq_msix(vsi, basename);
4627         else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags))
4628                 err = request_irq(pf->pdev->irq, i40e_intr, 0,
4629                                   pf->int_name, pf);
4630         else
4631                 err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4632                                   pf->int_name, pf);
4633
4634         if (err)
4635                 dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4636
4637         return err;
4638 }
4639
4640 #ifdef CONFIG_NET_POLL_CONTROLLER
4641 /**
4642  * i40e_netpoll - A Polling 'interrupt' handler
4643  * @netdev: network interface device structure
4644  *
4645  * This is used by netconsole to send skbs without having to re-enable
4646  * interrupts.  It's not called while the normal interrupt routine is executing.
4647  **/
4648 static void i40e_netpoll(struct net_device *netdev)
4649 {
4650         struct i40e_netdev_priv *np = netdev_priv(netdev);
4651         struct i40e_vsi *vsi = np->vsi;
4652         struct i40e_pf *pf = vsi->back;
4653         int i;
4654
4655         /* if interface is down do nothing */
4656         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4657                 return;
4658
4659         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4660                 for (i = 0; i < vsi->num_q_vectors; i++)
4661                         i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4662         } else {
4663                 i40e_intr(pf->pdev->irq, netdev);
4664         }
4665 }
4666 #endif
4667
4668 #define I40E_QTX_ENA_WAIT_COUNT 50
4669
4670 /**
4671  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4672  * @pf: the PF being configured
4673  * @pf_q: the PF queue
4674  * @enable: enable or disable state of the queue
4675  *
4676  * This routine will wait for the given Tx queue of the PF to reach the
4677  * enabled or disabled state.
4678  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4679  * multiple retries; else will return 0 in case of success.
4680  **/
4681 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4682 {
4683         int i;
4684         u32 tx_reg;
4685
4686         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4687                 tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4688                 if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4689                         break;
4690
4691                 usleep_range(10, 20);
4692         }
4693         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4694                 return -ETIMEDOUT;
4695
4696         return 0;
4697 }
4698
4699 /**
4700  * i40e_control_tx_q - Start or stop a particular Tx queue
4701  * @pf: the PF structure
4702  * @pf_q: the PF queue to configure
4703  * @enable: start or stop the queue
4704  *
4705  * This function enables or disables a single queue. Note that any delay
4706  * required after the operation is expected to be handled by the caller of
4707  * this function.
4708  **/
4709 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4710 {
4711         struct i40e_hw *hw = &pf->hw;
4712         u32 tx_reg;
4713         int i;
4714
4715         /* warn the TX unit of coming changes */
4716         i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4717         if (!enable)
4718                 usleep_range(10, 20);
4719
4720         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4721                 tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4722                 if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4723                     ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4724                         break;
4725                 usleep_range(1000, 2000);
4726         }
4727
4728         /* Skip if the queue is already in the requested state */
4729         if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4730                 return;
4731
4732         /* turn on/off the queue */
4733         if (enable) {
4734                 wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4735                 tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4736         } else {
4737                 tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4738         }
4739
4740         wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4741 }
4742
4743 /**
4744  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4745  * @seid: VSI SEID
4746  * @pf: the PF structure
4747  * @pf_q: the PF queue to configure
4748  * @is_xdp: true if the queue is used for XDP
4749  * @enable: start or stop the queue
4750  **/
4751 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4752                            bool is_xdp, bool enable)
4753 {
4754         int ret;
4755
4756         i40e_control_tx_q(pf, pf_q, enable);
4757
4758         /* wait for the change to finish */
4759         ret = i40e_pf_txq_wait(pf, pf_q, enable);
4760         if (ret) {
4761                 dev_info(&pf->pdev->dev,
4762                          "VSI seid %d %sTx ring %d %sable timeout\n",
4763                          seid, (is_xdp ? "XDP " : ""), pf_q,
4764                          (enable ? "en" : "dis"));
4765         }
4766
4767         return ret;
4768 }
4769
4770 /**
4771  * i40e_vsi_enable_tx - Start a VSI's rings
4772  * @vsi: the VSI being configured
4773  **/
4774 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4775 {
4776         struct i40e_pf *pf = vsi->back;
4777         int i, pf_q, ret = 0;
4778
4779         pf_q = vsi->base_queue;
4780         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4781                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4782                                              pf_q,
4783                                              false /*is xdp*/, true);
4784                 if (ret)
4785                         break;
4786
4787                 if (!i40e_enabled_xdp_vsi(vsi))
4788                         continue;
4789
4790                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4791                                              pf_q + vsi->alloc_queue_pairs,
4792                                              true /*is xdp*/, true);
4793                 if (ret)
4794                         break;
4795         }
4796         return ret;
4797 }
4798
4799 /**
4800  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4801  * @pf: the PF being configured
4802  * @pf_q: the PF queue
4803  * @enable: enable or disable state of the queue
4804  *
4805  * This routine will wait for the given Rx queue of the PF to reach the
4806  * enabled or disabled state.
4807  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4808  * multiple retries; else will return 0 in case of success.
4809  **/
4810 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4811 {
4812         int i;
4813         u32 rx_reg;
4814
4815         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4816                 rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4817                 if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4818                         break;
4819
4820                 usleep_range(10, 20);
4821         }
4822         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4823                 return -ETIMEDOUT;
4824
4825         return 0;
4826 }
4827
4828 /**
4829  * i40e_control_rx_q - Start or stop a particular Rx queue
4830  * @pf: the PF structure
4831  * @pf_q: the PF queue to configure
4832  * @enable: start or stop the queue
4833  *
4834  * This function enables or disables a single queue. Note that
4835  * any delay required after the operation is expected to be
4836  * handled by the caller of this function.
4837  **/
4838 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4839 {
4840         struct i40e_hw *hw = &pf->hw;
4841         u32 rx_reg;
4842         int i;
4843
4844         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4845                 rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4846                 if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4847                     ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4848                         break;
4849                 usleep_range(1000, 2000);
4850         }
4851
4852         /* Skip if the queue is already in the requested state */
4853         if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4854                 return;
4855
4856         /* turn on/off the queue */
4857         if (enable)
4858                 rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4859         else
4860                 rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4861
4862         wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4863 }
4864
4865 /**
4866  * i40e_control_wait_rx_q
4867  * @pf: the PF structure
4868  * @pf_q: queue being configured
4869  * @enable: start or stop the rings
4870  *
4871  * This function enables or disables a single queue along with waiting
4872  * for the change to finish. The caller of this function should handle
4873  * the delays needed in the case of disabling queues.
4874  **/
4875 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4876 {
4877         int ret = 0;
4878
4879         i40e_control_rx_q(pf, pf_q, enable);
4880
4881         /* wait for the change to finish */
4882         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4883         if (ret)
4884                 return ret;
4885
4886         return ret;
4887 }
4888
4889 /**
4890  * i40e_vsi_enable_rx - Start a VSI's rings
4891  * @vsi: the VSI being configured
4892  **/
4893 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4894 {
4895         struct i40e_pf *pf = vsi->back;
4896         int i, pf_q, ret = 0;
4897
4898         pf_q = vsi->base_queue;
4899         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4900                 ret = i40e_control_wait_rx_q(pf, pf_q, true);
4901                 if (ret) {
4902                         dev_info(&pf->pdev->dev,
4903                                  "VSI seid %d Rx ring %d enable timeout\n",
4904                                  vsi->seid, pf_q);
4905                         break;
4906                 }
4907         }
4908
4909         return ret;
4910 }
4911
4912 /**
4913  * i40e_vsi_start_rings - Start a VSI's rings
4914  * @vsi: the VSI being configured
4915  **/
4916 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4917 {
4918         int ret = 0;
4919
4920         /* do rx first for enable and last for disable */
4921         ret = i40e_vsi_enable_rx(vsi);
4922         if (ret)
4923                 return ret;
4924         ret = i40e_vsi_enable_tx(vsi);
4925
4926         return ret;
4927 }
4928
4929 #define I40E_DISABLE_TX_GAP_MSEC        50
4930
4931 /**
4932  * i40e_vsi_stop_rings - Stop a VSI's rings
4933  * @vsi: the VSI being configured
4934  **/
4935 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4936 {
4937         struct i40e_pf *pf = vsi->back;
4938         u32 pf_q, tx_q_end, rx_q_end;
4939
4940         /* When port TX is suspended, don't wait */
4941         if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4942                 return i40e_vsi_stop_rings_no_wait(vsi);
4943
4944         tx_q_end = vsi->base_queue +
4945                 vsi->alloc_queue_pairs * (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
4946         for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4947                 i40e_pre_tx_queue_cfg(&pf->hw, pf_q, false);
4948
4949         rx_q_end = vsi->base_queue + vsi->num_queue_pairs;
4950         for (pf_q = vsi->base_queue; pf_q < rx_q_end; pf_q++)
4951                 i40e_control_rx_q(pf, pf_q, false);
4952
4953         msleep(I40E_DISABLE_TX_GAP_MSEC);
4954         for (pf_q = vsi->base_queue; pf_q < tx_q_end; pf_q++)
4955                 wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4956
4957         i40e_vsi_wait_queues_disabled(vsi);
4958 }
4959
4960 /**
4961  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4962  * @vsi: the VSI being shutdown
4963  *
4964  * This function stops all the rings for a VSI but does not delay to verify
4965  * that rings have been disabled. It is expected that the caller is shutting
4966  * down multiple VSIs at once and will delay together for all the VSIs after
4967  * initiating the shutdown. This is particularly useful for shutting down lots
4968  * of VFs together. Otherwise, a large delay can be incurred while configuring
4969  * each VSI in serial.
4970  **/
4971 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4972 {
4973         struct i40e_pf *pf = vsi->back;
4974         int i, pf_q;
4975
4976         pf_q = vsi->base_queue;
4977         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4978                 i40e_control_tx_q(pf, pf_q, false);
4979                 i40e_control_rx_q(pf, pf_q, false);
4980         }
4981 }
4982
4983 /**
4984  * i40e_vsi_free_irq - Free the irq association with the OS
4985  * @vsi: the VSI being configured
4986  **/
4987 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4988 {
4989         struct i40e_pf *pf = vsi->back;
4990         struct i40e_hw *hw = &pf->hw;
4991         int base = vsi->base_vector;
4992         u32 val, qp;
4993         int i;
4994
4995         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
4996                 if (!vsi->q_vectors)
4997                         return;
4998
4999                 if (!vsi->irqs_ready)
5000                         return;
5001
5002                 vsi->irqs_ready = false;
5003                 for (i = 0; i < vsi->num_q_vectors; i++) {
5004                         int irq_num;
5005                         u16 vector;
5006
5007                         vector = i + base;
5008                         irq_num = pf->msix_entries[vector].vector;
5009
5010                         /* free only the irqs that were actually requested */
5011                         if (!vsi->q_vectors[i] ||
5012                             !vsi->q_vectors[i]->num_ringpairs)
5013                                 continue;
5014
5015                         /* clear the affinity notifier in the IRQ descriptor */
5016                         irq_set_affinity_notifier(irq_num, NULL);
5017                         /* remove our suggested affinity mask for this IRQ */
5018                         irq_update_affinity_hint(irq_num, NULL);
5019                         free_irq(irq_num, vsi->q_vectors[i]);
5020
5021                         /* Tear down the interrupt queue link list
5022                          *
5023                          * We know that they come in pairs and always
5024                          * the Rx first, then the Tx.  To clear the
5025                          * link list, stick the EOL value into the
5026                          * next_q field of the registers.
5027                          */
5028                         val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
5029                         qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK,
5030                                        val);
5031                         val |= I40E_QUEUE_END_OF_LIST
5032                                 << I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
5033                         wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
5034
5035                         while (qp != I40E_QUEUE_END_OF_LIST) {
5036                                 u32 next;
5037
5038                                 val = rd32(hw, I40E_QINT_RQCTL(qp));
5039
5040                                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5041                                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5042                                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5043                                          I40E_QINT_RQCTL_INTEVENT_MASK);
5044
5045                                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5046                                          I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5047
5048                                 wr32(hw, I40E_QINT_RQCTL(qp), val);
5049
5050                                 val = rd32(hw, I40E_QINT_TQCTL(qp));
5051
5052                                 next = FIELD_GET(I40E_QINT_TQCTL_NEXTQ_INDX_MASK,
5053                                                  val);
5054
5055                                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5056                                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5057                                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5058                                          I40E_QINT_TQCTL_INTEVENT_MASK);
5059
5060                                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5061                                          I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5062
5063                                 wr32(hw, I40E_QINT_TQCTL(qp), val);
5064                                 qp = next;
5065                         }
5066                 }
5067         } else {
5068                 free_irq(pf->pdev->irq, pf);
5069
5070                 val = rd32(hw, I40E_PFINT_LNKLST0);
5071                 qp = FIELD_GET(I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK, val);
5072                 val |= I40E_QUEUE_END_OF_LIST
5073                         << I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
5074                 wr32(hw, I40E_PFINT_LNKLST0, val);
5075
5076                 val = rd32(hw, I40E_QINT_RQCTL(qp));
5077                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
5078                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
5079                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
5080                          I40E_QINT_RQCTL_INTEVENT_MASK);
5081
5082                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
5083                         I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
5084
5085                 wr32(hw, I40E_QINT_RQCTL(qp), val);
5086
5087                 val = rd32(hw, I40E_QINT_TQCTL(qp));
5088
5089                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
5090                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
5091                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
5092                          I40E_QINT_TQCTL_INTEVENT_MASK);
5093
5094                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
5095                         I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
5096
5097                 wr32(hw, I40E_QINT_TQCTL(qp), val);
5098         }
5099 }
5100
5101 /**
5102  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
5103  * @vsi: the VSI being configured
5104  * @v_idx: Index of vector to be freed
5105  *
5106  * This function frees the memory allocated to the q_vector.  In addition if
5107  * NAPI is enabled it will delete any references to the NAPI struct prior
5108  * to freeing the q_vector.
5109  **/
5110 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
5111 {
5112         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
5113         struct i40e_ring *ring;
5114
5115         if (!q_vector)
5116                 return;
5117
5118         /* disassociate q_vector from rings */
5119         i40e_for_each_ring(ring, q_vector->tx)
5120                 ring->q_vector = NULL;
5121
5122         i40e_for_each_ring(ring, q_vector->rx)
5123                 ring->q_vector = NULL;
5124
5125         /* only VSI w/ an associated netdev is set up w/ NAPI */
5126         if (vsi->netdev)
5127                 netif_napi_del(&q_vector->napi);
5128
5129         vsi->q_vectors[v_idx] = NULL;
5130
5131         kfree_rcu(q_vector, rcu);
5132 }
5133
5134 /**
5135  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
5136  * @vsi: the VSI being un-configured
5137  *
5138  * This frees the memory allocated to the q_vectors and
5139  * deletes references to the NAPI struct.
5140  **/
5141 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
5142 {
5143         int v_idx;
5144
5145         for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
5146                 i40e_free_q_vector(vsi, v_idx);
5147 }
5148
5149 /**
5150  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
5151  * @pf: board private structure
5152  **/
5153 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
5154 {
5155         /* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
5156         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
5157                 pci_disable_msix(pf->pdev);
5158                 kfree(pf->msix_entries);
5159                 pf->msix_entries = NULL;
5160                 kfree(pf->irq_pile);
5161                 pf->irq_pile = NULL;
5162         } else if (test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
5163                 pci_disable_msi(pf->pdev);
5164         }
5165         clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
5166         clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
5167 }
5168
5169 /**
5170  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5171  * @pf: board private structure
5172  *
5173  * We go through and clear interrupt specific resources and reset the structure
5174  * to pre-load conditions
5175  **/
5176 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5177 {
5178         int i;
5179
5180         if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5181                 i40e_free_misc_vector(pf);
5182
5183         i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5184                       I40E_IWARP_IRQ_PILE_ID);
5185
5186         i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5187         for (i = 0; i < pf->num_alloc_vsi; i++)
5188                 if (pf->vsi[i])
5189                         i40e_vsi_free_q_vectors(pf->vsi[i]);
5190         i40e_reset_interrupt_capability(pf);
5191 }
5192
5193 /**
5194  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5195  * @vsi: the VSI being configured
5196  **/
5197 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5198 {
5199         int q_idx;
5200
5201         if (!vsi->netdev)
5202                 return;
5203
5204         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5205                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5206
5207                 if (q_vector->rx.ring || q_vector->tx.ring)
5208                         napi_enable(&q_vector->napi);
5209         }
5210 }
5211
5212 /**
5213  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5214  * @vsi: the VSI being configured
5215  **/
5216 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5217 {
5218         int q_idx;
5219
5220         if (!vsi->netdev)
5221                 return;
5222
5223         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5224                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5225
5226                 if (q_vector->rx.ring || q_vector->tx.ring)
5227                         napi_disable(&q_vector->napi);
5228         }
5229 }
5230
5231 /**
5232  * i40e_vsi_close - Shut down a VSI
5233  * @vsi: the vsi to be quelled
5234  **/
5235 static void i40e_vsi_close(struct i40e_vsi *vsi)
5236 {
5237         struct i40e_pf *pf = vsi->back;
5238         if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5239                 i40e_down(vsi);
5240         i40e_vsi_free_irq(vsi);
5241         i40e_vsi_free_tx_resources(vsi);
5242         i40e_vsi_free_rx_resources(vsi);
5243         vsi->current_netdev_flags = 0;
5244         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5245         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5246                 set_bit(__I40E_CLIENT_RESET, pf->state);
5247 }
5248
5249 /**
5250  * i40e_quiesce_vsi - Pause a given VSI
5251  * @vsi: the VSI being paused
5252  **/
5253 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5254 {
5255         if (test_bit(__I40E_VSI_DOWN, vsi->state))
5256                 return;
5257
5258         set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5259         if (vsi->netdev && netif_running(vsi->netdev))
5260                 vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5261         else
5262                 i40e_vsi_close(vsi);
5263 }
5264
5265 /**
5266  * i40e_unquiesce_vsi - Resume a given VSI
5267  * @vsi: the VSI being resumed
5268  **/
5269 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5270 {
5271         if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5272                 return;
5273
5274         if (vsi->netdev && netif_running(vsi->netdev))
5275                 vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5276         else
5277                 i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5278 }
5279
5280 /**
5281  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5282  * @pf: the PF
5283  **/
5284 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5285 {
5286         int v;
5287
5288         for (v = 0; v < pf->num_alloc_vsi; v++) {
5289                 if (pf->vsi[v])
5290                         i40e_quiesce_vsi(pf->vsi[v]);
5291         }
5292 }
5293
5294 /**
5295  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5296  * @pf: the PF
5297  **/
5298 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5299 {
5300         int v;
5301
5302         for (v = 0; v < pf->num_alloc_vsi; v++) {
5303                 if (pf->vsi[v])
5304                         i40e_unquiesce_vsi(pf->vsi[v]);
5305         }
5306 }
5307
5308 /**
5309  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5310  * @vsi: the VSI being configured
5311  *
5312  * Wait until all queues on a given VSI have been disabled.
5313  **/
5314 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5315 {
5316         struct i40e_pf *pf = vsi->back;
5317         int i, pf_q, ret;
5318
5319         pf_q = vsi->base_queue;
5320         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5321                 /* Check and wait for the Tx queue */
5322                 ret = i40e_pf_txq_wait(pf, pf_q, false);
5323                 if (ret) {
5324                         dev_info(&pf->pdev->dev,
5325                                  "VSI seid %d Tx ring %d disable timeout\n",
5326                                  vsi->seid, pf_q);
5327                         return ret;
5328                 }
5329
5330                 if (!i40e_enabled_xdp_vsi(vsi))
5331                         goto wait_rx;
5332
5333                 /* Check and wait for the XDP Tx queue */
5334                 ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5335                                        false);
5336                 if (ret) {
5337                         dev_info(&pf->pdev->dev,
5338                                  "VSI seid %d XDP Tx ring %d disable timeout\n",
5339                                  vsi->seid, pf_q);
5340                         return ret;
5341                 }
5342 wait_rx:
5343                 /* Check and wait for the Rx queue */
5344                 ret = i40e_pf_rxq_wait(pf, pf_q, false);
5345                 if (ret) {
5346                         dev_info(&pf->pdev->dev,
5347                                  "VSI seid %d Rx ring %d disable timeout\n",
5348                                  vsi->seid, pf_q);
5349                         return ret;
5350                 }
5351         }
5352
5353         return 0;
5354 }
5355
5356 #ifdef CONFIG_I40E_DCB
5357 /**
5358  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5359  * @pf: the PF
5360  *
5361  * This function waits for the queues to be in disabled state for all the
5362  * VSIs that are managed by this PF.
5363  **/
5364 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5365 {
5366         int v, ret = 0;
5367
5368         for (v = 0; v < pf->num_alloc_vsi; v++) {
5369                 if (pf->vsi[v]) {
5370                         ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5371                         if (ret)
5372                                 break;
5373                 }
5374         }
5375
5376         return ret;
5377 }
5378
5379 #endif
5380
5381 /**
5382  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5383  * @pf: pointer to PF
5384  *
5385  * Get TC map for ISCSI PF type that will include iSCSI TC
5386  * and LAN TC.
5387  **/
5388 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5389 {
5390         struct i40e_dcb_app_priority_table app;
5391         struct i40e_hw *hw = &pf->hw;
5392         u8 enabled_tc = 1; /* TC0 is always enabled */
5393         u8 tc, i;
5394         /* Get the iSCSI APP TLV */
5395         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5396
5397         for (i = 0; i < dcbcfg->numapps; i++) {
5398                 app = dcbcfg->app[i];
5399                 if (app.selector == I40E_APP_SEL_TCPIP &&
5400                     app.protocolid == I40E_APP_PROTOID_ISCSI) {
5401                         tc = dcbcfg->etscfg.prioritytable[app.priority];
5402                         enabled_tc |= BIT(tc);
5403                         break;
5404                 }
5405         }
5406
5407         return enabled_tc;
5408 }
5409
5410 /**
5411  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5412  * @dcbcfg: the corresponding DCBx configuration structure
5413  *
5414  * Return the number of TCs from given DCBx configuration
5415  **/
5416 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5417 {
5418         int i, tc_unused = 0;
5419         u8 num_tc = 0;
5420         u8 ret = 0;
5421
5422         /* Scan the ETS Config Priority Table to find
5423          * traffic class enabled for a given priority
5424          * and create a bitmask of enabled TCs
5425          */
5426         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5427                 num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5428
5429         /* Now scan the bitmask to check for
5430          * contiguous TCs starting with TC0
5431          */
5432         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5433                 if (num_tc & BIT(i)) {
5434                         if (!tc_unused) {
5435                                 ret++;
5436                         } else {
5437                                 pr_err("Non-contiguous TC - Disabling DCB\n");
5438                                 return 1;
5439                         }
5440                 } else {
5441                         tc_unused = 1;
5442                 }
5443         }
5444
5445         /* There is always at least TC0 */
5446         if (!ret)
5447                 ret = 1;
5448
5449         return ret;
5450 }
5451
5452 /**
5453  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5454  * @dcbcfg: the corresponding DCBx configuration structure
5455  *
5456  * Query the current DCB configuration and return the number of
5457  * traffic classes enabled from the given DCBX config
5458  **/
5459 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5460 {
5461         u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5462         u8 enabled_tc = 1;
5463         u8 i;
5464
5465         for (i = 0; i < num_tc; i++)
5466                 enabled_tc |= BIT(i);
5467
5468         return enabled_tc;
5469 }
5470
5471 /**
5472  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5473  * @pf: PF being queried
5474  *
5475  * Query the current MQPRIO configuration and return the number of
5476  * traffic classes enabled.
5477  **/
5478 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5479 {
5480         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5481         u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5482         u8 enabled_tc = 1, i;
5483
5484         for (i = 1; i < num_tc; i++)
5485                 enabled_tc |= BIT(i);
5486         return enabled_tc;
5487 }
5488
5489 /**
5490  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5491  * @pf: PF being queried
5492  *
5493  * Return number of traffic classes enabled for the given PF
5494  **/
5495 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5496 {
5497         struct i40e_hw *hw = &pf->hw;
5498         u8 i, enabled_tc = 1;
5499         u8 num_tc = 0;
5500         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5501
5502         if (i40e_is_tc_mqprio_enabled(pf))
5503                 return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5504
5505         /* If neither MQPRIO nor DCB is enabled, then always use single TC */
5506         if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5507                 return 1;
5508
5509         /* SFP mode will be enabled for all TCs on port */
5510         if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5511                 return i40e_dcb_get_num_tc(dcbcfg);
5512
5513         /* MFP mode return count of enabled TCs for this PF */
5514         if (pf->hw.func_caps.iscsi)
5515                 enabled_tc =  i40e_get_iscsi_tc_map(pf);
5516         else
5517                 return 1; /* Only TC0 */
5518
5519         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5520                 if (enabled_tc & BIT(i))
5521                         num_tc++;
5522         }
5523         return num_tc;
5524 }
5525
5526 /**
5527  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5528  * @pf: PF being queried
5529  *
5530  * Return a bitmap for enabled traffic classes for this PF.
5531  **/
5532 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5533 {
5534         if (i40e_is_tc_mqprio_enabled(pf))
5535                 return i40e_mqprio_get_enabled_tc(pf);
5536
5537         /* If neither MQPRIO nor DCB is enabled for this PF then just return
5538          * default TC
5539          */
5540         if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags))
5541                 return I40E_DEFAULT_TRAFFIC_CLASS;
5542
5543         /* SFP mode we want PF to be enabled for all TCs */
5544         if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
5545                 return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5546
5547         /* MFP enabled and iSCSI PF type */
5548         if (pf->hw.func_caps.iscsi)
5549                 return i40e_get_iscsi_tc_map(pf);
5550         else
5551                 return I40E_DEFAULT_TRAFFIC_CLASS;
5552 }
5553
5554 /**
5555  * i40e_vsi_get_bw_info - Query VSI BW Information
5556  * @vsi: the VSI being queried
5557  *
5558  * Returns 0 on success, negative value on failure
5559  **/
5560 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5561 {
5562         struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5563         struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5564         struct i40e_pf *pf = vsi->back;
5565         struct i40e_hw *hw = &pf->hw;
5566         u32 tc_bw_max;
5567         int ret;
5568         int i;
5569
5570         /* Get the VSI level BW configuration */
5571         ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5572         if (ret) {
5573                 dev_info(&pf->pdev->dev,
5574                          "couldn't get PF vsi bw config, err %pe aq_err %s\n",
5575                          ERR_PTR(ret),
5576                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5577                 return -EINVAL;
5578         }
5579
5580         /* Get the VSI level BW configuration per TC */
5581         ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5582                                                NULL);
5583         if (ret) {
5584                 dev_info(&pf->pdev->dev,
5585                          "couldn't get PF vsi ets bw config, err %pe aq_err %s\n",
5586                          ERR_PTR(ret),
5587                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5588                 return -EINVAL;
5589         }
5590
5591         if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5592                 dev_info(&pf->pdev->dev,
5593                          "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5594                          bw_config.tc_valid_bits,
5595                          bw_ets_config.tc_valid_bits);
5596                 /* Still continuing */
5597         }
5598
5599         vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5600         vsi->bw_max_quanta = bw_config.max_bw;
5601         tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5602                     (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5603         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5604                 vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5605                 vsi->bw_ets_limit_credits[i] =
5606                                         le16_to_cpu(bw_ets_config.credits[i]);
5607                 /* 3 bits out of 4 for each TC */
5608                 vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5609         }
5610
5611         return 0;
5612 }
5613
5614 /**
5615  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5616  * @vsi: the VSI being configured
5617  * @enabled_tc: TC bitmap
5618  * @bw_share: BW shared credits per TC
5619  *
5620  * Returns 0 on success, negative value on failure
5621  **/
5622 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5623                                        u8 *bw_share)
5624 {
5625         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5626         struct i40e_pf *pf = vsi->back;
5627         int ret;
5628         int i;
5629
5630         /* There is no need to reset BW when mqprio mode is on.  */
5631         if (i40e_is_tc_mqprio_enabled(pf))
5632                 return 0;
5633         if (!vsi->mqprio_qopt.qopt.hw && !test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
5634                 ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5635                 if (ret)
5636                         dev_info(&pf->pdev->dev,
5637                                  "Failed to reset tx rate for vsi->seid %u\n",
5638                                  vsi->seid);
5639                 return ret;
5640         }
5641         memset(&bw_data, 0, sizeof(bw_data));
5642         bw_data.tc_valid_bits = enabled_tc;
5643         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5644                 bw_data.tc_bw_credits[i] = bw_share[i];
5645
5646         ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5647         if (ret) {
5648                 dev_info(&pf->pdev->dev,
5649                          "AQ command Config VSI BW allocation per TC failed = %d\n",
5650                          pf->hw.aq.asq_last_status);
5651                 return -EINVAL;
5652         }
5653
5654         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5655                 vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5656
5657         return 0;
5658 }
5659
5660 /**
5661  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5662  * @vsi: the VSI being configured
5663  * @enabled_tc: TC map to be enabled
5664  *
5665  **/
5666 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5667 {
5668         struct net_device *netdev = vsi->netdev;
5669         struct i40e_pf *pf = vsi->back;
5670         struct i40e_hw *hw = &pf->hw;
5671         u8 netdev_tc = 0;
5672         int i;
5673         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5674
5675         if (!netdev)
5676                 return;
5677
5678         if (!enabled_tc) {
5679                 netdev_reset_tc(netdev);
5680                 return;
5681         }
5682
5683         /* Set up actual enabled TCs on the VSI */
5684         if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5685                 return;
5686
5687         /* set per TC queues for the VSI */
5688         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5689                 /* Only set TC queues for enabled tcs
5690                  *
5691                  * e.g. For a VSI that has TC0 and TC3 enabled the
5692                  * enabled_tc bitmap would be 0x00001001; the driver
5693                  * will set the numtc for netdev as 2 that will be
5694                  * referenced by the netdev layer as TC 0 and 1.
5695                  */
5696                 if (vsi->tc_config.enabled_tc & BIT(i))
5697                         netdev_set_tc_queue(netdev,
5698                                         vsi->tc_config.tc_info[i].netdev_tc,
5699                                         vsi->tc_config.tc_info[i].qcount,
5700                                         vsi->tc_config.tc_info[i].qoffset);
5701         }
5702
5703         if (i40e_is_tc_mqprio_enabled(pf))
5704                 return;
5705
5706         /* Assign UP2TC map for the VSI */
5707         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5708                 /* Get the actual TC# for the UP */
5709                 u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5710                 /* Get the mapped netdev TC# for the UP */
5711                 netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5712                 netdev_set_prio_tc_map(netdev, i, netdev_tc);
5713         }
5714 }
5715
5716 /**
5717  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5718  * @vsi: the VSI being configured
5719  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5720  **/
5721 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5722                                       struct i40e_vsi_context *ctxt)
5723 {
5724         /* copy just the sections touched not the entire info
5725          * since not all sections are valid as returned by
5726          * update vsi params
5727          */
5728         vsi->info.mapping_flags = ctxt->info.mapping_flags;
5729         memcpy(&vsi->info.queue_mapping,
5730                &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5731         memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5732                sizeof(vsi->info.tc_mapping));
5733 }
5734
5735 /**
5736  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5737  * @vsi: the VSI being reconfigured
5738  * @vsi_offset: offset from main VF VSI
5739  */
5740 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5741 {
5742         struct i40e_vsi_context ctxt = {};
5743         struct i40e_pf *pf;
5744         struct i40e_hw *hw;
5745         int ret;
5746
5747         if (!vsi)
5748                 return -EINVAL;
5749         pf = vsi->back;
5750         hw = &pf->hw;
5751
5752         ctxt.seid = vsi->seid;
5753         ctxt.pf_num = hw->pf_id;
5754         ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5755         ctxt.uplink_seid = vsi->uplink_seid;
5756         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5757         ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5758         ctxt.info = vsi->info;
5759
5760         i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5761                                  false);
5762         if (vsi->reconfig_rss) {
5763                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
5764                                       vsi->num_queue_pairs);
5765                 ret = i40e_vsi_config_rss(vsi);
5766                 if (ret) {
5767                         dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5768                         return ret;
5769                 }
5770                 vsi->reconfig_rss = false;
5771         }
5772
5773         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5774         if (ret) {
5775                 dev_info(&pf->pdev->dev, "Update vsi config failed, err %pe aq_err %s\n",
5776                          ERR_PTR(ret),
5777                          i40e_aq_str(hw, hw->aq.asq_last_status));
5778                 return ret;
5779         }
5780         /* update the local VSI info with updated queue map */
5781         i40e_vsi_update_queue_map(vsi, &ctxt);
5782         vsi->info.valid_sections = 0;
5783
5784         return ret;
5785 }
5786
5787 /**
5788  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5789  * @vsi: VSI to be configured
5790  * @enabled_tc: TC bitmap
5791  *
5792  * This configures a particular VSI for TCs that are mapped to the
5793  * given TC bitmap. It uses default bandwidth share for TCs across
5794  * VSIs to configure TC for a particular VSI.
5795  *
5796  * NOTE:
5797  * It is expected that the VSI queues have been quisced before calling
5798  * this function.
5799  **/
5800 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5801 {
5802         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5803         struct i40e_pf *pf = vsi->back;
5804         struct i40e_hw *hw = &pf->hw;
5805         struct i40e_vsi_context ctxt;
5806         int ret = 0;
5807         int i;
5808
5809         /* Check if enabled_tc is same as existing or new TCs */
5810         if (vsi->tc_config.enabled_tc == enabled_tc &&
5811             vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5812                 return ret;
5813
5814         /* Enable ETS TCs with equal BW Share for now across all VSIs */
5815         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5816                 if (enabled_tc & BIT(i))
5817                         bw_share[i] = 1;
5818         }
5819
5820         ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5821         if (ret) {
5822                 struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5823
5824                 dev_info(&pf->pdev->dev,
5825                          "Failed configuring TC map %d for VSI %d\n",
5826                          enabled_tc, vsi->seid);
5827                 ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5828                                                   &bw_config, NULL);
5829                 if (ret) {
5830                         dev_info(&pf->pdev->dev,
5831                                  "Failed querying vsi bw info, err %pe aq_err %s\n",
5832                                  ERR_PTR(ret),
5833                                  i40e_aq_str(hw, hw->aq.asq_last_status));
5834                         goto out;
5835                 }
5836                 if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5837                         u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5838
5839                         if (!valid_tc)
5840                                 valid_tc = bw_config.tc_valid_bits;
5841                         /* Always enable TC0, no matter what */
5842                         valid_tc |= 1;
5843                         dev_info(&pf->pdev->dev,
5844                                  "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5845                                  enabled_tc, bw_config.tc_valid_bits, valid_tc);
5846                         enabled_tc = valid_tc;
5847                 }
5848
5849                 ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5850                 if (ret) {
5851                         dev_err(&pf->pdev->dev,
5852                                 "Unable to  configure TC map %d for VSI %d\n",
5853                                 enabled_tc, vsi->seid);
5854                         goto out;
5855                 }
5856         }
5857
5858         /* Update Queue Pairs Mapping for currently enabled UPs */
5859         ctxt.seid = vsi->seid;
5860         ctxt.pf_num = vsi->back->hw.pf_id;
5861         ctxt.vf_num = 0;
5862         ctxt.uplink_seid = vsi->uplink_seid;
5863         ctxt.info = vsi->info;
5864         if (i40e_is_tc_mqprio_enabled(pf)) {
5865                 ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5866                 if (ret)
5867                         goto out;
5868         } else {
5869                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5870         }
5871
5872         /* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5873          * queues changed.
5874          */
5875         if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5876                 vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5877                                       vsi->num_queue_pairs);
5878                 ret = i40e_vsi_config_rss(vsi);
5879                 if (ret) {
5880                         dev_info(&vsi->back->pdev->dev,
5881                                  "Failed to reconfig rss for num_queues\n");
5882                         return ret;
5883                 }
5884                 vsi->reconfig_rss = false;
5885         }
5886         if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
5887                 ctxt.info.valid_sections |=
5888                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5889                 ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5890         }
5891
5892         /* Update the VSI after updating the VSI queue-mapping
5893          * information
5894          */
5895         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5896         if (ret) {
5897                 dev_info(&pf->pdev->dev,
5898                          "Update vsi tc config failed, err %pe aq_err %s\n",
5899                          ERR_PTR(ret),
5900                          i40e_aq_str(hw, hw->aq.asq_last_status));
5901                 goto out;
5902         }
5903         /* update the local VSI info with updated queue map */
5904         i40e_vsi_update_queue_map(vsi, &ctxt);
5905         vsi->info.valid_sections = 0;
5906
5907         /* Update current VSI BW information */
5908         ret = i40e_vsi_get_bw_info(vsi);
5909         if (ret) {
5910                 dev_info(&pf->pdev->dev,
5911                          "Failed updating vsi bw info, err %pe aq_err %s\n",
5912                          ERR_PTR(ret),
5913                          i40e_aq_str(hw, hw->aq.asq_last_status));
5914                 goto out;
5915         }
5916
5917         /* Update the netdev TC setup */
5918         i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5919 out:
5920         return ret;
5921 }
5922
5923 /**
5924  * i40e_get_link_speed - Returns link speed for the interface
5925  * @vsi: VSI to be configured
5926  *
5927  **/
5928 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5929 {
5930         struct i40e_pf *pf = vsi->back;
5931
5932         switch (pf->hw.phy.link_info.link_speed) {
5933         case I40E_LINK_SPEED_40GB:
5934                 return 40000;
5935         case I40E_LINK_SPEED_25GB:
5936                 return 25000;
5937         case I40E_LINK_SPEED_20GB:
5938                 return 20000;
5939         case I40E_LINK_SPEED_10GB:
5940                 return 10000;
5941         case I40E_LINK_SPEED_1GB:
5942                 return 1000;
5943         default:
5944                 return -EINVAL;
5945         }
5946 }
5947
5948 /**
5949  * i40e_bw_bytes_to_mbits - Convert max_tx_rate from bytes to mbits
5950  * @vsi: Pointer to vsi structure
5951  * @max_tx_rate: max TX rate in bytes to be converted into Mbits
5952  *
5953  * Helper function to convert units before send to set BW limit
5954  **/
5955 static u64 i40e_bw_bytes_to_mbits(struct i40e_vsi *vsi, u64 max_tx_rate)
5956 {
5957         if (max_tx_rate < I40E_BW_MBPS_DIVISOR) {
5958                 dev_warn(&vsi->back->pdev->dev,
5959                          "Setting max tx rate to minimum usable value of 50Mbps.\n");
5960                 max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5961         } else {
5962                 do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
5963         }
5964
5965         return max_tx_rate;
5966 }
5967
5968 /**
5969  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5970  * @vsi: VSI to be configured
5971  * @seid: seid of the channel/VSI
5972  * @max_tx_rate: max TX rate to be configured as BW limit
5973  *
5974  * Helper function to set BW limit for a given VSI
5975  **/
5976 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5977 {
5978         struct i40e_pf *pf = vsi->back;
5979         u64 credits = 0;
5980         int speed = 0;
5981         int ret = 0;
5982
5983         speed = i40e_get_link_speed(vsi);
5984         if (max_tx_rate > speed) {
5985                 dev_err(&pf->pdev->dev,
5986                         "Invalid max tx rate %llu specified for VSI seid %d.",
5987                         max_tx_rate, seid);
5988                 return -EINVAL;
5989         }
5990         if (max_tx_rate && max_tx_rate < I40E_BW_CREDIT_DIVISOR) {
5991                 dev_warn(&pf->pdev->dev,
5992                          "Setting max tx rate to minimum usable value of 50Mbps.\n");
5993                 max_tx_rate = I40E_BW_CREDIT_DIVISOR;
5994         }
5995
5996         /* Tx rate credits are in values of 50Mbps, 0 is disabled */
5997         credits = max_tx_rate;
5998         do_div(credits, I40E_BW_CREDIT_DIVISOR);
5999         ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
6000                                           I40E_MAX_BW_INACTIVE_ACCUM, NULL);
6001         if (ret)
6002                 dev_err(&pf->pdev->dev,
6003                         "Failed set tx rate (%llu Mbps) for vsi->seid %u, err %pe aq_err %s\n",
6004                         max_tx_rate, seid, ERR_PTR(ret),
6005                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6006         return ret;
6007 }
6008
6009 /**
6010  * i40e_remove_queue_channels - Remove queue channels for the TCs
6011  * @vsi: VSI to be configured
6012  *
6013  * Remove queue channels for the TCs
6014  **/
6015 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
6016 {
6017         enum i40e_admin_queue_err last_aq_status;
6018         struct i40e_cloud_filter *cfilter;
6019         struct i40e_channel *ch, *ch_tmp;
6020         struct i40e_pf *pf = vsi->back;
6021         struct hlist_node *node;
6022         int ret, i;
6023
6024         /* Reset rss size that was stored when reconfiguring rss for
6025          * channel VSIs with non-power-of-2 queue count.
6026          */
6027         vsi->current_rss_size = 0;
6028
6029         /* perform cleanup for channels if they exist */
6030         if (list_empty(&vsi->ch_list))
6031                 return;
6032
6033         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6034                 struct i40e_vsi *p_vsi;
6035
6036                 list_del(&ch->list);
6037                 p_vsi = ch->parent_vsi;
6038                 if (!p_vsi || !ch->initialized) {
6039                         kfree(ch);
6040                         continue;
6041                 }
6042                 /* Reset queue contexts */
6043                 for (i = 0; i < ch->num_queue_pairs; i++) {
6044                         struct i40e_ring *tx_ring, *rx_ring;
6045                         u16 pf_q;
6046
6047                         pf_q = ch->base_queue + i;
6048                         tx_ring = vsi->tx_rings[pf_q];
6049                         tx_ring->ch = NULL;
6050
6051                         rx_ring = vsi->rx_rings[pf_q];
6052                         rx_ring->ch = NULL;
6053                 }
6054
6055                 /* Reset BW configured for this VSI via mqprio */
6056                 ret = i40e_set_bw_limit(vsi, ch->seid, 0);
6057                 if (ret)
6058                         dev_info(&vsi->back->pdev->dev,
6059                                  "Failed to reset tx rate for ch->seid %u\n",
6060                                  ch->seid);
6061
6062                 /* delete cloud filters associated with this channel */
6063                 hlist_for_each_entry_safe(cfilter, node,
6064                                           &pf->cloud_filter_list, cloud_node) {
6065                         if (cfilter->seid != ch->seid)
6066                                 continue;
6067
6068                         hash_del(&cfilter->cloud_node);
6069                         if (cfilter->dst_port)
6070                                 ret = i40e_add_del_cloud_filter_big_buf(vsi,
6071                                                                         cfilter,
6072                                                                         false);
6073                         else
6074                                 ret = i40e_add_del_cloud_filter(vsi, cfilter,
6075                                                                 false);
6076                         last_aq_status = pf->hw.aq.asq_last_status;
6077                         if (ret)
6078                                 dev_info(&pf->pdev->dev,
6079                                          "Failed to delete cloud filter, err %pe aq_err %s\n",
6080                                          ERR_PTR(ret),
6081                                          i40e_aq_str(&pf->hw, last_aq_status));
6082                         kfree(cfilter);
6083                 }
6084
6085                 /* delete VSI from FW */
6086                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6087                                              NULL);
6088                 if (ret)
6089                         dev_err(&vsi->back->pdev->dev,
6090                                 "unable to remove channel (%d) for parent VSI(%d)\n",
6091                                 ch->seid, p_vsi->seid);
6092                 kfree(ch);
6093         }
6094         INIT_LIST_HEAD(&vsi->ch_list);
6095 }
6096
6097 /**
6098  * i40e_get_max_queues_for_channel
6099  * @vsi: ptr to VSI to which channels are associated with
6100  *
6101  * Helper function which returns max value among the queue counts set on the
6102  * channels/TCs created.
6103  **/
6104 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
6105 {
6106         struct i40e_channel *ch, *ch_tmp;
6107         int max = 0;
6108
6109         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
6110                 if (!ch->initialized)
6111                         continue;
6112                 if (ch->num_queue_pairs > max)
6113                         max = ch->num_queue_pairs;
6114         }
6115
6116         return max;
6117 }
6118
6119 /**
6120  * i40e_validate_num_queues - validate num_queues w.r.t channel
6121  * @pf: ptr to PF device
6122  * @num_queues: number of queues
6123  * @vsi: the parent VSI
6124  * @reconfig_rss: indicates should the RSS be reconfigured or not
6125  *
6126  * This function validates number of queues in the context of new channel
6127  * which is being established and determines if RSS should be reconfigured
6128  * or not for parent VSI.
6129  **/
6130 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
6131                                     struct i40e_vsi *vsi, bool *reconfig_rss)
6132 {
6133         int max_ch_queues;
6134
6135         if (!reconfig_rss)
6136                 return -EINVAL;
6137
6138         *reconfig_rss = false;
6139         if (vsi->current_rss_size) {
6140                 if (num_queues > vsi->current_rss_size) {
6141                         dev_dbg(&pf->pdev->dev,
6142                                 "Error: num_queues (%d) > vsi's current_size(%d)\n",
6143                                 num_queues, vsi->current_rss_size);
6144                         return -EINVAL;
6145                 } else if ((num_queues < vsi->current_rss_size) &&
6146                            (!is_power_of_2(num_queues))) {
6147                         dev_dbg(&pf->pdev->dev,
6148                                 "Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
6149                                 num_queues, vsi->current_rss_size);
6150                         return -EINVAL;
6151                 }
6152         }
6153
6154         if (!is_power_of_2(num_queues)) {
6155                 /* Find the max num_queues configured for channel if channel
6156                  * exist.
6157                  * if channel exist, then enforce 'num_queues' to be more than
6158                  * max ever queues configured for channel.
6159                  */
6160                 max_ch_queues = i40e_get_max_queues_for_channel(vsi);
6161                 if (num_queues < max_ch_queues) {
6162                         dev_dbg(&pf->pdev->dev,
6163                                 "Error: num_queues (%d) < max queues configured for channel(%d)\n",
6164                                 num_queues, max_ch_queues);
6165                         return -EINVAL;
6166                 }
6167                 *reconfig_rss = true;
6168         }
6169
6170         return 0;
6171 }
6172
6173 /**
6174  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
6175  * @vsi: the VSI being setup
6176  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
6177  *
6178  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
6179  **/
6180 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6181 {
6182         struct i40e_pf *pf = vsi->back;
6183         u8 seed[I40E_HKEY_ARRAY_SIZE];
6184         struct i40e_hw *hw = &pf->hw;
6185         int local_rss_size;
6186         u8 *lut;
6187         int ret;
6188
6189         if (!vsi->rss_size)
6190                 return -EINVAL;
6191
6192         if (rss_size > vsi->rss_size)
6193                 return -EINVAL;
6194
6195         local_rss_size = min_t(int, vsi->rss_size, rss_size);
6196         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6197         if (!lut)
6198                 return -ENOMEM;
6199
6200         /* Ignoring user configured lut if there is one */
6201         i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6202
6203         /* Use user configured hash key if there is one, otherwise
6204          * use default.
6205          */
6206         if (vsi->rss_hkey_user)
6207                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6208         else
6209                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6210
6211         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6212         if (ret) {
6213                 dev_info(&pf->pdev->dev,
6214                          "Cannot set RSS lut, err %pe aq_err %s\n",
6215                          ERR_PTR(ret),
6216                          i40e_aq_str(hw, hw->aq.asq_last_status));
6217                 kfree(lut);
6218                 return ret;
6219         }
6220         kfree(lut);
6221
6222         /* Do the update w.r.t. storing rss_size */
6223         if (!vsi->orig_rss_size)
6224                 vsi->orig_rss_size = vsi->rss_size;
6225         vsi->current_rss_size = local_rss_size;
6226
6227         return ret;
6228 }
6229
6230 /**
6231  * i40e_channel_setup_queue_map - Setup a channel queue map
6232  * @pf: ptr to PF device
6233  * @ctxt: VSI context structure
6234  * @ch: ptr to channel structure
6235  *
6236  * Setup queue map for a specific channel
6237  **/
6238 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6239                                          struct i40e_vsi_context *ctxt,
6240                                          struct i40e_channel *ch)
6241 {
6242         u16 qcount, qmap, sections = 0;
6243         u8 offset = 0;
6244         int pow;
6245
6246         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6247         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6248
6249         qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6250         ch->num_queue_pairs = qcount;
6251
6252         /* find the next higher power-of-2 of num queue pairs */
6253         pow = ilog2(qcount);
6254         if (!is_power_of_2(qcount))
6255                 pow++;
6256
6257         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6258                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6259
6260         /* Setup queue TC[0].qmap for given VSI context */
6261         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6262
6263         ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6264         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6265         ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6266         ctxt->info.valid_sections |= cpu_to_le16(sections);
6267 }
6268
6269 /**
6270  * i40e_add_channel - add a channel by adding VSI
6271  * @pf: ptr to PF device
6272  * @uplink_seid: underlying HW switching element (VEB) ID
6273  * @ch: ptr to channel structure
6274  *
6275  * Add a channel (VSI) using add_vsi and queue_map
6276  **/
6277 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6278                             struct i40e_channel *ch)
6279 {
6280         struct i40e_hw *hw = &pf->hw;
6281         struct i40e_vsi_context ctxt;
6282         u8 enabled_tc = 0x1; /* TC0 enabled */
6283         int ret;
6284
6285         if (ch->type != I40E_VSI_VMDQ2) {
6286                 dev_info(&pf->pdev->dev,
6287                          "add new vsi failed, ch->type %d\n", ch->type);
6288                 return -EINVAL;
6289         }
6290
6291         memset(&ctxt, 0, sizeof(ctxt));
6292         ctxt.pf_num = hw->pf_id;
6293         ctxt.vf_num = 0;
6294         ctxt.uplink_seid = uplink_seid;
6295         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6296         if (ch->type == I40E_VSI_VMDQ2)
6297                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6298
6299         if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6300                 ctxt.info.valid_sections |=
6301                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6302                 ctxt.info.switch_id =
6303                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6304         }
6305
6306         /* Set queue map for a given VSI context */
6307         i40e_channel_setup_queue_map(pf, &ctxt, ch);
6308
6309         /* Now time to create VSI */
6310         ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6311         if (ret) {
6312                 dev_info(&pf->pdev->dev,
6313                          "add new vsi failed, err %pe aq_err %s\n",
6314                          ERR_PTR(ret),
6315                          i40e_aq_str(&pf->hw,
6316                                      pf->hw.aq.asq_last_status));
6317                 return -ENOENT;
6318         }
6319
6320         /* Success, update channel, set enabled_tc only if the channel
6321          * is not a macvlan
6322          */
6323         ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6324         ch->seid = ctxt.seid;
6325         ch->vsi_number = ctxt.vsi_number;
6326         ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6327
6328         /* copy just the sections touched not the entire info
6329          * since not all sections are valid as returned by
6330          * update vsi params
6331          */
6332         ch->info.mapping_flags = ctxt.info.mapping_flags;
6333         memcpy(&ch->info.queue_mapping,
6334                &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6335         memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6336                sizeof(ctxt.info.tc_mapping));
6337
6338         return 0;
6339 }
6340
6341 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6342                                   u8 *bw_share)
6343 {
6344         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6345         int ret;
6346         int i;
6347
6348         memset(&bw_data, 0, sizeof(bw_data));
6349         bw_data.tc_valid_bits = ch->enabled_tc;
6350         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6351                 bw_data.tc_bw_credits[i] = bw_share[i];
6352
6353         ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6354                                        &bw_data, NULL);
6355         if (ret) {
6356                 dev_info(&vsi->back->pdev->dev,
6357                          "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6358                          vsi->back->hw.aq.asq_last_status, ch->seid);
6359                 return -EINVAL;
6360         }
6361
6362         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6363                 ch->info.qs_handle[i] = bw_data.qs_handles[i];
6364
6365         return 0;
6366 }
6367
6368 /**
6369  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6370  * @pf: ptr to PF device
6371  * @vsi: the VSI being setup
6372  * @ch: ptr to channel structure
6373  *
6374  * Configure TX rings associated with channel (VSI) since queues are being
6375  * from parent VSI.
6376  **/
6377 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6378                                        struct i40e_vsi *vsi,
6379                                        struct i40e_channel *ch)
6380 {
6381         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6382         int ret;
6383         int i;
6384
6385         /* Enable ETS TCs with equal BW Share for now across all VSIs */
6386         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6387                 if (ch->enabled_tc & BIT(i))
6388                         bw_share[i] = 1;
6389         }
6390
6391         /* configure BW for new VSI */
6392         ret = i40e_channel_config_bw(vsi, ch, bw_share);
6393         if (ret) {
6394                 dev_info(&vsi->back->pdev->dev,
6395                          "Failed configuring TC map %d for channel (seid %u)\n",
6396                          ch->enabled_tc, ch->seid);
6397                 return ret;
6398         }
6399
6400         for (i = 0; i < ch->num_queue_pairs; i++) {
6401                 struct i40e_ring *tx_ring, *rx_ring;
6402                 u16 pf_q;
6403
6404                 pf_q = ch->base_queue + i;
6405
6406                 /* Get to TX ring ptr of main VSI, for re-setup TX queue
6407                  * context
6408                  */
6409                 tx_ring = vsi->tx_rings[pf_q];
6410                 tx_ring->ch = ch;
6411
6412                 /* Get the RX ring ptr */
6413                 rx_ring = vsi->rx_rings[pf_q];
6414                 rx_ring->ch = ch;
6415         }
6416
6417         return 0;
6418 }
6419
6420 /**
6421  * i40e_setup_hw_channel - setup new channel
6422  * @pf: ptr to PF device
6423  * @vsi: the VSI being setup
6424  * @ch: ptr to channel structure
6425  * @uplink_seid: underlying HW switching element (VEB) ID
6426  * @type: type of channel to be created (VMDq2/VF)
6427  *
6428  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6429  * and configures TX rings accordingly
6430  **/
6431 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6432                                         struct i40e_vsi *vsi,
6433                                         struct i40e_channel *ch,
6434                                         u16 uplink_seid, u8 type)
6435 {
6436         int ret;
6437
6438         ch->initialized = false;
6439         ch->base_queue = vsi->next_base_queue;
6440         ch->type = type;
6441
6442         /* Proceed with creation of channel (VMDq2) VSI */
6443         ret = i40e_add_channel(pf, uplink_seid, ch);
6444         if (ret) {
6445                 dev_info(&pf->pdev->dev,
6446                          "failed to add_channel using uplink_seid %u\n",
6447                          uplink_seid);
6448                 return ret;
6449         }
6450
6451         /* Mark the successful creation of channel */
6452         ch->initialized = true;
6453
6454         /* Reconfigure TX queues using QTX_CTL register */
6455         ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6456         if (ret) {
6457                 dev_info(&pf->pdev->dev,
6458                          "failed to configure TX rings for channel %u\n",
6459                          ch->seid);
6460                 return ret;
6461         }
6462
6463         /* update 'next_base_queue' */
6464         vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6465         dev_dbg(&pf->pdev->dev,
6466                 "Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6467                 ch->seid, ch->vsi_number, ch->stat_counter_idx,
6468                 ch->num_queue_pairs,
6469                 vsi->next_base_queue);
6470         return ret;
6471 }
6472
6473 /**
6474  * i40e_setup_channel - setup new channel using uplink element
6475  * @pf: ptr to PF device
6476  * @vsi: pointer to the VSI to set up the channel within
6477  * @ch: ptr to channel structure
6478  *
6479  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6480  * and uplink switching element (uplink_seid)
6481  **/
6482 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6483                                struct i40e_channel *ch)
6484 {
6485         u8 vsi_type;
6486         u16 seid;
6487         int ret;
6488
6489         if (vsi->type == I40E_VSI_MAIN) {
6490                 vsi_type = I40E_VSI_VMDQ2;
6491         } else {
6492                 dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6493                         vsi->type);
6494                 return false;
6495         }
6496
6497         /* underlying switching element */
6498         seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6499
6500         /* create channel (VSI), configure TX rings */
6501         ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6502         if (ret) {
6503                 dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6504                 return false;
6505         }
6506
6507         return ch->initialized ? true : false;
6508 }
6509
6510 /**
6511  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6512  * @vsi: ptr to VSI which has PF backing
6513  *
6514  * Sets up switch mode correctly if it needs to be changed and perform
6515  * what are allowed modes.
6516  **/
6517 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6518 {
6519         u8 mode;
6520         struct i40e_pf *pf = vsi->back;
6521         struct i40e_hw *hw = &pf->hw;
6522         int ret;
6523
6524         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6525         if (ret)
6526                 return -EINVAL;
6527
6528         if (hw->dev_caps.switch_mode) {
6529                 /* if switch mode is set, support mode2 (non-tunneled for
6530                  * cloud filter) for now
6531                  */
6532                 u32 switch_mode = hw->dev_caps.switch_mode &
6533                                   I40E_SWITCH_MODE_MASK;
6534                 if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6535                         if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6536                                 return 0;
6537                         dev_err(&pf->pdev->dev,
6538                                 "Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6539                                 hw->dev_caps.switch_mode);
6540                         return -EINVAL;
6541                 }
6542         }
6543
6544         /* Set Bit 7 to be valid */
6545         mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6546
6547         /* Set L4type for TCP support */
6548         mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6549
6550         /* Set cloud filter mode */
6551         mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6552
6553         /* Prep mode field for set_switch_config */
6554         ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6555                                         pf->last_sw_conf_valid_flags,
6556                                         mode, NULL);
6557         if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6558                 dev_err(&pf->pdev->dev,
6559                         "couldn't set switch config bits, err %pe aq_err %s\n",
6560                         ERR_PTR(ret),
6561                         i40e_aq_str(hw,
6562                                     hw->aq.asq_last_status));
6563
6564         return ret;
6565 }
6566
6567 /**
6568  * i40e_create_queue_channel - function to create channel
6569  * @vsi: VSI to be configured
6570  * @ch: ptr to channel (it contains channel specific params)
6571  *
6572  * This function creates channel (VSI) using num_queues specified by user,
6573  * reconfigs RSS if needed.
6574  **/
6575 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6576                               struct i40e_channel *ch)
6577 {
6578         struct i40e_pf *pf = vsi->back;
6579         bool reconfig_rss;
6580         int err;
6581
6582         if (!ch)
6583                 return -EINVAL;
6584
6585         if (!ch->num_queue_pairs) {
6586                 dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6587                         ch->num_queue_pairs);
6588                 return -EINVAL;
6589         }
6590
6591         /* validate user requested num_queues for channel */
6592         err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6593                                        &reconfig_rss);
6594         if (err) {
6595                 dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6596                          ch->num_queue_pairs);
6597                 return -EINVAL;
6598         }
6599
6600         /* By default we are in VEPA mode, if this is the first VF/VMDq
6601          * VSI to be added switch to VEB mode.
6602          */
6603
6604         if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
6605                 set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
6606
6607                 if (vsi->type == I40E_VSI_MAIN) {
6608                         if (i40e_is_tc_mqprio_enabled(pf))
6609                                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6610                         else
6611                                 i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6612                 }
6613                 /* now onwards for main VSI, number of queues will be value
6614                  * of TC0's queue count
6615                  */
6616         }
6617
6618         /* By this time, vsi->cnt_q_avail shall be set to non-zero and
6619          * it should be more than num_queues
6620          */
6621         if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6622                 dev_dbg(&pf->pdev->dev,
6623                         "Error: cnt_q_avail (%u) less than num_queues %d\n",
6624                         vsi->cnt_q_avail, ch->num_queue_pairs);
6625                 return -EINVAL;
6626         }
6627
6628         /* reconfig_rss only if vsi type is MAIN_VSI */
6629         if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6630                 err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6631                 if (err) {
6632                         dev_info(&pf->pdev->dev,
6633                                  "Error: unable to reconfig rss for num_queues (%u)\n",
6634                                  ch->num_queue_pairs);
6635                         return -EINVAL;
6636                 }
6637         }
6638
6639         if (!i40e_setup_channel(pf, vsi, ch)) {
6640                 dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6641                 return -EINVAL;
6642         }
6643
6644         dev_info(&pf->pdev->dev,
6645                  "Setup channel (id:%u) utilizing num_queues %d\n",
6646                  ch->seid, ch->num_queue_pairs);
6647
6648         /* configure VSI for BW limit */
6649         if (ch->max_tx_rate) {
6650                 u64 credits = ch->max_tx_rate;
6651
6652                 if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6653                         return -EINVAL;
6654
6655                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
6656                 dev_dbg(&pf->pdev->dev,
6657                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6658                         ch->max_tx_rate,
6659                         credits,
6660                         ch->seid);
6661         }
6662
6663         /* in case of VF, this will be main SRIOV VSI */
6664         ch->parent_vsi = vsi;
6665
6666         /* and update main_vsi's count for queue_available to use */
6667         vsi->cnt_q_avail -= ch->num_queue_pairs;
6668
6669         return 0;
6670 }
6671
6672 /**
6673  * i40e_configure_queue_channels - Add queue channel for the given TCs
6674  * @vsi: VSI to be configured
6675  *
6676  * Configures queue channel mapping to the given TCs
6677  **/
6678 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6679 {
6680         struct i40e_channel *ch;
6681         u64 max_rate = 0;
6682         int ret = 0, i;
6683
6684         /* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6685         vsi->tc_seid_map[0] = vsi->seid;
6686         for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6687                 if (vsi->tc_config.enabled_tc & BIT(i)) {
6688                         ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6689                         if (!ch) {
6690                                 ret = -ENOMEM;
6691                                 goto err_free;
6692                         }
6693
6694                         INIT_LIST_HEAD(&ch->list);
6695                         ch->num_queue_pairs =
6696                                 vsi->tc_config.tc_info[i].qcount;
6697                         ch->base_queue =
6698                                 vsi->tc_config.tc_info[i].qoffset;
6699
6700                         /* Bandwidth limit through tc interface is in bytes/s,
6701                          * change to Mbit/s
6702                          */
6703                         max_rate = vsi->mqprio_qopt.max_rate[i];
6704                         do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6705                         ch->max_tx_rate = max_rate;
6706
6707                         list_add_tail(&ch->list, &vsi->ch_list);
6708
6709                         ret = i40e_create_queue_channel(vsi, ch);
6710                         if (ret) {
6711                                 dev_err(&vsi->back->pdev->dev,
6712                                         "Failed creating queue channel with TC%d: queues %d\n",
6713                                         i, ch->num_queue_pairs);
6714                                 goto err_free;
6715                         }
6716                         vsi->tc_seid_map[i] = ch->seid;
6717                 }
6718         }
6719
6720         /* reset to reconfigure TX queue contexts */
6721         i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6722         return ret;
6723
6724 err_free:
6725         i40e_remove_queue_channels(vsi);
6726         return ret;
6727 }
6728
6729 /**
6730  * i40e_veb_config_tc - Configure TCs for given VEB
6731  * @veb: given VEB
6732  * @enabled_tc: TC bitmap
6733  *
6734  * Configures given TC bitmap for VEB (switching) element
6735  **/
6736 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6737 {
6738         struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6739         struct i40e_pf *pf = veb->pf;
6740         int ret = 0;
6741         int i;
6742
6743         /* No TCs or already enabled TCs just return */
6744         if (!enabled_tc || veb->enabled_tc == enabled_tc)
6745                 return ret;
6746
6747         bw_data.tc_valid_bits = enabled_tc;
6748         /* bw_data.absolute_credits is not set (relative) */
6749
6750         /* Enable ETS TCs with equal BW Share for now */
6751         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6752                 if (enabled_tc & BIT(i))
6753                         bw_data.tc_bw_share_credits[i] = 1;
6754         }
6755
6756         ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6757                                                    &bw_data, NULL);
6758         if (ret) {
6759                 dev_info(&pf->pdev->dev,
6760                          "VEB bw config failed, err %pe aq_err %s\n",
6761                          ERR_PTR(ret),
6762                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6763                 goto out;
6764         }
6765
6766         /* Update the BW information */
6767         ret = i40e_veb_get_bw_info(veb);
6768         if (ret) {
6769                 dev_info(&pf->pdev->dev,
6770                          "Failed getting veb bw config, err %pe aq_err %s\n",
6771                          ERR_PTR(ret),
6772                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6773         }
6774
6775 out:
6776         return ret;
6777 }
6778
6779 #ifdef CONFIG_I40E_DCB
6780 /**
6781  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6782  * @pf: PF struct
6783  *
6784  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6785  * the caller would've quiesce all the VSIs before calling
6786  * this function
6787  **/
6788 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6789 {
6790         u8 tc_map = 0;
6791         int ret;
6792         u8 v;
6793
6794         /* Enable the TCs available on PF to all VEBs */
6795         tc_map = i40e_pf_get_tc_map(pf);
6796         if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6797                 return;
6798
6799         for (v = 0; v < I40E_MAX_VEB; v++) {
6800                 if (!pf->veb[v])
6801                         continue;
6802                 ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6803                 if (ret) {
6804                         dev_info(&pf->pdev->dev,
6805                                  "Failed configuring TC for VEB seid=%d\n",
6806                                  pf->veb[v]->seid);
6807                         /* Will try to configure as many components */
6808                 }
6809         }
6810
6811         /* Update each VSI */
6812         for (v = 0; v < pf->num_alloc_vsi; v++) {
6813                 if (!pf->vsi[v])
6814                         continue;
6815
6816                 /* - Enable all TCs for the LAN VSI
6817                  * - For all others keep them at TC0 for now
6818                  */
6819                 if (v == pf->lan_vsi)
6820                         tc_map = i40e_pf_get_tc_map(pf);
6821                 else
6822                         tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6823
6824                 ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6825                 if (ret) {
6826                         dev_info(&pf->pdev->dev,
6827                                  "Failed configuring TC for VSI seid=%d\n",
6828                                  pf->vsi[v]->seid);
6829                         /* Will try to configure as many components */
6830                 } else {
6831                         /* Re-configure VSI vectors based on updated TC map */
6832                         i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6833                         if (pf->vsi[v]->netdev)
6834                                 i40e_dcbnl_set_all(pf->vsi[v]);
6835                 }
6836         }
6837 }
6838
6839 /**
6840  * i40e_resume_port_tx - Resume port Tx
6841  * @pf: PF struct
6842  *
6843  * Resume a port's Tx and issue a PF reset in case of failure to
6844  * resume.
6845  **/
6846 static int i40e_resume_port_tx(struct i40e_pf *pf)
6847 {
6848         struct i40e_hw *hw = &pf->hw;
6849         int ret;
6850
6851         ret = i40e_aq_resume_port_tx(hw, NULL);
6852         if (ret) {
6853                 dev_info(&pf->pdev->dev,
6854                          "Resume Port Tx failed, err %pe aq_err %s\n",
6855                           ERR_PTR(ret),
6856                           i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6857                 /* Schedule PF reset to recover */
6858                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6859                 i40e_service_event_schedule(pf);
6860         }
6861
6862         return ret;
6863 }
6864
6865 /**
6866  * i40e_suspend_port_tx - Suspend port Tx
6867  * @pf: PF struct
6868  *
6869  * Suspend a port's Tx and issue a PF reset in case of failure.
6870  **/
6871 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6872 {
6873         struct i40e_hw *hw = &pf->hw;
6874         int ret;
6875
6876         ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6877         if (ret) {
6878                 dev_info(&pf->pdev->dev,
6879                          "Suspend Port Tx failed, err %pe aq_err %s\n",
6880                          ERR_PTR(ret),
6881                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6882                 /* Schedule PF reset to recover */
6883                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6884                 i40e_service_event_schedule(pf);
6885         }
6886
6887         return ret;
6888 }
6889
6890 /**
6891  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6892  * @pf: PF being configured
6893  * @new_cfg: New DCBX configuration
6894  *
6895  * Program DCB settings into HW and reconfigure VEB/VSIs on
6896  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6897  **/
6898 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6899                                   struct i40e_dcbx_config *new_cfg)
6900 {
6901         struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6902         int ret;
6903
6904         /* Check if need reconfiguration */
6905         if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6906                 dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6907                 return 0;
6908         }
6909
6910         /* Config change disable all VSIs */
6911         i40e_pf_quiesce_all_vsi(pf);
6912
6913         /* Copy the new config to the current config */
6914         *old_cfg = *new_cfg;
6915         old_cfg->etsrec = old_cfg->etscfg;
6916         ret = i40e_set_dcb_config(&pf->hw);
6917         if (ret) {
6918                 dev_info(&pf->pdev->dev,
6919                          "Set DCB Config failed, err %pe aq_err %s\n",
6920                          ERR_PTR(ret),
6921                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6922                 goto out;
6923         }
6924
6925         /* Changes in configuration update VEB/VSI */
6926         i40e_dcb_reconfigure(pf);
6927 out:
6928         /* In case of reset do not try to resume anything */
6929         if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6930                 /* Re-start the VSIs if disabled */
6931                 ret = i40e_resume_port_tx(pf);
6932                 /* In case of error no point in resuming VSIs */
6933                 if (ret)
6934                         goto err;
6935                 i40e_pf_unquiesce_all_vsi(pf);
6936         }
6937 err:
6938         return ret;
6939 }
6940
6941 /**
6942  * i40e_hw_dcb_config - Program new DCBX settings into HW
6943  * @pf: PF being configured
6944  * @new_cfg: New DCBX configuration
6945  *
6946  * Program DCB settings into HW and reconfigure VEB/VSIs on
6947  * given PF
6948  **/
6949 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6950 {
6951         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6952         u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6953         u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6954         struct i40e_dcbx_config *old_cfg;
6955         u8 mode[I40E_MAX_TRAFFIC_CLASS];
6956         struct i40e_rx_pb_config pb_cfg;
6957         struct i40e_hw *hw = &pf->hw;
6958         u8 num_ports = hw->num_ports;
6959         bool need_reconfig;
6960         int ret = -EINVAL;
6961         u8 lltc_map = 0;
6962         u8 tc_map = 0;
6963         u8 new_numtc;
6964         u8 i;
6965
6966         dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6967         /* Un-pack information to Program ETS HW via shared API
6968          * numtc, tcmap
6969          * LLTC map
6970          * ETS/NON-ETS arbiter mode
6971          * max exponent (credit refills)
6972          * Total number of ports
6973          * PFC priority bit-map
6974          * Priority Table
6975          * BW % per TC
6976          * Arbiter mode between UPs sharing same TC
6977          * TSA table (ETS or non-ETS)
6978          * EEE enabled or not
6979          * MFS TC table
6980          */
6981
6982         new_numtc = i40e_dcb_get_num_tc(new_cfg);
6983
6984         memset(&ets_data, 0, sizeof(ets_data));
6985         for (i = 0; i < new_numtc; i++) {
6986                 tc_map |= BIT(i);
6987                 switch (new_cfg->etscfg.tsatable[i]) {
6988                 case I40E_IEEE_TSA_ETS:
6989                         prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6990                         ets_data.tc_bw_share_credits[i] =
6991                                         new_cfg->etscfg.tcbwtable[i];
6992                         break;
6993                 case I40E_IEEE_TSA_STRICT:
6994                         prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6995                         lltc_map |= BIT(i);
6996                         ets_data.tc_bw_share_credits[i] =
6997                                         I40E_DCB_STRICT_PRIO_CREDITS;
6998                         break;
6999                 default:
7000                         /* Invalid TSA type */
7001                         need_reconfig = false;
7002                         goto out;
7003                 }
7004         }
7005
7006         old_cfg = &hw->local_dcbx_config;
7007         /* Check if need reconfiguration */
7008         need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
7009
7010         /* If needed, enable/disable frame tagging, disable all VSIs
7011          * and suspend port tx
7012          */
7013         if (need_reconfig) {
7014                 /* Enable DCB tagging only when more than one TC */
7015                 if (new_numtc > 1)
7016                         set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7017                 else
7018                         clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7019
7020                 set_bit(__I40E_PORT_SUSPENDED, pf->state);
7021                 /* Reconfiguration needed quiesce all VSIs */
7022                 i40e_pf_quiesce_all_vsi(pf);
7023                 ret = i40e_suspend_port_tx(pf);
7024                 if (ret)
7025                         goto err;
7026         }
7027
7028         /* Configure Port ETS Tx Scheduler */
7029         ets_data.tc_valid_bits = tc_map;
7030         ets_data.tc_strict_priority_flags = lltc_map;
7031         ret = i40e_aq_config_switch_comp_ets
7032                 (hw, pf->mac_seid, &ets_data,
7033                  i40e_aqc_opc_modify_switching_comp_ets, NULL);
7034         if (ret) {
7035                 dev_info(&pf->pdev->dev,
7036                          "Modify Port ETS failed, err %pe aq_err %s\n",
7037                          ERR_PTR(ret),
7038                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7039                 goto out;
7040         }
7041
7042         /* Configure Rx ETS HW */
7043         memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
7044         i40e_dcb_hw_set_num_tc(hw, new_numtc);
7045         i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
7046                                    I40E_DCB_ARB_MODE_STRICT_PRIORITY,
7047                                    I40E_DCB_DEFAULT_MAX_EXPONENT,
7048                                    lltc_map);
7049         i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
7050         i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
7051                                      prio_type);
7052         i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
7053                                new_cfg->etscfg.prioritytable);
7054         i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
7055
7056         /* Configure Rx Packet Buffers in HW */
7057         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7058                 mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
7059                 mfs_tc[i] += I40E_PACKET_HDR_PAD;
7060         }
7061
7062         i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
7063                                          false, new_cfg->pfc.pfcenable,
7064                                          mfs_tc, &pb_cfg);
7065         i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
7066
7067         /* Update the local Rx Packet buffer config */
7068         pf->pb_cfg = pb_cfg;
7069
7070         /* Inform the FW about changes to DCB configuration */
7071         ret = i40e_aq_dcb_updated(&pf->hw, NULL);
7072         if (ret) {
7073                 dev_info(&pf->pdev->dev,
7074                          "DCB Updated failed, err %pe aq_err %s\n",
7075                          ERR_PTR(ret),
7076                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7077                 goto out;
7078         }
7079
7080         /* Update the port DCBx configuration */
7081         *old_cfg = *new_cfg;
7082
7083         /* Changes in configuration update VEB/VSI */
7084         i40e_dcb_reconfigure(pf);
7085 out:
7086         /* Re-start the VSIs if disabled */
7087         if (need_reconfig) {
7088                 ret = i40e_resume_port_tx(pf);
7089
7090                 clear_bit(__I40E_PORT_SUSPENDED, pf->state);
7091                 /* In case of error no point in resuming VSIs */
7092                 if (ret)
7093                         goto err;
7094
7095                 /* Wait for the PF's queues to be disabled */
7096                 ret = i40e_pf_wait_queues_disabled(pf);
7097                 if (ret) {
7098                         /* Schedule PF reset to recover */
7099                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7100                         i40e_service_event_schedule(pf);
7101                         goto err;
7102                 } else {
7103                         i40e_pf_unquiesce_all_vsi(pf);
7104                         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7105                         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
7106                 }
7107                 /* registers are set, lets apply */
7108                 if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps))
7109                         ret = i40e_hw_set_dcb_config(pf, new_cfg);
7110         }
7111
7112 err:
7113         return ret;
7114 }
7115
7116 /**
7117  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
7118  * @pf: PF being queried
7119  *
7120  * Set default DCB configuration in case DCB is to be done in SW.
7121  **/
7122 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
7123 {
7124         struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
7125         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
7126         struct i40e_hw *hw = &pf->hw;
7127         int err;
7128
7129         if (test_bit(I40E_HW_CAP_USE_SET_LLDP_MIB, pf->hw.caps)) {
7130                 /* Update the local cached instance with TC0 ETS */
7131                 memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
7132                 pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7133                 pf->tmp_cfg.etscfg.maxtcs = 0;
7134                 pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7135                 pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
7136                 pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
7137                 pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
7138                 /* FW needs one App to configure HW */
7139                 pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
7140                 pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
7141                 pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
7142                 pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
7143
7144                 return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
7145         }
7146
7147         memset(&ets_data, 0, sizeof(ets_data));
7148         ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
7149         ets_data.tc_strict_priority_flags = 0; /* ETS */
7150         ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
7151
7152         /* Enable ETS on the Physical port */
7153         err = i40e_aq_config_switch_comp_ets
7154                 (hw, pf->mac_seid, &ets_data,
7155                  i40e_aqc_opc_enable_switching_comp_ets, NULL);
7156         if (err) {
7157                 dev_info(&pf->pdev->dev,
7158                          "Enable Port ETS failed, err %pe aq_err %s\n",
7159                          ERR_PTR(err),
7160                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7161                 err = -ENOENT;
7162                 goto out;
7163         }
7164
7165         /* Update the local cached instance with TC0 ETS */
7166         dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
7167         dcb_cfg->etscfg.cbs = 0;
7168         dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
7169         dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
7170
7171 out:
7172         return err;
7173 }
7174
7175 /**
7176  * i40e_init_pf_dcb - Initialize DCB configuration
7177  * @pf: PF being configured
7178  *
7179  * Query the current DCB configuration and cache it
7180  * in the hardware structure
7181  **/
7182 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7183 {
7184         struct i40e_hw *hw = &pf->hw;
7185         int err;
7186
7187         /* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7188          * Also do not enable DCBx if FW LLDP agent is disabled
7189          */
7190         if (test_bit(I40E_HW_CAP_NO_DCB_SUPPORT, pf->hw.caps)) {
7191                 dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7192                 err = -EOPNOTSUPP;
7193                 goto out;
7194         }
7195         if (test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) {
7196                 dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7197                 err = i40e_dcb_sw_default_config(pf);
7198                 if (err) {
7199                         dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7200                         goto out;
7201                 }
7202                 dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7203                 pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7204                                DCB_CAP_DCBX_VER_IEEE;
7205                 /* at init capable but disabled */
7206                 set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7207                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7208                 goto out;
7209         }
7210         err = i40e_init_dcb(hw, true);
7211         if (!err) {
7212                 /* Device/Function is not DCBX capable */
7213                 if ((!hw->func_caps.dcb) ||
7214                     (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7215                         dev_info(&pf->pdev->dev,
7216                                  "DCBX offload is not supported or is disabled for this PF.\n");
7217                 } else {
7218                         /* When status is not DISABLED then DCBX in FW */
7219                         pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7220                                        DCB_CAP_DCBX_VER_IEEE;
7221
7222                         set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
7223                         /* Enable DCB tagging only when more than one TC
7224                          * or explicitly disable if only one TC
7225                          */
7226                         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7227                                 set_bit(I40E_FLAG_DCB_ENA, pf->flags);
7228                         else
7229                                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
7230                         dev_dbg(&pf->pdev->dev,
7231                                 "DCBX offload is supported for this PF.\n");
7232                 }
7233         } else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7234                 dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7235                 set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags);
7236         } else {
7237                 dev_info(&pf->pdev->dev,
7238                          "Query for DCB configuration failed, err %pe aq_err %s\n",
7239                          ERR_PTR(err),
7240                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7241         }
7242
7243 out:
7244         return err;
7245 }
7246 #endif /* CONFIG_I40E_DCB */
7247
7248 /**
7249  * i40e_print_link_message - print link up or down
7250  * @vsi: the VSI for which link needs a message
7251  * @isup: true of link is up, false otherwise
7252  */
7253 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7254 {
7255         enum i40e_aq_link_speed new_speed;
7256         struct i40e_pf *pf = vsi->back;
7257         char *speed = "Unknown";
7258         char *fc = "Unknown";
7259         char *fec = "";
7260         char *req_fec = "";
7261         char *an = "";
7262
7263         if (isup)
7264                 new_speed = pf->hw.phy.link_info.link_speed;
7265         else
7266                 new_speed = I40E_LINK_SPEED_UNKNOWN;
7267
7268         if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7269                 return;
7270         vsi->current_isup = isup;
7271         vsi->current_speed = new_speed;
7272         if (!isup) {
7273                 netdev_info(vsi->netdev, "NIC Link is Down\n");
7274                 return;
7275         }
7276
7277         /* Warn user if link speed on NPAR enabled partition is not at
7278          * least 10GB
7279          */
7280         if (pf->hw.func_caps.npar_enable &&
7281             (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7282              pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7283                 netdev_warn(vsi->netdev,
7284                             "The partition detected link speed that is less than 10Gbps\n");
7285
7286         switch (pf->hw.phy.link_info.link_speed) {
7287         case I40E_LINK_SPEED_40GB:
7288                 speed = "40 G";
7289                 break;
7290         case I40E_LINK_SPEED_20GB:
7291                 speed = "20 G";
7292                 break;
7293         case I40E_LINK_SPEED_25GB:
7294                 speed = "25 G";
7295                 break;
7296         case I40E_LINK_SPEED_10GB:
7297                 speed = "10 G";
7298                 break;
7299         case I40E_LINK_SPEED_5GB:
7300                 speed = "5 G";
7301                 break;
7302         case I40E_LINK_SPEED_2_5GB:
7303                 speed = "2.5 G";
7304                 break;
7305         case I40E_LINK_SPEED_1GB:
7306                 speed = "1000 M";
7307                 break;
7308         case I40E_LINK_SPEED_100MB:
7309                 speed = "100 M";
7310                 break;
7311         default:
7312                 break;
7313         }
7314
7315         switch (pf->hw.fc.current_mode) {
7316         case I40E_FC_FULL:
7317                 fc = "RX/TX";
7318                 break;
7319         case I40E_FC_TX_PAUSE:
7320                 fc = "TX";
7321                 break;
7322         case I40E_FC_RX_PAUSE:
7323                 fc = "RX";
7324                 break;
7325         default:
7326                 fc = "None";
7327                 break;
7328         }
7329
7330         if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7331                 req_fec = "None";
7332                 fec = "None";
7333                 an = "False";
7334
7335                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7336                         an = "True";
7337
7338                 if (pf->hw.phy.link_info.fec_info &
7339                     I40E_AQ_CONFIG_FEC_KR_ENA)
7340                         fec = "CL74 FC-FEC/BASE-R";
7341                 else if (pf->hw.phy.link_info.fec_info &
7342                          I40E_AQ_CONFIG_FEC_RS_ENA)
7343                         fec = "CL108 RS-FEC";
7344
7345                 /* 'CL108 RS-FEC' should be displayed when RS is requested, or
7346                  * both RS and FC are requested
7347                  */
7348                 if (vsi->back->hw.phy.link_info.req_fec_info &
7349                     (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7350                         if (vsi->back->hw.phy.link_info.req_fec_info &
7351                             I40E_AQ_REQUEST_FEC_RS)
7352                                 req_fec = "CL108 RS-FEC";
7353                         else
7354                                 req_fec = "CL74 FC-FEC/BASE-R";
7355                 }
7356                 netdev_info(vsi->netdev,
7357                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7358                             speed, req_fec, fec, an, fc);
7359         } else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7360                 req_fec = "None";
7361                 fec = "None";
7362                 an = "False";
7363
7364                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7365                         an = "True";
7366
7367                 if (pf->hw.phy.link_info.fec_info &
7368                     I40E_AQ_CONFIG_FEC_KR_ENA)
7369                         fec = "CL74 FC-FEC/BASE-R";
7370
7371                 if (pf->hw.phy.link_info.req_fec_info &
7372                     I40E_AQ_REQUEST_FEC_KR)
7373                         req_fec = "CL74 FC-FEC/BASE-R";
7374
7375                 netdev_info(vsi->netdev,
7376                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7377                             speed, req_fec, fec, an, fc);
7378         } else {
7379                 netdev_info(vsi->netdev,
7380                             "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7381                             speed, fc);
7382         }
7383
7384 }
7385
7386 /**
7387  * i40e_up_complete - Finish the last steps of bringing up a connection
7388  * @vsi: the VSI being configured
7389  **/
7390 static int i40e_up_complete(struct i40e_vsi *vsi)
7391 {
7392         struct i40e_pf *pf = vsi->back;
7393         int err;
7394
7395         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
7396                 i40e_vsi_configure_msix(vsi);
7397         else
7398                 i40e_configure_msi_and_legacy(vsi);
7399
7400         /* start rings */
7401         err = i40e_vsi_start_rings(vsi);
7402         if (err)
7403                 return err;
7404
7405         clear_bit(__I40E_VSI_DOWN, vsi->state);
7406         i40e_napi_enable_all(vsi);
7407         i40e_vsi_enable_irq(vsi);
7408
7409         if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7410             (vsi->netdev)) {
7411                 i40e_print_link_message(vsi, true);
7412                 netif_tx_start_all_queues(vsi->netdev);
7413                 netif_carrier_on(vsi->netdev);
7414         }
7415
7416         /* replay FDIR SB filters */
7417         if (vsi->type == I40E_VSI_FDIR) {
7418                 /* reset fd counters */
7419                 pf->fd_add_err = 0;
7420                 pf->fd_atr_cnt = 0;
7421                 i40e_fdir_filter_restore(vsi);
7422         }
7423
7424         /* On the next run of the service_task, notify any clients of the new
7425          * opened netdev
7426          */
7427         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7428         i40e_service_event_schedule(pf);
7429
7430         return 0;
7431 }
7432
7433 /**
7434  * i40e_vsi_reinit_locked - Reset the VSI
7435  * @vsi: the VSI being configured
7436  *
7437  * Rebuild the ring structs after some configuration
7438  * has changed, e.g. MTU size.
7439  **/
7440 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7441 {
7442         struct i40e_pf *pf = vsi->back;
7443
7444         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7445                 usleep_range(1000, 2000);
7446         i40e_down(vsi);
7447
7448         i40e_up(vsi);
7449         clear_bit(__I40E_CONFIG_BUSY, pf->state);
7450 }
7451
7452 /**
7453  * i40e_force_link_state - Force the link status
7454  * @pf: board private structure
7455  * @is_up: whether the link state should be forced up or down
7456  **/
7457 static int i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7458 {
7459         struct i40e_aq_get_phy_abilities_resp abilities;
7460         struct i40e_aq_set_phy_config config = {0};
7461         bool non_zero_phy_type = is_up;
7462         struct i40e_hw *hw = &pf->hw;
7463         u64 mask;
7464         u8 speed;
7465         int err;
7466
7467         /* Card might've been put in an unstable state by other drivers
7468          * and applications, which causes incorrect speed values being
7469          * set on startup. In order to clear speed registers, we call
7470          * get_phy_capabilities twice, once to get initial state of
7471          * available speeds, and once to get current PHY config.
7472          */
7473         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7474                                            NULL);
7475         if (err) {
7476                 dev_err(&pf->pdev->dev,
7477                         "failed to get phy cap., ret =  %pe last_status =  %s\n",
7478                         ERR_PTR(err),
7479                         i40e_aq_str(hw, hw->aq.asq_last_status));
7480                 return err;
7481         }
7482         speed = abilities.link_speed;
7483
7484         /* Get the current phy config */
7485         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7486                                            NULL);
7487         if (err) {
7488                 dev_err(&pf->pdev->dev,
7489                         "failed to get phy cap., ret =  %pe last_status =  %s\n",
7490                         ERR_PTR(err),
7491                         i40e_aq_str(hw, hw->aq.asq_last_status));
7492                 return err;
7493         }
7494
7495         /* If link needs to go up, but was not forced to go down,
7496          * and its speed values are OK, no need for a flap
7497          * if non_zero_phy_type was set, still need to force up
7498          */
7499         if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags))
7500                 non_zero_phy_type = true;
7501         else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7502                 return 0;
7503
7504         /* To force link we need to set bits for all supported PHY types,
7505          * but there are now more than 32, so we need to split the bitmap
7506          * across two fields.
7507          */
7508         mask = I40E_PHY_TYPES_BITMASK;
7509         config.phy_type =
7510                 non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7511         config.phy_type_ext =
7512                 non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7513         /* Copy the old settings, except of phy_type */
7514         config.abilities = abilities.abilities;
7515         if (test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags)) {
7516                 if (is_up)
7517                         config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7518                 else
7519                         config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7520         }
7521         if (abilities.link_speed != 0)
7522                 config.link_speed = abilities.link_speed;
7523         else
7524                 config.link_speed = speed;
7525         config.eee_capability = abilities.eee_capability;
7526         config.eeer = abilities.eeer_val;
7527         config.low_power_ctrl = abilities.d3_lpan;
7528         config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7529                             I40E_AQ_PHY_FEC_CONFIG_MASK;
7530         err = i40e_aq_set_phy_config(hw, &config, NULL);
7531
7532         if (err) {
7533                 dev_err(&pf->pdev->dev,
7534                         "set phy config ret =  %pe last_status =  %s\n",
7535                         ERR_PTR(err),
7536                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7537                 return err;
7538         }
7539
7540         /* Update the link info */
7541         err = i40e_update_link_info(hw);
7542         if (err) {
7543                 /* Wait a little bit (on 40G cards it sometimes takes a really
7544                  * long time for link to come back from the atomic reset)
7545                  * and try once more
7546                  */
7547                 msleep(1000);
7548                 i40e_update_link_info(hw);
7549         }
7550
7551         i40e_aq_set_link_restart_an(hw, is_up, NULL);
7552
7553         return 0;
7554 }
7555
7556 /**
7557  * i40e_up - Bring the connection back up after being down
7558  * @vsi: the VSI being configured
7559  **/
7560 int i40e_up(struct i40e_vsi *vsi)
7561 {
7562         int err;
7563
7564         if (vsi->type == I40E_VSI_MAIN &&
7565             (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7566              test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7567                 i40e_force_link_state(vsi->back, true);
7568
7569         err = i40e_vsi_configure(vsi);
7570         if (!err)
7571                 err = i40e_up_complete(vsi);
7572
7573         return err;
7574 }
7575
7576 /**
7577  * i40e_down - Shutdown the connection processing
7578  * @vsi: the VSI being stopped
7579  **/
7580 void i40e_down(struct i40e_vsi *vsi)
7581 {
7582         int i;
7583
7584         /* It is assumed that the caller of this function
7585          * sets the vsi->state __I40E_VSI_DOWN bit.
7586          */
7587         if (vsi->netdev) {
7588                 netif_carrier_off(vsi->netdev);
7589                 netif_tx_disable(vsi->netdev);
7590         }
7591         i40e_vsi_disable_irq(vsi);
7592         i40e_vsi_stop_rings(vsi);
7593         if (vsi->type == I40E_VSI_MAIN &&
7594            (test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, vsi->back->flags) ||
7595             test_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, vsi->back->flags)))
7596                 i40e_force_link_state(vsi->back, false);
7597         i40e_napi_disable_all(vsi);
7598
7599         for (i = 0; i < vsi->num_queue_pairs; i++) {
7600                 i40e_clean_tx_ring(vsi->tx_rings[i]);
7601                 if (i40e_enabled_xdp_vsi(vsi)) {
7602                         /* Make sure that in-progress ndo_xdp_xmit and
7603                          * ndo_xsk_wakeup calls are completed.
7604                          */
7605                         synchronize_rcu();
7606                         i40e_clean_tx_ring(vsi->xdp_rings[i]);
7607                 }
7608                 i40e_clean_rx_ring(vsi->rx_rings[i]);
7609         }
7610
7611 }
7612
7613 /**
7614  * i40e_validate_mqprio_qopt- validate queue mapping info
7615  * @vsi: the VSI being configured
7616  * @mqprio_qopt: queue parametrs
7617  **/
7618 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7619                                      struct tc_mqprio_qopt_offload *mqprio_qopt)
7620 {
7621         u64 sum_max_rate = 0;
7622         u64 max_rate = 0;
7623         int i;
7624
7625         if (mqprio_qopt->qopt.offset[0] != 0 ||
7626             mqprio_qopt->qopt.num_tc < 1 ||
7627             mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7628                 return -EINVAL;
7629         for (i = 0; ; i++) {
7630                 if (!mqprio_qopt->qopt.count[i])
7631                         return -EINVAL;
7632                 if (mqprio_qopt->min_rate[i]) {
7633                         dev_err(&vsi->back->pdev->dev,
7634                                 "Invalid min tx rate (greater than 0) specified\n");
7635                         return -EINVAL;
7636                 }
7637                 max_rate = mqprio_qopt->max_rate[i];
7638                 do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7639                 sum_max_rate += max_rate;
7640
7641                 if (i >= mqprio_qopt->qopt.num_tc - 1)
7642                         break;
7643                 if (mqprio_qopt->qopt.offset[i + 1] !=
7644                     (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7645                         return -EINVAL;
7646         }
7647         if (vsi->num_queue_pairs <
7648             (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7649                 dev_err(&vsi->back->pdev->dev,
7650                         "Failed to create traffic channel, insufficient number of queues.\n");
7651                 return -EINVAL;
7652         }
7653         if (sum_max_rate > i40e_get_link_speed(vsi)) {
7654                 dev_err(&vsi->back->pdev->dev,
7655                         "Invalid max tx rate specified\n");
7656                 return -EINVAL;
7657         }
7658         return 0;
7659 }
7660
7661 /**
7662  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7663  * @vsi: the VSI being configured
7664  **/
7665 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7666 {
7667         u16 qcount;
7668         int i;
7669
7670         /* Only TC0 is enabled */
7671         vsi->tc_config.numtc = 1;
7672         vsi->tc_config.enabled_tc = 1;
7673         qcount = min_t(int, vsi->alloc_queue_pairs,
7674                        i40e_pf_get_max_q_per_tc(vsi->back));
7675         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7676                 /* For the TC that is not enabled set the offset to default
7677                  * queue and allocate one queue for the given TC.
7678                  */
7679                 vsi->tc_config.tc_info[i].qoffset = 0;
7680                 if (i == 0)
7681                         vsi->tc_config.tc_info[i].qcount = qcount;
7682                 else
7683                         vsi->tc_config.tc_info[i].qcount = 1;
7684                 vsi->tc_config.tc_info[i].netdev_tc = 0;
7685         }
7686 }
7687
7688 /**
7689  * i40e_del_macvlan_filter
7690  * @hw: pointer to the HW structure
7691  * @seid: seid of the channel VSI
7692  * @macaddr: the mac address to apply as a filter
7693  * @aq_err: store the admin Q error
7694  *
7695  * This function deletes a mac filter on the channel VSI which serves as the
7696  * macvlan. Returns 0 on success.
7697  **/
7698 static int i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7699                                    const u8 *macaddr, int *aq_err)
7700 {
7701         struct i40e_aqc_remove_macvlan_element_data element;
7702         int status;
7703
7704         memset(&element, 0, sizeof(element));
7705         ether_addr_copy(element.mac_addr, macaddr);
7706         element.vlan_tag = 0;
7707         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7708         status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7709         *aq_err = hw->aq.asq_last_status;
7710
7711         return status;
7712 }
7713
7714 /**
7715  * i40e_add_macvlan_filter
7716  * @hw: pointer to the HW structure
7717  * @seid: seid of the channel VSI
7718  * @macaddr: the mac address to apply as a filter
7719  * @aq_err: store the admin Q error
7720  *
7721  * This function adds a mac filter on the channel VSI which serves as the
7722  * macvlan. Returns 0 on success.
7723  **/
7724 static int i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7725                                    const u8 *macaddr, int *aq_err)
7726 {
7727         struct i40e_aqc_add_macvlan_element_data element;
7728         u16 cmd_flags = 0;
7729         int status;
7730
7731         ether_addr_copy(element.mac_addr, macaddr);
7732         element.vlan_tag = 0;
7733         element.queue_number = 0;
7734         element.match_method = I40E_AQC_MM_ERR_NO_RES;
7735         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7736         element.flags = cpu_to_le16(cmd_flags);
7737         status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7738         *aq_err = hw->aq.asq_last_status;
7739
7740         return status;
7741 }
7742
7743 /**
7744  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7745  * @vsi: the VSI we want to access
7746  * @ch: the channel we want to access
7747  */
7748 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7749 {
7750         struct i40e_ring *tx_ring, *rx_ring;
7751         u16 pf_q;
7752         int i;
7753
7754         for (i = 0; i < ch->num_queue_pairs; i++) {
7755                 pf_q = ch->base_queue + i;
7756                 tx_ring = vsi->tx_rings[pf_q];
7757                 tx_ring->ch = NULL;
7758                 rx_ring = vsi->rx_rings[pf_q];
7759                 rx_ring->ch = NULL;
7760         }
7761 }
7762
7763 /**
7764  * i40e_free_macvlan_channels
7765  * @vsi: the VSI we want to access
7766  *
7767  * This function frees the Qs of the channel VSI from
7768  * the stack and also deletes the channel VSIs which
7769  * serve as macvlans.
7770  */
7771 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7772 {
7773         struct i40e_channel *ch, *ch_tmp;
7774         int ret;
7775
7776         if (list_empty(&vsi->macvlan_list))
7777                 return;
7778
7779         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7780                 struct i40e_vsi *parent_vsi;
7781
7782                 if (i40e_is_channel_macvlan(ch)) {
7783                         i40e_reset_ch_rings(vsi, ch);
7784                         clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7785                         netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7786                         netdev_set_sb_channel(ch->fwd->netdev, 0);
7787                         kfree(ch->fwd);
7788                         ch->fwd = NULL;
7789                 }
7790
7791                 list_del(&ch->list);
7792                 parent_vsi = ch->parent_vsi;
7793                 if (!parent_vsi || !ch->initialized) {
7794                         kfree(ch);
7795                         continue;
7796                 }
7797
7798                 /* remove the VSI */
7799                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7800                                              NULL);
7801                 if (ret)
7802                         dev_err(&vsi->back->pdev->dev,
7803                                 "unable to remove channel (%d) for parent VSI(%d)\n",
7804                                 ch->seid, parent_vsi->seid);
7805                 kfree(ch);
7806         }
7807         vsi->macvlan_cnt = 0;
7808 }
7809
7810 /**
7811  * i40e_fwd_ring_up - bring the macvlan device up
7812  * @vsi: the VSI we want to access
7813  * @vdev: macvlan netdevice
7814  * @fwd: the private fwd structure
7815  */
7816 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7817                             struct i40e_fwd_adapter *fwd)
7818 {
7819         struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7820         int ret = 0, num_tc = 1,  i, aq_err;
7821         struct i40e_pf *pf = vsi->back;
7822         struct i40e_hw *hw = &pf->hw;
7823
7824         /* Go through the list and find an available channel */
7825         list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7826                 if (!i40e_is_channel_macvlan(iter)) {
7827                         iter->fwd = fwd;
7828                         /* record configuration for macvlan interface in vdev */
7829                         for (i = 0; i < num_tc; i++)
7830                                 netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7831                                                              i,
7832                                                              iter->num_queue_pairs,
7833                                                              iter->base_queue);
7834                         for (i = 0; i < iter->num_queue_pairs; i++) {
7835                                 struct i40e_ring *tx_ring, *rx_ring;
7836                                 u16 pf_q;
7837
7838                                 pf_q = iter->base_queue + i;
7839
7840                                 /* Get to TX ring ptr */
7841                                 tx_ring = vsi->tx_rings[pf_q];
7842                                 tx_ring->ch = iter;
7843
7844                                 /* Get the RX ring ptr */
7845                                 rx_ring = vsi->rx_rings[pf_q];
7846                                 rx_ring->ch = iter;
7847                         }
7848                         ch = iter;
7849                         break;
7850                 }
7851         }
7852
7853         if (!ch)
7854                 return -EINVAL;
7855
7856         /* Guarantee all rings are updated before we update the
7857          * MAC address filter.
7858          */
7859         wmb();
7860
7861         /* Add a mac filter */
7862         ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7863         if (ret) {
7864                 /* if we cannot add the MAC rule then disable the offload */
7865                 macvlan_release_l2fw_offload(vdev);
7866                 for (i = 0; i < ch->num_queue_pairs; i++) {
7867                         struct i40e_ring *rx_ring;
7868                         u16 pf_q;
7869
7870                         pf_q = ch->base_queue + i;
7871                         rx_ring = vsi->rx_rings[pf_q];
7872                         rx_ring->netdev = NULL;
7873                 }
7874                 dev_info(&pf->pdev->dev,
7875                          "Error adding mac filter on macvlan err %pe, aq_err %s\n",
7876                           ERR_PTR(ret),
7877                           i40e_aq_str(hw, aq_err));
7878                 netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7879         }
7880
7881         return ret;
7882 }
7883
7884 /**
7885  * i40e_setup_macvlans - create the channels which will be macvlans
7886  * @vsi: the VSI we want to access
7887  * @macvlan_cnt: no. of macvlans to be setup
7888  * @qcnt: no. of Qs per macvlan
7889  * @vdev: macvlan netdevice
7890  */
7891 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7892                                struct net_device *vdev)
7893 {
7894         struct i40e_pf *pf = vsi->back;
7895         struct i40e_hw *hw = &pf->hw;
7896         struct i40e_vsi_context ctxt;
7897         u16 sections, qmap, num_qps;
7898         struct i40e_channel *ch;
7899         int i, pow, ret = 0;
7900         u8 offset = 0;
7901
7902         if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7903                 return -EINVAL;
7904
7905         num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7906
7907         /* find the next higher power-of-2 of num queue pairs */
7908         pow = fls(roundup_pow_of_two(num_qps) - 1);
7909
7910         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7911                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7912
7913         /* Setup context bits for the main VSI */
7914         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7915         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7916         memset(&ctxt, 0, sizeof(ctxt));
7917         ctxt.seid = vsi->seid;
7918         ctxt.pf_num = vsi->back->hw.pf_id;
7919         ctxt.vf_num = 0;
7920         ctxt.uplink_seid = vsi->uplink_seid;
7921         ctxt.info = vsi->info;
7922         ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7923         ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7924         ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7925         ctxt.info.valid_sections |= cpu_to_le16(sections);
7926
7927         /* Reconfigure RSS for main VSI with new max queue count */
7928         vsi->rss_size = max_t(u16, num_qps, qcnt);
7929         ret = i40e_vsi_config_rss(vsi);
7930         if (ret) {
7931                 dev_info(&pf->pdev->dev,
7932                          "Failed to reconfig RSS for num_queues (%u)\n",
7933                          vsi->rss_size);
7934                 return ret;
7935         }
7936         vsi->reconfig_rss = true;
7937         dev_dbg(&vsi->back->pdev->dev,
7938                 "Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7939         vsi->next_base_queue = num_qps;
7940         vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7941
7942         /* Update the VSI after updating the VSI queue-mapping
7943          * information
7944          */
7945         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7946         if (ret) {
7947                 dev_info(&pf->pdev->dev,
7948                          "Update vsi tc config failed, err %pe aq_err %s\n",
7949                          ERR_PTR(ret),
7950                          i40e_aq_str(hw, hw->aq.asq_last_status));
7951                 return ret;
7952         }
7953         /* update the local VSI info with updated queue map */
7954         i40e_vsi_update_queue_map(vsi, &ctxt);
7955         vsi->info.valid_sections = 0;
7956
7957         /* Create channels for macvlans */
7958         INIT_LIST_HEAD(&vsi->macvlan_list);
7959         for (i = 0; i < macvlan_cnt; i++) {
7960                 ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7961                 if (!ch) {
7962                         ret = -ENOMEM;
7963                         goto err_free;
7964                 }
7965                 INIT_LIST_HEAD(&ch->list);
7966                 ch->num_queue_pairs = qcnt;
7967                 if (!i40e_setup_channel(pf, vsi, ch)) {
7968                         ret = -EINVAL;
7969                         kfree(ch);
7970                         goto err_free;
7971                 }
7972                 ch->parent_vsi = vsi;
7973                 vsi->cnt_q_avail -= ch->num_queue_pairs;
7974                 vsi->macvlan_cnt++;
7975                 list_add_tail(&ch->list, &vsi->macvlan_list);
7976         }
7977
7978         return ret;
7979
7980 err_free:
7981         dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7982         i40e_free_macvlan_channels(vsi);
7983
7984         return ret;
7985 }
7986
7987 /**
7988  * i40e_fwd_add - configure macvlans
7989  * @netdev: net device to configure
7990  * @vdev: macvlan netdevice
7991  **/
7992 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7993 {
7994         struct i40e_netdev_priv *np = netdev_priv(netdev);
7995         u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7996         struct i40e_vsi *vsi = np->vsi;
7997         struct i40e_pf *pf = vsi->back;
7998         struct i40e_fwd_adapter *fwd;
7999         int avail_macvlan, ret;
8000
8001         if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8002                 netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
8003                 return ERR_PTR(-EINVAL);
8004         }
8005         if (i40e_is_tc_mqprio_enabled(pf)) {
8006                 netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
8007                 return ERR_PTR(-EINVAL);
8008         }
8009         if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
8010                 netdev_info(netdev, "Not enough vectors available to support macvlans\n");
8011                 return ERR_PTR(-EINVAL);
8012         }
8013
8014         /* The macvlan device has to be a single Q device so that the
8015          * tc_to_txq field can be reused to pick the tx queue.
8016          */
8017         if (netif_is_multiqueue(vdev))
8018                 return ERR_PTR(-ERANGE);
8019
8020         if (!vsi->macvlan_cnt) {
8021                 /* reserve bit 0 for the pf device */
8022                 set_bit(0, vsi->fwd_bitmask);
8023
8024                 /* Try to reserve as many queues as possible for macvlans. First
8025                  * reserve 3/4th of max vectors, then half, then quarter and
8026                  * calculate Qs per macvlan as you go
8027                  */
8028                 vectors = pf->num_lan_msix;
8029                 if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
8030                         /* allocate 4 Qs per macvlan and 32 Qs to the PF*/
8031                         q_per_macvlan = 4;
8032                         macvlan_cnt = (vectors - 32) / 4;
8033                 } else if (vectors <= 64 && vectors > 32) {
8034                         /* allocate 2 Qs per macvlan and 16 Qs to the PF*/
8035                         q_per_macvlan = 2;
8036                         macvlan_cnt = (vectors - 16) / 2;
8037                 } else if (vectors <= 32 && vectors > 16) {
8038                         /* allocate 1 Q per macvlan and 16 Qs to the PF*/
8039                         q_per_macvlan = 1;
8040                         macvlan_cnt = vectors - 16;
8041                 } else if (vectors <= 16 && vectors > 8) {
8042                         /* allocate 1 Q per macvlan and 8 Qs to the PF */
8043                         q_per_macvlan = 1;
8044                         macvlan_cnt = vectors - 8;
8045                 } else {
8046                         /* allocate 1 Q per macvlan and 1 Q to the PF */
8047                         q_per_macvlan = 1;
8048                         macvlan_cnt = vectors - 1;
8049                 }
8050
8051                 if (macvlan_cnt == 0)
8052                         return ERR_PTR(-EBUSY);
8053
8054                 /* Quiesce VSI queues */
8055                 i40e_quiesce_vsi(vsi);
8056
8057                 /* sets up the macvlans but does not "enable" them */
8058                 ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
8059                                           vdev);
8060                 if (ret)
8061                         return ERR_PTR(ret);
8062
8063                 /* Unquiesce VSI */
8064                 i40e_unquiesce_vsi(vsi);
8065         }
8066         avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
8067                                             vsi->macvlan_cnt);
8068         if (avail_macvlan >= I40E_MAX_MACVLANS)
8069                 return ERR_PTR(-EBUSY);
8070
8071         /* create the fwd struct */
8072         fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
8073         if (!fwd)
8074                 return ERR_PTR(-ENOMEM);
8075
8076         set_bit(avail_macvlan, vsi->fwd_bitmask);
8077         fwd->bit_no = avail_macvlan;
8078         netdev_set_sb_channel(vdev, avail_macvlan);
8079         fwd->netdev = vdev;
8080
8081         if (!netif_running(netdev))
8082                 return fwd;
8083
8084         /* Set fwd ring up */
8085         ret = i40e_fwd_ring_up(vsi, vdev, fwd);
8086         if (ret) {
8087                 /* unbind the queues and drop the subordinate channel config */
8088                 netdev_unbind_sb_channel(netdev, vdev);
8089                 netdev_set_sb_channel(vdev, 0);
8090
8091                 kfree(fwd);
8092                 return ERR_PTR(-EINVAL);
8093         }
8094
8095         return fwd;
8096 }
8097
8098 /**
8099  * i40e_del_all_macvlans - Delete all the mac filters on the channels
8100  * @vsi: the VSI we want to access
8101  */
8102 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
8103 {
8104         struct i40e_channel *ch, *ch_tmp;
8105         struct i40e_pf *pf = vsi->back;
8106         struct i40e_hw *hw = &pf->hw;
8107         int aq_err, ret = 0;
8108
8109         if (list_empty(&vsi->macvlan_list))
8110                 return;
8111
8112         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8113                 if (i40e_is_channel_macvlan(ch)) {
8114                         ret = i40e_del_macvlan_filter(hw, ch->seid,
8115                                                       i40e_channel_mac(ch),
8116                                                       &aq_err);
8117                         if (!ret) {
8118                                 /* Reset queue contexts */
8119                                 i40e_reset_ch_rings(vsi, ch);
8120                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8121                                 netdev_unbind_sb_channel(vsi->netdev,
8122                                                          ch->fwd->netdev);
8123                                 netdev_set_sb_channel(ch->fwd->netdev, 0);
8124                                 kfree(ch->fwd);
8125                                 ch->fwd = NULL;
8126                         }
8127                 }
8128         }
8129 }
8130
8131 /**
8132  * i40e_fwd_del - delete macvlan interfaces
8133  * @netdev: net device to configure
8134  * @vdev: macvlan netdevice
8135  */
8136 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
8137 {
8138         struct i40e_netdev_priv *np = netdev_priv(netdev);
8139         struct i40e_fwd_adapter *fwd = vdev;
8140         struct i40e_channel *ch, *ch_tmp;
8141         struct i40e_vsi *vsi = np->vsi;
8142         struct i40e_pf *pf = vsi->back;
8143         struct i40e_hw *hw = &pf->hw;
8144         int aq_err, ret = 0;
8145
8146         /* Find the channel associated with the macvlan and del mac filter */
8147         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
8148                 if (i40e_is_channel_macvlan(ch) &&
8149                     ether_addr_equal(i40e_channel_mac(ch),
8150                                      fwd->netdev->dev_addr)) {
8151                         ret = i40e_del_macvlan_filter(hw, ch->seid,
8152                                                       i40e_channel_mac(ch),
8153                                                       &aq_err);
8154                         if (!ret) {
8155                                 /* Reset queue contexts */
8156                                 i40e_reset_ch_rings(vsi, ch);
8157                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
8158                                 netdev_unbind_sb_channel(netdev, fwd->netdev);
8159                                 netdev_set_sb_channel(fwd->netdev, 0);
8160                                 kfree(ch->fwd);
8161                                 ch->fwd = NULL;
8162                         } else {
8163                                 dev_info(&pf->pdev->dev,
8164                                          "Error deleting mac filter on macvlan err %pe, aq_err %s\n",
8165                                           ERR_PTR(ret),
8166                                           i40e_aq_str(hw, aq_err));
8167                         }
8168                         break;
8169                 }
8170         }
8171 }
8172
8173 /**
8174  * i40e_setup_tc - configure multiple traffic classes
8175  * @netdev: net device to configure
8176  * @type_data: tc offload data
8177  **/
8178 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
8179 {
8180         struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8181         struct i40e_netdev_priv *np = netdev_priv(netdev);
8182         struct i40e_vsi *vsi = np->vsi;
8183         struct i40e_pf *pf = vsi->back;
8184         u8 enabled_tc = 0, num_tc, hw;
8185         bool need_reset = false;
8186         int old_queue_pairs;
8187         int ret = -EINVAL;
8188         u16 mode;
8189         int i;
8190
8191         old_queue_pairs = vsi->num_queue_pairs;
8192         num_tc = mqprio_qopt->qopt.num_tc;
8193         hw = mqprio_qopt->qopt.hw;
8194         mode = mqprio_qopt->mode;
8195         if (!hw) {
8196                 clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8197                 memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8198                 goto config_tc;
8199         }
8200
8201         /* Check if MFP enabled */
8202         if (test_bit(I40E_FLAG_MFP_ENA, pf->flags)) {
8203                 netdev_info(netdev,
8204                             "Configuring TC not supported in MFP mode\n");
8205                 return ret;
8206         }
8207         switch (mode) {
8208         case TC_MQPRIO_MODE_DCB:
8209                 clear_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8210
8211                 /* Check if DCB enabled to continue */
8212                 if (!test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8213                         netdev_info(netdev,
8214                                     "DCB is not enabled for adapter\n");
8215                         return ret;
8216                 }
8217
8218                 /* Check whether tc count is within enabled limit */
8219                 if (num_tc > i40e_pf_get_num_tc(pf)) {
8220                         netdev_info(netdev,
8221                                     "TC count greater than enabled on link for adapter\n");
8222                         return ret;
8223                 }
8224                 break;
8225         case TC_MQPRIO_MODE_CHANNEL:
8226                 if (test_bit(I40E_FLAG_DCB_ENA, pf->flags)) {
8227                         netdev_info(netdev,
8228                                     "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8229                         return ret;
8230                 }
8231                 if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
8232                         return ret;
8233                 ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8234                 if (ret)
8235                         return ret;
8236                 memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8237                        sizeof(*mqprio_qopt));
8238                 set_bit(I40E_FLAG_TC_MQPRIO_ENA, pf->flags);
8239                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
8240                 break;
8241         default:
8242                 return -EINVAL;
8243         }
8244
8245 config_tc:
8246         /* Generate TC map for number of tc requested */
8247         for (i = 0; i < num_tc; i++)
8248                 enabled_tc |= BIT(i);
8249
8250         /* Requesting same TC configuration as already enabled */
8251         if (enabled_tc == vsi->tc_config.enabled_tc &&
8252             mode != TC_MQPRIO_MODE_CHANNEL)
8253                 return 0;
8254
8255         /* Quiesce VSI queues */
8256         i40e_quiesce_vsi(vsi);
8257
8258         if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8259                 i40e_remove_queue_channels(vsi);
8260
8261         /* Configure VSI for enabled TCs */
8262         ret = i40e_vsi_config_tc(vsi, enabled_tc);
8263         if (ret) {
8264                 netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8265                             vsi->seid);
8266                 need_reset = true;
8267                 goto exit;
8268         } else if (enabled_tc &&
8269                    (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8270                 netdev_info(netdev,
8271                             "Failed to create channel. Override queues (%u) not power of 2\n",
8272                             vsi->tc_config.tc_info[0].qcount);
8273                 ret = -EINVAL;
8274                 need_reset = true;
8275                 goto exit;
8276         }
8277
8278         dev_info(&vsi->back->pdev->dev,
8279                  "Setup channel (id:%u) utilizing num_queues %d\n",
8280                  vsi->seid, vsi->tc_config.tc_info[0].qcount);
8281
8282         if (i40e_is_tc_mqprio_enabled(pf)) {
8283                 if (vsi->mqprio_qopt.max_rate[0]) {
8284                         u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
8285                                                   vsi->mqprio_qopt.max_rate[0]);
8286
8287                         ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8288                         if (!ret) {
8289                                 u64 credits = max_tx_rate;
8290
8291                                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
8292                                 dev_dbg(&vsi->back->pdev->dev,
8293                                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8294                                         max_tx_rate,
8295                                         credits,
8296                                         vsi->seid);
8297                         } else {
8298                                 need_reset = true;
8299                                 goto exit;
8300                         }
8301                 }
8302                 ret = i40e_configure_queue_channels(vsi);
8303                 if (ret) {
8304                         vsi->num_queue_pairs = old_queue_pairs;
8305                         netdev_info(netdev,
8306                                     "Failed configuring queue channels\n");
8307                         need_reset = true;
8308                         goto exit;
8309                 }
8310         }
8311
8312 exit:
8313         /* Reset the configuration data to defaults, only TC0 is enabled */
8314         if (need_reset) {
8315                 i40e_vsi_set_default_tc_config(vsi);
8316                 need_reset = false;
8317         }
8318
8319         /* Unquiesce VSI */
8320         i40e_unquiesce_vsi(vsi);
8321         return ret;
8322 }
8323
8324 /**
8325  * i40e_set_cld_element - sets cloud filter element data
8326  * @filter: cloud filter rule
8327  * @cld: ptr to cloud filter element data
8328  *
8329  * This is helper function to copy data into cloud filter element
8330  **/
8331 static inline void
8332 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8333                      struct i40e_aqc_cloud_filters_element_data *cld)
8334 {
8335         u32 ipa;
8336         int i;
8337
8338         memset(cld, 0, sizeof(*cld));
8339         ether_addr_copy(cld->outer_mac, filter->dst_mac);
8340         ether_addr_copy(cld->inner_mac, filter->src_mac);
8341
8342         if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8343                 return;
8344
8345         if (filter->n_proto == ETH_P_IPV6) {
8346 #define IPV6_MAX_INDEX  (ARRAY_SIZE(filter->dst_ipv6) - 1)
8347                 for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8348                         ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8349
8350                         *(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8351                 }
8352         } else {
8353                 ipa = be32_to_cpu(filter->dst_ipv4);
8354
8355                 memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8356         }
8357
8358         cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8359
8360         /* tenant_id is not supported by FW now, once the support is enabled
8361          * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8362          */
8363         if (filter->tenant_id)
8364                 return;
8365 }
8366
8367 /**
8368  * i40e_add_del_cloud_filter - Add/del cloud filter
8369  * @vsi: pointer to VSI
8370  * @filter: cloud filter rule
8371  * @add: if true, add, if false, delete
8372  *
8373  * Add or delete a cloud filter for a specific flow spec.
8374  * Returns 0 if the filter were successfully added.
8375  **/
8376 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8377                               struct i40e_cloud_filter *filter, bool add)
8378 {
8379         struct i40e_aqc_cloud_filters_element_data cld_filter;
8380         struct i40e_pf *pf = vsi->back;
8381         int ret;
8382         static const u16 flag_table[128] = {
8383                 [I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8384                         I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8385                 [I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8386                         I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8387                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8388                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8389                 [I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8390                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8391                 [I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8392                         I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8393                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8394                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8395                 [I40E_CLOUD_FILTER_FLAGS_IIP] =
8396                         I40E_AQC_ADD_CLOUD_FILTER_IIP,
8397         };
8398
8399         if (filter->flags >= ARRAY_SIZE(flag_table))
8400                 return -EIO;
8401
8402         memset(&cld_filter, 0, sizeof(cld_filter));
8403
8404         /* copy element needed to add cloud filter from filter */
8405         i40e_set_cld_element(filter, &cld_filter);
8406
8407         if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8408                 cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8409                                              I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8410
8411         if (filter->n_proto == ETH_P_IPV6)
8412                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8413                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8414         else
8415                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8416                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8417
8418         if (add)
8419                 ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8420                                                 &cld_filter, 1);
8421         else
8422                 ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8423                                                 &cld_filter, 1);
8424         if (ret)
8425                 dev_dbg(&pf->pdev->dev,
8426                         "Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8427                         add ? "add" : "delete", filter->dst_port, ret,
8428                         pf->hw.aq.asq_last_status);
8429         else
8430                 dev_info(&pf->pdev->dev,
8431                          "%s cloud filter for VSI: %d\n",
8432                          add ? "Added" : "Deleted", filter->seid);
8433         return ret;
8434 }
8435
8436 /**
8437  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8438  * @vsi: pointer to VSI
8439  * @filter: cloud filter rule
8440  * @add: if true, add, if false, delete
8441  *
8442  * Add or delete a cloud filter for a specific flow spec using big buffer.
8443  * Returns 0 if the filter were successfully added.
8444  **/
8445 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8446                                       struct i40e_cloud_filter *filter,
8447                                       bool add)
8448 {
8449         struct i40e_aqc_cloud_filters_element_bb cld_filter;
8450         struct i40e_pf *pf = vsi->back;
8451         int ret;
8452
8453         /* Both (src/dst) valid mac_addr are not supported */
8454         if ((is_valid_ether_addr(filter->dst_mac) &&
8455              is_valid_ether_addr(filter->src_mac)) ||
8456             (is_multicast_ether_addr(filter->dst_mac) &&
8457              is_multicast_ether_addr(filter->src_mac)))
8458                 return -EOPNOTSUPP;
8459
8460         /* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8461          * ports are not supported via big buffer now.
8462          */
8463         if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8464                 return -EOPNOTSUPP;
8465
8466         /* adding filter using src_port/src_ip is not supported at this stage */
8467         if (filter->src_port ||
8468             (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8469             !ipv6_addr_any(&filter->ip.v6.src_ip6))
8470                 return -EOPNOTSUPP;
8471
8472         memset(&cld_filter, 0, sizeof(cld_filter));
8473
8474         /* copy element needed to add cloud filter from filter */
8475         i40e_set_cld_element(filter, &cld_filter.element);
8476
8477         if (is_valid_ether_addr(filter->dst_mac) ||
8478             is_valid_ether_addr(filter->src_mac) ||
8479             is_multicast_ether_addr(filter->dst_mac) ||
8480             is_multicast_ether_addr(filter->src_mac)) {
8481                 /* MAC + IP : unsupported mode */
8482                 if (filter->dst_ipv4)
8483                         return -EOPNOTSUPP;
8484
8485                 /* since we validated that L4 port must be valid before
8486                  * we get here, start with respective "flags" value
8487                  * and update if vlan is present or not
8488                  */
8489                 cld_filter.element.flags =
8490                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8491
8492                 if (filter->vlan_id) {
8493                         cld_filter.element.flags =
8494                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8495                 }
8496
8497         } else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8498                    !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8499                 cld_filter.element.flags =
8500                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8501                 if (filter->n_proto == ETH_P_IPV6)
8502                         cld_filter.element.flags |=
8503                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8504                 else
8505                         cld_filter.element.flags |=
8506                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8507         } else {
8508                 dev_err(&pf->pdev->dev,
8509                         "either mac or ip has to be valid for cloud filter\n");
8510                 return -EINVAL;
8511         }
8512
8513         /* Now copy L4 port in Byte 6..7 in general fields */
8514         cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8515                                                 be16_to_cpu(filter->dst_port);
8516
8517         if (add) {
8518                 /* Validate current device switch mode, change if necessary */
8519                 ret = i40e_validate_and_set_switch_mode(vsi);
8520                 if (ret) {
8521                         dev_err(&pf->pdev->dev,
8522                                 "failed to set switch mode, ret %d\n",
8523                                 ret);
8524                         return ret;
8525                 }
8526
8527                 ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8528                                                    &cld_filter, 1);
8529         } else {
8530                 ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8531                                                    &cld_filter, 1);
8532         }
8533
8534         if (ret)
8535                 dev_dbg(&pf->pdev->dev,
8536                         "Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8537                         add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8538         else
8539                 dev_info(&pf->pdev->dev,
8540                          "%s cloud filter for VSI: %d, L4 port: %d\n",
8541                          add ? "add" : "delete", filter->seid,
8542                          ntohs(filter->dst_port));
8543         return ret;
8544 }
8545
8546 /**
8547  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8548  * @vsi: Pointer to VSI
8549  * @f: Pointer to struct flow_cls_offload
8550  * @filter: Pointer to cloud filter structure
8551  *
8552  **/
8553 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8554                                  struct flow_cls_offload *f,
8555                                  struct i40e_cloud_filter *filter)
8556 {
8557         struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8558         struct flow_dissector *dissector = rule->match.dissector;
8559         u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8560         struct i40e_pf *pf = vsi->back;
8561         u8 field_flags = 0;
8562
8563         if (dissector->used_keys &
8564             ~(BIT_ULL(FLOW_DISSECTOR_KEY_CONTROL) |
8565               BIT_ULL(FLOW_DISSECTOR_KEY_BASIC) |
8566               BIT_ULL(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8567               BIT_ULL(FLOW_DISSECTOR_KEY_VLAN) |
8568               BIT_ULL(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8569               BIT_ULL(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8570               BIT_ULL(FLOW_DISSECTOR_KEY_PORTS) |
8571               BIT_ULL(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8572                 dev_err(&pf->pdev->dev, "Unsupported key used: 0x%llx\n",
8573                         dissector->used_keys);
8574                 return -EOPNOTSUPP;
8575         }
8576
8577         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8578                 struct flow_match_enc_keyid match;
8579
8580                 flow_rule_match_enc_keyid(rule, &match);
8581                 if (match.mask->keyid != 0)
8582                         field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8583
8584                 filter->tenant_id = be32_to_cpu(match.key->keyid);
8585         }
8586
8587         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8588                 struct flow_match_basic match;
8589
8590                 flow_rule_match_basic(rule, &match);
8591                 n_proto_key = ntohs(match.key->n_proto);
8592                 n_proto_mask = ntohs(match.mask->n_proto);
8593
8594                 if (n_proto_key == ETH_P_ALL) {
8595                         n_proto_key = 0;
8596                         n_proto_mask = 0;
8597                 }
8598                 filter->n_proto = n_proto_key & n_proto_mask;
8599                 filter->ip_proto = match.key->ip_proto;
8600         }
8601
8602         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8603                 struct flow_match_eth_addrs match;
8604
8605                 flow_rule_match_eth_addrs(rule, &match);
8606
8607                 /* use is_broadcast and is_zero to check for all 0xf or 0 */
8608                 if (!is_zero_ether_addr(match.mask->dst)) {
8609                         if (is_broadcast_ether_addr(match.mask->dst)) {
8610                                 field_flags |= I40E_CLOUD_FIELD_OMAC;
8611                         } else {
8612                                 dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8613                                         match.mask->dst);
8614                                 return -EIO;
8615                         }
8616                 }
8617
8618                 if (!is_zero_ether_addr(match.mask->src)) {
8619                         if (is_broadcast_ether_addr(match.mask->src)) {
8620                                 field_flags |= I40E_CLOUD_FIELD_IMAC;
8621                         } else {
8622                                 dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8623                                         match.mask->src);
8624                                 return -EIO;
8625                         }
8626                 }
8627                 ether_addr_copy(filter->dst_mac, match.key->dst);
8628                 ether_addr_copy(filter->src_mac, match.key->src);
8629         }
8630
8631         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8632                 struct flow_match_vlan match;
8633
8634                 flow_rule_match_vlan(rule, &match);
8635                 if (match.mask->vlan_id) {
8636                         if (match.mask->vlan_id == VLAN_VID_MASK) {
8637                                 field_flags |= I40E_CLOUD_FIELD_IVLAN;
8638
8639                         } else {
8640                                 dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8641                                         match.mask->vlan_id);
8642                                 return -EIO;
8643                         }
8644                 }
8645
8646                 filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8647         }
8648
8649         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8650                 struct flow_match_control match;
8651
8652                 flow_rule_match_control(rule, &match);
8653                 addr_type = match.key->addr_type;
8654         }
8655
8656         if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8657                 struct flow_match_ipv4_addrs match;
8658
8659                 flow_rule_match_ipv4_addrs(rule, &match);
8660                 if (match.mask->dst) {
8661                         if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8662                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8663                         } else {
8664                                 dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8665                                         &match.mask->dst);
8666                                 return -EIO;
8667                         }
8668                 }
8669
8670                 if (match.mask->src) {
8671                         if (match.mask->src == cpu_to_be32(0xffffffff)) {
8672                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8673                         } else {
8674                                 dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8675                                         &match.mask->src);
8676                                 return -EIO;
8677                         }
8678                 }
8679
8680                 if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8681                         dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8682                         return -EIO;
8683                 }
8684                 filter->dst_ipv4 = match.key->dst;
8685                 filter->src_ipv4 = match.key->src;
8686         }
8687
8688         if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8689                 struct flow_match_ipv6_addrs match;
8690
8691                 flow_rule_match_ipv6_addrs(rule, &match);
8692
8693                 /* src and dest IPV6 address should not be LOOPBACK
8694                  * (0:0:0:0:0:0:0:1), which can be represented as ::1
8695                  */
8696                 if (ipv6_addr_loopback(&match.key->dst) ||
8697                     ipv6_addr_loopback(&match.key->src)) {
8698                         dev_err(&pf->pdev->dev,
8699                                 "Bad ipv6, addr is LOOPBACK\n");
8700                         return -EIO;
8701                 }
8702                 if (!ipv6_addr_any(&match.mask->dst) ||
8703                     !ipv6_addr_any(&match.mask->src))
8704                         field_flags |= I40E_CLOUD_FIELD_IIP;
8705
8706                 memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8707                        sizeof(filter->src_ipv6));
8708                 memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8709                        sizeof(filter->dst_ipv6));
8710         }
8711
8712         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8713                 struct flow_match_ports match;
8714
8715                 flow_rule_match_ports(rule, &match);
8716                 if (match.mask->src) {
8717                         if (match.mask->src == cpu_to_be16(0xffff)) {
8718                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8719                         } else {
8720                                 dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8721                                         be16_to_cpu(match.mask->src));
8722                                 return -EIO;
8723                         }
8724                 }
8725
8726                 if (match.mask->dst) {
8727                         if (match.mask->dst == cpu_to_be16(0xffff)) {
8728                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8729                         } else {
8730                                 dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8731                                         be16_to_cpu(match.mask->dst));
8732                                 return -EIO;
8733                         }
8734                 }
8735
8736                 filter->dst_port = match.key->dst;
8737                 filter->src_port = match.key->src;
8738
8739                 switch (filter->ip_proto) {
8740                 case IPPROTO_TCP:
8741                 case IPPROTO_UDP:
8742                         break;
8743                 default:
8744                         dev_err(&pf->pdev->dev,
8745                                 "Only UDP and TCP transport are supported\n");
8746                         return -EINVAL;
8747                 }
8748         }
8749         filter->flags = field_flags;
8750         return 0;
8751 }
8752
8753 /**
8754  * i40e_handle_tclass: Forward to a traffic class on the device
8755  * @vsi: Pointer to VSI
8756  * @tc: traffic class index on the device
8757  * @filter: Pointer to cloud filter structure
8758  *
8759  **/
8760 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8761                               struct i40e_cloud_filter *filter)
8762 {
8763         struct i40e_channel *ch, *ch_tmp;
8764
8765         /* direct to a traffic class on the same device */
8766         if (tc == 0) {
8767                 filter->seid = vsi->seid;
8768                 return 0;
8769         } else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8770                 if (!filter->dst_port) {
8771                         dev_err(&vsi->back->pdev->dev,
8772                                 "Specify destination port to direct to traffic class that is not default\n");
8773                         return -EINVAL;
8774                 }
8775                 if (list_empty(&vsi->ch_list))
8776                         return -EINVAL;
8777                 list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8778                                          list) {
8779                         if (ch->seid == vsi->tc_seid_map[tc])
8780                                 filter->seid = ch->seid;
8781                 }
8782                 return 0;
8783         }
8784         dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8785         return -EINVAL;
8786 }
8787
8788 /**
8789  * i40e_configure_clsflower - Configure tc flower filters
8790  * @vsi: Pointer to VSI
8791  * @cls_flower: Pointer to struct flow_cls_offload
8792  *
8793  **/
8794 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8795                                     struct flow_cls_offload *cls_flower)
8796 {
8797         int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8798         struct i40e_cloud_filter *filter = NULL;
8799         struct i40e_pf *pf = vsi->back;
8800         int err = 0;
8801
8802         if (tc < 0) {
8803                 dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8804                 return -EOPNOTSUPP;
8805         }
8806
8807         if (!tc) {
8808                 dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8809                 return -EINVAL;
8810         }
8811
8812         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8813             test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8814                 return -EBUSY;
8815
8816         if (pf->fdir_pf_active_filters ||
8817             (!hlist_empty(&pf->fdir_filter_list))) {
8818                 dev_err(&vsi->back->pdev->dev,
8819                         "Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8820                 return -EINVAL;
8821         }
8822
8823         if (test_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags)) {
8824                 dev_err(&vsi->back->pdev->dev,
8825                         "Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8826                 clear_bit(I40E_FLAG_FD_SB_ENA, vsi->back->flags);
8827                 clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, vsi->back->flags);
8828         }
8829
8830         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8831         if (!filter)
8832                 return -ENOMEM;
8833
8834         filter->cookie = cls_flower->cookie;
8835
8836         err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8837         if (err < 0)
8838                 goto err;
8839
8840         err = i40e_handle_tclass(vsi, tc, filter);
8841         if (err < 0)
8842                 goto err;
8843
8844         /* Add cloud filter */
8845         if (filter->dst_port)
8846                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8847         else
8848                 err = i40e_add_del_cloud_filter(vsi, filter, true);
8849
8850         if (err) {
8851                 dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8852                         err);
8853                 goto err;
8854         }
8855
8856         /* add filter to the ordered list */
8857         INIT_HLIST_NODE(&filter->cloud_node);
8858
8859         hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8860
8861         pf->num_cloud_filters++;
8862
8863         return err;
8864 err:
8865         kfree(filter);
8866         return err;
8867 }
8868
8869 /**
8870  * i40e_find_cloud_filter - Find the could filter in the list
8871  * @vsi: Pointer to VSI
8872  * @cookie: filter specific cookie
8873  *
8874  **/
8875 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8876                                                         unsigned long *cookie)
8877 {
8878         struct i40e_cloud_filter *filter = NULL;
8879         struct hlist_node *node2;
8880
8881         hlist_for_each_entry_safe(filter, node2,
8882                                   &vsi->back->cloud_filter_list, cloud_node)
8883                 if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8884                         return filter;
8885         return NULL;
8886 }
8887
8888 /**
8889  * i40e_delete_clsflower - Remove tc flower filters
8890  * @vsi: Pointer to VSI
8891  * @cls_flower: Pointer to struct flow_cls_offload
8892  *
8893  **/
8894 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8895                                  struct flow_cls_offload *cls_flower)
8896 {
8897         struct i40e_cloud_filter *filter = NULL;
8898         struct i40e_pf *pf = vsi->back;
8899         int err = 0;
8900
8901         filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8902
8903         if (!filter)
8904                 return -EINVAL;
8905
8906         hash_del(&filter->cloud_node);
8907
8908         if (filter->dst_port)
8909                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8910         else
8911                 err = i40e_add_del_cloud_filter(vsi, filter, false);
8912
8913         kfree(filter);
8914         if (err) {
8915                 dev_err(&pf->pdev->dev,
8916                         "Failed to delete cloud filter, err %pe\n",
8917                         ERR_PTR(err));
8918                 return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8919         }
8920
8921         pf->num_cloud_filters--;
8922         if (!pf->num_cloud_filters)
8923                 if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
8924                     !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
8925                         set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
8926                         clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
8927                         clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
8928                 }
8929         return 0;
8930 }
8931
8932 /**
8933  * i40e_setup_tc_cls_flower - flower classifier offloads
8934  * @np: net device to configure
8935  * @cls_flower: offload data
8936  **/
8937 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8938                                     struct flow_cls_offload *cls_flower)
8939 {
8940         struct i40e_vsi *vsi = np->vsi;
8941
8942         switch (cls_flower->command) {
8943         case FLOW_CLS_REPLACE:
8944                 return i40e_configure_clsflower(vsi, cls_flower);
8945         case FLOW_CLS_DESTROY:
8946                 return i40e_delete_clsflower(vsi, cls_flower);
8947         case FLOW_CLS_STATS:
8948                 return -EOPNOTSUPP;
8949         default:
8950                 return -EOPNOTSUPP;
8951         }
8952 }
8953
8954 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8955                                   void *cb_priv)
8956 {
8957         struct i40e_netdev_priv *np = cb_priv;
8958
8959         if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8960                 return -EOPNOTSUPP;
8961
8962         switch (type) {
8963         case TC_SETUP_CLSFLOWER:
8964                 return i40e_setup_tc_cls_flower(np, type_data);
8965
8966         default:
8967                 return -EOPNOTSUPP;
8968         }
8969 }
8970
8971 static LIST_HEAD(i40e_block_cb_list);
8972
8973 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8974                            void *type_data)
8975 {
8976         struct i40e_netdev_priv *np = netdev_priv(netdev);
8977
8978         switch (type) {
8979         case TC_SETUP_QDISC_MQPRIO:
8980                 return i40e_setup_tc(netdev, type_data);
8981         case TC_SETUP_BLOCK:
8982                 return flow_block_cb_setup_simple(type_data,
8983                                                   &i40e_block_cb_list,
8984                                                   i40e_setup_tc_block_cb,
8985                                                   np, np, true);
8986         default:
8987                 return -EOPNOTSUPP;
8988         }
8989 }
8990
8991 /**
8992  * i40e_open - Called when a network interface is made active
8993  * @netdev: network interface device structure
8994  *
8995  * The open entry point is called when a network interface is made
8996  * active by the system (IFF_UP).  At this point all resources needed
8997  * for transmit and receive operations are allocated, the interrupt
8998  * handler is registered with the OS, the netdev watchdog subtask is
8999  * enabled, and the stack is notified that the interface is ready.
9000  *
9001  * Returns 0 on success, negative value on failure
9002  **/
9003 int i40e_open(struct net_device *netdev)
9004 {
9005         struct i40e_netdev_priv *np = netdev_priv(netdev);
9006         struct i40e_vsi *vsi = np->vsi;
9007         struct i40e_pf *pf = vsi->back;
9008         int err;
9009
9010         /* disallow open during test or if eeprom is broken */
9011         if (test_bit(__I40E_TESTING, pf->state) ||
9012             test_bit(__I40E_BAD_EEPROM, pf->state))
9013                 return -EBUSY;
9014
9015         netif_carrier_off(netdev);
9016
9017         if (i40e_force_link_state(pf, true))
9018                 return -EAGAIN;
9019
9020         err = i40e_vsi_open(vsi);
9021         if (err)
9022                 return err;
9023
9024         /* configure global TSO hardware offload settings */
9025         wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
9026                                                        TCP_FLAG_FIN) >> 16);
9027         wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
9028                                                        TCP_FLAG_FIN |
9029                                                        TCP_FLAG_CWR) >> 16);
9030         wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
9031         udp_tunnel_get_rx_info(netdev);
9032
9033         return 0;
9034 }
9035
9036 /**
9037  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
9038  * @vsi: vsi structure
9039  *
9040  * This updates netdev's number of tx/rx queues
9041  *
9042  * Returns status of setting tx/rx queues
9043  **/
9044 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
9045 {
9046         int ret;
9047
9048         ret = netif_set_real_num_rx_queues(vsi->netdev,
9049                                            vsi->num_queue_pairs);
9050         if (ret)
9051                 return ret;
9052
9053         return netif_set_real_num_tx_queues(vsi->netdev,
9054                                             vsi->num_queue_pairs);
9055 }
9056
9057 /**
9058  * i40e_vsi_open -
9059  * @vsi: the VSI to open
9060  *
9061  * Finish initialization of the VSI.
9062  *
9063  * Returns 0 on success, negative value on failure
9064  *
9065  * Note: expects to be called while under rtnl_lock()
9066  **/
9067 int i40e_vsi_open(struct i40e_vsi *vsi)
9068 {
9069         struct i40e_pf *pf = vsi->back;
9070         char int_name[I40E_INT_NAME_STR_LEN];
9071         int err;
9072
9073         /* allocate descriptors */
9074         err = i40e_vsi_setup_tx_resources(vsi);
9075         if (err)
9076                 goto err_setup_tx;
9077         err = i40e_vsi_setup_rx_resources(vsi);
9078         if (err)
9079                 goto err_setup_rx;
9080
9081         err = i40e_vsi_configure(vsi);
9082         if (err)
9083                 goto err_setup_rx;
9084
9085         if (vsi->netdev) {
9086                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
9087                          dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
9088                 err = i40e_vsi_request_irq(vsi, int_name);
9089                 if (err)
9090                         goto err_setup_rx;
9091
9092                 /* Notify the stack of the actual queue counts. */
9093                 err = i40e_netif_set_realnum_tx_rx_queues(vsi);
9094                 if (err)
9095                         goto err_set_queues;
9096
9097         } else if (vsi->type == I40E_VSI_FDIR) {
9098                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
9099                          dev_driver_string(&pf->pdev->dev),
9100                          dev_name(&pf->pdev->dev));
9101                 err = i40e_vsi_request_irq(vsi, int_name);
9102                 if (err)
9103                         goto err_setup_rx;
9104
9105         } else {
9106                 err = -EINVAL;
9107                 goto err_setup_rx;
9108         }
9109
9110         err = i40e_up_complete(vsi);
9111         if (err)
9112                 goto err_up_complete;
9113
9114         return 0;
9115
9116 err_up_complete:
9117         i40e_down(vsi);
9118 err_set_queues:
9119         i40e_vsi_free_irq(vsi);
9120 err_setup_rx:
9121         i40e_vsi_free_rx_resources(vsi);
9122 err_setup_tx:
9123         i40e_vsi_free_tx_resources(vsi);
9124         if (vsi == pf->vsi[pf->lan_vsi])
9125                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
9126
9127         return err;
9128 }
9129
9130 /**
9131  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
9132  * @pf: Pointer to PF
9133  *
9134  * This function destroys the hlist where all the Flow Director
9135  * filters were saved.
9136  **/
9137 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
9138 {
9139         struct i40e_fdir_filter *filter;
9140         struct i40e_flex_pit *pit_entry, *tmp;
9141         struct hlist_node *node2;
9142
9143         hlist_for_each_entry_safe(filter, node2,
9144                                   &pf->fdir_filter_list, fdir_node) {
9145                 hlist_del(&filter->fdir_node);
9146                 kfree(filter);
9147         }
9148
9149         list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
9150                 list_del(&pit_entry->list);
9151                 kfree(pit_entry);
9152         }
9153         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
9154
9155         list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
9156                 list_del(&pit_entry->list);
9157                 kfree(pit_entry);
9158         }
9159         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
9160
9161         pf->fdir_pf_active_filters = 0;
9162         i40e_reset_fdir_filter_cnt(pf);
9163
9164         /* Reprogram the default input set for TCP/IPv4 */
9165         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9166                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9167                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9168
9169         /* Reprogram the default input set for TCP/IPv6 */
9170         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
9171                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9172                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9173
9174         /* Reprogram the default input set for UDP/IPv4 */
9175         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
9176                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9177                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9178
9179         /* Reprogram the default input set for UDP/IPv6 */
9180         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9181                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9182                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9183
9184         /* Reprogram the default input set for SCTP/IPv4 */
9185         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9186                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9187                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9188
9189         /* Reprogram the default input set for SCTP/IPv6 */
9190         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9191                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9192                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9193
9194         /* Reprogram the default input set for Other/IPv4 */
9195         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9196                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9197
9198         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9199                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9200
9201         /* Reprogram the default input set for Other/IPv6 */
9202         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9203                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9204
9205         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9206                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9207 }
9208
9209 /**
9210  * i40e_cloud_filter_exit - Cleans up the cloud filters
9211  * @pf: Pointer to PF
9212  *
9213  * This function destroys the hlist where all the cloud filters
9214  * were saved.
9215  **/
9216 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9217 {
9218         struct i40e_cloud_filter *cfilter;
9219         struct hlist_node *node;
9220
9221         hlist_for_each_entry_safe(cfilter, node,
9222                                   &pf->cloud_filter_list, cloud_node) {
9223                 hlist_del(&cfilter->cloud_node);
9224                 kfree(cfilter);
9225         }
9226         pf->num_cloud_filters = 0;
9227
9228         if (test_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags) &&
9229             !test_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags)) {
9230                 set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
9231                 clear_bit(I40E_FLAG_FD_SB_TO_CLOUD_FILTER, pf->flags);
9232                 clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
9233         }
9234 }
9235
9236 /**
9237  * i40e_close - Disables a network interface
9238  * @netdev: network interface device structure
9239  *
9240  * The close entry point is called when an interface is de-activated
9241  * by the OS.  The hardware is still under the driver's control, but
9242  * this netdev interface is disabled.
9243  *
9244  * Returns 0, this is not allowed to fail
9245  **/
9246 int i40e_close(struct net_device *netdev)
9247 {
9248         struct i40e_netdev_priv *np = netdev_priv(netdev);
9249         struct i40e_vsi *vsi = np->vsi;
9250
9251         i40e_vsi_close(vsi);
9252
9253         return 0;
9254 }
9255
9256 /**
9257  * i40e_do_reset - Start a PF or Core Reset sequence
9258  * @pf: board private structure
9259  * @reset_flags: which reset is requested
9260  * @lock_acquired: indicates whether or not the lock has been acquired
9261  * before this function was called.
9262  *
9263  * The essential difference in resets is that the PF Reset
9264  * doesn't clear the packet buffers, doesn't reset the PE
9265  * firmware, and doesn't bother the other PFs on the chip.
9266  **/
9267 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9268 {
9269         u32 val;
9270
9271         /* do the biggest reset indicated */
9272         if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9273
9274                 /* Request a Global Reset
9275                  *
9276                  * This will start the chip's countdown to the actual full
9277                  * chip reset event, and a warning interrupt to be sent
9278                  * to all PFs, including the requestor.  Our handler
9279                  * for the warning interrupt will deal with the shutdown
9280                  * and recovery of the switch setup.
9281                  */
9282                 dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9283                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9284                 val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9285                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9286
9287         } else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9288
9289                 /* Request a Core Reset
9290                  *
9291                  * Same as Global Reset, except does *not* include the MAC/PHY
9292                  */
9293                 dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9294                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9295                 val |= I40E_GLGEN_RTRIG_CORER_MASK;
9296                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9297                 i40e_flush(&pf->hw);
9298
9299         } else if (reset_flags & I40E_PF_RESET_FLAG) {
9300
9301                 /* Request a PF Reset
9302                  *
9303                  * Resets only the PF-specific registers
9304                  *
9305                  * This goes directly to the tear-down and rebuild of
9306                  * the switch, since we need to do all the recovery as
9307                  * for the Core Reset.
9308                  */
9309                 dev_dbg(&pf->pdev->dev, "PFR requested\n");
9310                 i40e_handle_reset_warning(pf, lock_acquired);
9311
9312         } else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9313                 /* Request a PF Reset
9314                  *
9315                  * Resets PF and reinitializes PFs VSI.
9316                  */
9317                 i40e_prep_for_reset(pf);
9318                 i40e_reset_and_rebuild(pf, true, lock_acquired);
9319                 dev_info(&pf->pdev->dev,
9320                          test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
9321                          "FW LLDP is disabled\n" :
9322                          "FW LLDP is enabled\n");
9323
9324         } else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9325                 int v;
9326
9327                 /* Find the VSI(s) that requested a re-init */
9328                 dev_info(&pf->pdev->dev,
9329                          "VSI reinit requested\n");
9330                 for (v = 0; v < pf->num_alloc_vsi; v++) {
9331                         struct i40e_vsi *vsi = pf->vsi[v];
9332
9333                         if (vsi != NULL &&
9334                             test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9335                                                vsi->state))
9336                                 i40e_vsi_reinit_locked(pf->vsi[v]);
9337                 }
9338         } else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9339                 int v;
9340
9341                 /* Find the VSI(s) that needs to be brought down */
9342                 dev_info(&pf->pdev->dev, "VSI down requested\n");
9343                 for (v = 0; v < pf->num_alloc_vsi; v++) {
9344                         struct i40e_vsi *vsi = pf->vsi[v];
9345
9346                         if (vsi != NULL &&
9347                             test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9348                                                vsi->state)) {
9349                                 set_bit(__I40E_VSI_DOWN, vsi->state);
9350                                 i40e_down(vsi);
9351                         }
9352                 }
9353         } else {
9354                 dev_info(&pf->pdev->dev,
9355                          "bad reset request 0x%08x\n", reset_flags);
9356         }
9357 }
9358
9359 #ifdef CONFIG_I40E_DCB
9360 /**
9361  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9362  * @pf: board private structure
9363  * @old_cfg: current DCB config
9364  * @new_cfg: new DCB config
9365  **/
9366 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9367                             struct i40e_dcbx_config *old_cfg,
9368                             struct i40e_dcbx_config *new_cfg)
9369 {
9370         bool need_reconfig = false;
9371
9372         /* Check if ETS configuration has changed */
9373         if (memcmp(&new_cfg->etscfg,
9374                    &old_cfg->etscfg,
9375                    sizeof(new_cfg->etscfg))) {
9376                 /* If Priority Table has changed reconfig is needed */
9377                 if (memcmp(&new_cfg->etscfg.prioritytable,
9378                            &old_cfg->etscfg.prioritytable,
9379                            sizeof(new_cfg->etscfg.prioritytable))) {
9380                         need_reconfig = true;
9381                         dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9382                 }
9383
9384                 if (memcmp(&new_cfg->etscfg.tcbwtable,
9385                            &old_cfg->etscfg.tcbwtable,
9386                            sizeof(new_cfg->etscfg.tcbwtable)))
9387                         dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9388
9389                 if (memcmp(&new_cfg->etscfg.tsatable,
9390                            &old_cfg->etscfg.tsatable,
9391                            sizeof(new_cfg->etscfg.tsatable)))
9392                         dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9393         }
9394
9395         /* Check if PFC configuration has changed */
9396         if (memcmp(&new_cfg->pfc,
9397                    &old_cfg->pfc,
9398                    sizeof(new_cfg->pfc))) {
9399                 need_reconfig = true;
9400                 dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9401         }
9402
9403         /* Check if APP Table has changed */
9404         if (memcmp(&new_cfg->app,
9405                    &old_cfg->app,
9406                    sizeof(new_cfg->app))) {
9407                 need_reconfig = true;
9408                 dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9409         }
9410
9411         dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9412         return need_reconfig;
9413 }
9414
9415 /**
9416  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9417  * @pf: board private structure
9418  * @e: event info posted on ARQ
9419  **/
9420 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9421                                   struct i40e_arq_event_info *e)
9422 {
9423         struct i40e_aqc_lldp_get_mib *mib =
9424                 (struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9425         struct i40e_hw *hw = &pf->hw;
9426         struct i40e_dcbx_config tmp_dcbx_cfg;
9427         bool need_reconfig = false;
9428         int ret = 0;
9429         u8 type;
9430
9431         /* X710-T*L 2.5G and 5G speeds don't support DCB */
9432         if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9433             (hw->phy.link_info.link_speed &
9434              ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9435              !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9436                 /* let firmware decide if the DCB should be disabled */
9437                 set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9438
9439         /* Not DCB capable or capability disabled */
9440         if (!test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
9441                 return ret;
9442
9443         /* Ignore if event is not for Nearest Bridge */
9444         type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9445                 & I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9446         dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9447         if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9448                 return ret;
9449
9450         /* Check MIB Type and return if event for Remote MIB update */
9451         type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9452         dev_dbg(&pf->pdev->dev,
9453                 "LLDP event mib type %s\n", type ? "remote" : "local");
9454         if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9455                 /* Update the remote cached instance and return */
9456                 ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9457                                 I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9458                                 &hw->remote_dcbx_config);
9459                 goto exit;
9460         }
9461
9462         /* Store the old configuration */
9463         tmp_dcbx_cfg = hw->local_dcbx_config;
9464
9465         /* Reset the old DCBx configuration data */
9466         memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9467         /* Get updated DCBX data from firmware */
9468         ret = i40e_get_dcb_config(&pf->hw);
9469         if (ret) {
9470                 /* X710-T*L 2.5G and 5G speeds don't support DCB */
9471                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9472                     (hw->phy.link_info.link_speed &
9473                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9474                         dev_warn(&pf->pdev->dev,
9475                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9476                         clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9477                 } else {
9478                         dev_info(&pf->pdev->dev,
9479                                  "Failed querying DCB configuration data from firmware, err %pe aq_err %s\n",
9480                                  ERR_PTR(ret),
9481                                  i40e_aq_str(&pf->hw,
9482                                              pf->hw.aq.asq_last_status));
9483                 }
9484                 goto exit;
9485         }
9486
9487         /* No change detected in DCBX configs */
9488         if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9489                     sizeof(tmp_dcbx_cfg))) {
9490                 dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9491                 goto exit;
9492         }
9493
9494         need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9495                                                &hw->local_dcbx_config);
9496
9497         i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9498
9499         if (!need_reconfig)
9500                 goto exit;
9501
9502         /* Enable DCB tagging only when more than one TC */
9503         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9504                 set_bit(I40E_FLAG_DCB_ENA, pf->flags);
9505         else
9506                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9507
9508         set_bit(__I40E_PORT_SUSPENDED, pf->state);
9509         /* Reconfiguration needed quiesce all VSIs */
9510         i40e_pf_quiesce_all_vsi(pf);
9511
9512         /* Changes in configuration update VEB/VSI */
9513         i40e_dcb_reconfigure(pf);
9514
9515         ret = i40e_resume_port_tx(pf);
9516
9517         clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9518         /* In case of error no point in resuming VSIs */
9519         if (ret)
9520                 goto exit;
9521
9522         /* Wait for the PF's queues to be disabled */
9523         ret = i40e_pf_wait_queues_disabled(pf);
9524         if (ret) {
9525                 /* Schedule PF reset to recover */
9526                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9527                 i40e_service_event_schedule(pf);
9528         } else {
9529                 i40e_pf_unquiesce_all_vsi(pf);
9530                 set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9531                 set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9532         }
9533
9534 exit:
9535         return ret;
9536 }
9537 #endif /* CONFIG_I40E_DCB */
9538
9539 /**
9540  * i40e_do_reset_safe - Protected reset path for userland calls.
9541  * @pf: board private structure
9542  * @reset_flags: which reset is requested
9543  *
9544  **/
9545 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9546 {
9547         rtnl_lock();
9548         i40e_do_reset(pf, reset_flags, true);
9549         rtnl_unlock();
9550 }
9551
9552 /**
9553  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9554  * @pf: board private structure
9555  * @e: event info posted on ARQ
9556  *
9557  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9558  * and VF queues
9559  **/
9560 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9561                                            struct i40e_arq_event_info *e)
9562 {
9563         struct i40e_aqc_lan_overflow *data =
9564                 (struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9565         u32 queue = le32_to_cpu(data->prtdcb_rupto);
9566         u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9567         struct i40e_hw *hw = &pf->hw;
9568         struct i40e_vf *vf;
9569         u16 vf_id;
9570
9571         dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9572                 queue, qtx_ctl);
9573
9574         if (FIELD_GET(I40E_QTX_CTL_PFVF_Q_MASK, qtx_ctl) !=
9575             I40E_QTX_CTL_VF_QUEUE)
9576                 return;
9577
9578         /* Queue belongs to VF, find the VF and issue VF reset */
9579         vf_id = FIELD_GET(I40E_QTX_CTL_VFVM_INDX_MASK, qtx_ctl);
9580         vf_id -= hw->func_caps.vf_base_id;
9581         vf = &pf->vf[vf_id];
9582         i40e_vc_notify_vf_reset(vf);
9583         /* Allow VF to process pending reset notification */
9584         msleep(20);
9585         i40e_reset_vf(vf, false);
9586 }
9587
9588 /**
9589  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9590  * @pf: board private structure
9591  **/
9592 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9593 {
9594         u32 val, fcnt_prog;
9595
9596         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9597         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9598         return fcnt_prog;
9599 }
9600
9601 /**
9602  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9603  * @pf: board private structure
9604  **/
9605 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9606 {
9607         u32 val, fcnt_prog;
9608
9609         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9610         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9611                     FIELD_GET(I40E_PFQF_FDSTAT_BEST_CNT_MASK, val);
9612         return fcnt_prog;
9613 }
9614
9615 /**
9616  * i40e_get_global_fd_count - Get total FD filters programmed on device
9617  * @pf: board private structure
9618  **/
9619 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9620 {
9621         u32 val, fcnt_prog;
9622
9623         val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9624         fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9625                     FIELD_GET(I40E_GLQF_FDCNT_0_BESTCNT_MASK, val);
9626         return fcnt_prog;
9627 }
9628
9629 /**
9630  * i40e_reenable_fdir_sb - Restore FDir SB capability
9631  * @pf: board private structure
9632  **/
9633 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9634 {
9635         if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9636                 if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
9637                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9638                         dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9639 }
9640
9641 /**
9642  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9643  * @pf: board private structure
9644  **/
9645 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9646 {
9647         if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9648                 /* ATR uses the same filtering logic as SB rules. It only
9649                  * functions properly if the input set mask is at the default
9650                  * settings. It is safe to restore the default input set
9651                  * because there are no active TCPv4 filter rules.
9652                  */
9653                 i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9654                                         I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9655                                         I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9656
9657                 if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
9658                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9659                         dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9660         }
9661 }
9662
9663 /**
9664  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9665  * @pf: board private structure
9666  * @filter: FDir filter to remove
9667  */
9668 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9669                                        struct i40e_fdir_filter *filter)
9670 {
9671         /* Update counters */
9672         pf->fdir_pf_active_filters--;
9673         pf->fd_inv = 0;
9674
9675         switch (filter->flow_type) {
9676         case TCP_V4_FLOW:
9677                 pf->fd_tcp4_filter_cnt--;
9678                 break;
9679         case UDP_V4_FLOW:
9680                 pf->fd_udp4_filter_cnt--;
9681                 break;
9682         case SCTP_V4_FLOW:
9683                 pf->fd_sctp4_filter_cnt--;
9684                 break;
9685         case TCP_V6_FLOW:
9686                 pf->fd_tcp6_filter_cnt--;
9687                 break;
9688         case UDP_V6_FLOW:
9689                 pf->fd_udp6_filter_cnt--;
9690                 break;
9691         case SCTP_V6_FLOW:
9692                 pf->fd_udp6_filter_cnt--;
9693                 break;
9694         case IP_USER_FLOW:
9695                 switch (filter->ipl4_proto) {
9696                 case IPPROTO_TCP:
9697                         pf->fd_tcp4_filter_cnt--;
9698                         break;
9699                 case IPPROTO_UDP:
9700                         pf->fd_udp4_filter_cnt--;
9701                         break;
9702                 case IPPROTO_SCTP:
9703                         pf->fd_sctp4_filter_cnt--;
9704                         break;
9705                 case IPPROTO_IP:
9706                         pf->fd_ip4_filter_cnt--;
9707                         break;
9708                 }
9709                 break;
9710         case IPV6_USER_FLOW:
9711                 switch (filter->ipl4_proto) {
9712                 case IPPROTO_TCP:
9713                         pf->fd_tcp6_filter_cnt--;
9714                         break;
9715                 case IPPROTO_UDP:
9716                         pf->fd_udp6_filter_cnt--;
9717                         break;
9718                 case IPPROTO_SCTP:
9719                         pf->fd_sctp6_filter_cnt--;
9720                         break;
9721                 case IPPROTO_IP:
9722                         pf->fd_ip6_filter_cnt--;
9723                         break;
9724                 }
9725                 break;
9726         }
9727
9728         /* Remove the filter from the list and free memory */
9729         hlist_del(&filter->fdir_node);
9730         kfree(filter);
9731 }
9732
9733 /**
9734  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9735  * @pf: board private structure
9736  **/
9737 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9738 {
9739         struct i40e_fdir_filter *filter;
9740         u32 fcnt_prog, fcnt_avail;
9741         struct hlist_node *node;
9742
9743         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9744                 return;
9745
9746         /* Check if we have enough room to re-enable FDir SB capability. */
9747         fcnt_prog = i40e_get_global_fd_count(pf);
9748         fcnt_avail = pf->fdir_pf_filter_count;
9749         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9750             (pf->fd_add_err == 0) ||
9751             (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9752                 i40e_reenable_fdir_sb(pf);
9753
9754         /* We should wait for even more space before re-enabling ATR.
9755          * Additionally, we cannot enable ATR as long as we still have TCP SB
9756          * rules active.
9757          */
9758         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9759             pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9760                 i40e_reenable_fdir_atr(pf);
9761
9762         /* if hw had a problem adding a filter, delete it */
9763         if (pf->fd_inv > 0) {
9764                 hlist_for_each_entry_safe(filter, node,
9765                                           &pf->fdir_filter_list, fdir_node)
9766                         if (filter->fd_id == pf->fd_inv)
9767                                 i40e_delete_invalid_filter(pf, filter);
9768         }
9769 }
9770
9771 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9772 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9773 /**
9774  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9775  * @pf: board private structure
9776  **/
9777 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9778 {
9779         unsigned long min_flush_time;
9780         int flush_wait_retry = 50;
9781         bool disable_atr = false;
9782         int fd_room;
9783         int reg;
9784
9785         if (!time_after(jiffies, pf->fd_flush_timestamp +
9786                                  (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9787                 return;
9788
9789         /* If the flush is happening too quick and we have mostly SB rules we
9790          * should not re-enable ATR for some time.
9791          */
9792         min_flush_time = pf->fd_flush_timestamp +
9793                          (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9794         fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9795
9796         if (!(time_after(jiffies, min_flush_time)) &&
9797             (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9798                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9799                         dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9800                 disable_atr = true;
9801         }
9802
9803         pf->fd_flush_timestamp = jiffies;
9804         set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9805         /* flush all filters */
9806         wr32(&pf->hw, I40E_PFQF_CTL_1,
9807              I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9808         i40e_flush(&pf->hw);
9809         pf->fd_flush_cnt++;
9810         pf->fd_add_err = 0;
9811         do {
9812                 /* Check FD flush status every 5-6msec */
9813                 usleep_range(5000, 6000);
9814                 reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9815                 if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9816                         break;
9817         } while (flush_wait_retry--);
9818         if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9819                 dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9820         } else {
9821                 /* replay sideband filters */
9822                 i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9823                 if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9824                         clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9825                 clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9826                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9827                         dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9828         }
9829 }
9830
9831 /**
9832  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9833  * @pf: board private structure
9834  **/
9835 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9836 {
9837         return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9838 }
9839
9840 /**
9841  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9842  * @pf: board private structure
9843  **/
9844 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9845 {
9846
9847         /* if interface is down do nothing */
9848         if (test_bit(__I40E_DOWN, pf->state))
9849                 return;
9850
9851         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9852                 i40e_fdir_flush_and_replay(pf);
9853
9854         i40e_fdir_check_and_reenable(pf);
9855
9856 }
9857
9858 /**
9859  * i40e_vsi_link_event - notify VSI of a link event
9860  * @vsi: vsi to be notified
9861  * @link_up: link up or down
9862  **/
9863 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9864 {
9865         if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9866                 return;
9867
9868         switch (vsi->type) {
9869         case I40E_VSI_MAIN:
9870                 if (!vsi->netdev || !vsi->netdev_registered)
9871                         break;
9872
9873                 if (link_up) {
9874                         netif_carrier_on(vsi->netdev);
9875                         netif_tx_wake_all_queues(vsi->netdev);
9876                 } else {
9877                         netif_carrier_off(vsi->netdev);
9878                         netif_tx_stop_all_queues(vsi->netdev);
9879                 }
9880                 break;
9881
9882         case I40E_VSI_SRIOV:
9883         case I40E_VSI_VMDQ2:
9884         case I40E_VSI_CTRL:
9885         case I40E_VSI_IWARP:
9886         case I40E_VSI_MIRROR:
9887         default:
9888                 /* there is no notification for other VSIs */
9889                 break;
9890         }
9891 }
9892
9893 /**
9894  * i40e_veb_link_event - notify elements on the veb of a link event
9895  * @veb: veb to be notified
9896  * @link_up: link up or down
9897  **/
9898 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9899 {
9900         struct i40e_pf *pf;
9901         int i;
9902
9903         if (!veb || !veb->pf)
9904                 return;
9905         pf = veb->pf;
9906
9907         /* depth first... */
9908         for (i = 0; i < I40E_MAX_VEB; i++)
9909                 if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9910                         i40e_veb_link_event(pf->veb[i], link_up);
9911
9912         /* ... now the local VSIs */
9913         for (i = 0; i < pf->num_alloc_vsi; i++)
9914                 if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9915                         i40e_vsi_link_event(pf->vsi[i], link_up);
9916 }
9917
9918 /**
9919  * i40e_link_event - Update netif_carrier status
9920  * @pf: board private structure
9921  **/
9922 static void i40e_link_event(struct i40e_pf *pf)
9923 {
9924         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9925         u8 new_link_speed, old_link_speed;
9926         bool new_link, old_link;
9927         int status;
9928 #ifdef CONFIG_I40E_DCB
9929         int err;
9930 #endif /* CONFIG_I40E_DCB */
9931
9932         /* set this to force the get_link_status call to refresh state */
9933         pf->hw.phy.get_link_info = true;
9934         old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9935         status = i40e_get_link_status(&pf->hw, &new_link);
9936
9937         /* On success, disable temp link polling */
9938         if (status == 0) {
9939                 clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9940         } else {
9941                 /* Enable link polling temporarily until i40e_get_link_status
9942                  * returns 0
9943                  */
9944                 set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9945                 dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9946                         status);
9947                 return;
9948         }
9949
9950         old_link_speed = pf->hw.phy.link_info_old.link_speed;
9951         new_link_speed = pf->hw.phy.link_info.link_speed;
9952
9953         if (new_link == old_link &&
9954             new_link_speed == old_link_speed &&
9955             (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9956              new_link == netif_carrier_ok(vsi->netdev)))
9957                 return;
9958
9959         i40e_print_link_message(vsi, new_link);
9960
9961         /* Notify the base of the switch tree connected to
9962          * the link.  Floating VEBs are not notified.
9963          */
9964         if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9965                 i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9966         else
9967                 i40e_vsi_link_event(vsi, new_link);
9968
9969         if (pf->vf)
9970                 i40e_vc_notify_link_state(pf);
9971
9972         if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
9973                 i40e_ptp_set_increment(pf);
9974 #ifdef CONFIG_I40E_DCB
9975         if (new_link == old_link)
9976                 return;
9977         /* Not SW DCB so firmware will take care of default settings */
9978         if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9979                 return;
9980
9981         /* We cover here only link down, as after link up in case of SW DCB
9982          * SW LLDP agent will take care of setting it up
9983          */
9984         if (!new_link) {
9985                 dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9986                 memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9987                 err = i40e_dcb_sw_default_config(pf);
9988                 if (err) {
9989                         clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9990                         clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9991                 } else {
9992                         pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9993                                        DCB_CAP_DCBX_VER_IEEE;
9994                         set_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
9995                         clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
9996                 }
9997         }
9998 #endif /* CONFIG_I40E_DCB */
9999 }
10000
10001 /**
10002  * i40e_watchdog_subtask - periodic checks not using event driven response
10003  * @pf: board private structure
10004  **/
10005 static void i40e_watchdog_subtask(struct i40e_pf *pf)
10006 {
10007         int i;
10008
10009         /* if interface is down do nothing */
10010         if (test_bit(__I40E_DOWN, pf->state) ||
10011             test_bit(__I40E_CONFIG_BUSY, pf->state))
10012                 return;
10013
10014         /* make sure we don't do these things too often */
10015         if (time_before(jiffies, (pf->service_timer_previous +
10016                                   pf->service_timer_period)))
10017                 return;
10018         pf->service_timer_previous = jiffies;
10019
10020         if (test_bit(I40E_FLAG_LINK_POLLING_ENA, pf->flags) ||
10021             test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
10022                 i40e_link_event(pf);
10023
10024         /* Update the stats for active netdevs so the network stack
10025          * can look at updated numbers whenever it cares to
10026          */
10027         for (i = 0; i < pf->num_alloc_vsi; i++)
10028                 if (pf->vsi[i] && pf->vsi[i]->netdev)
10029                         i40e_update_stats(pf->vsi[i]);
10030
10031         if (test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags)) {
10032                 /* Update the stats for the active switching components */
10033                 for (i = 0; i < I40E_MAX_VEB; i++)
10034                         if (pf->veb[i])
10035                                 i40e_update_veb_stats(pf->veb[i]);
10036         }
10037
10038         i40e_ptp_rx_hang(pf);
10039         i40e_ptp_tx_hang(pf);
10040 }
10041
10042 /**
10043  * i40e_reset_subtask - Set up for resetting the device and driver
10044  * @pf: board private structure
10045  **/
10046 static void i40e_reset_subtask(struct i40e_pf *pf)
10047 {
10048         u32 reset_flags = 0;
10049
10050         if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
10051                 reset_flags |= BIT(__I40E_REINIT_REQUESTED);
10052                 clear_bit(__I40E_REINIT_REQUESTED, pf->state);
10053         }
10054         if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
10055                 reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
10056                 clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
10057         }
10058         if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
10059                 reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
10060                 clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
10061         }
10062         if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
10063                 reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
10064                 clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
10065         }
10066         if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
10067                 reset_flags |= BIT(__I40E_DOWN_REQUESTED);
10068                 clear_bit(__I40E_DOWN_REQUESTED, pf->state);
10069         }
10070
10071         /* If there's a recovery already waiting, it takes
10072          * precedence before starting a new reset sequence.
10073          */
10074         if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
10075                 i40e_prep_for_reset(pf);
10076                 i40e_reset(pf);
10077                 i40e_rebuild(pf, false, false);
10078         }
10079
10080         /* If we're already down or resetting, just bail */
10081         if (reset_flags &&
10082             !test_bit(__I40E_DOWN, pf->state) &&
10083             !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
10084                 i40e_do_reset(pf, reset_flags, false);
10085         }
10086 }
10087
10088 /**
10089  * i40e_handle_link_event - Handle link event
10090  * @pf: board private structure
10091  * @e: event info posted on ARQ
10092  **/
10093 static void i40e_handle_link_event(struct i40e_pf *pf,
10094                                    struct i40e_arq_event_info *e)
10095 {
10096         struct i40e_aqc_get_link_status *status =
10097                 (struct i40e_aqc_get_link_status *)&e->desc.params.raw;
10098
10099         /* Do a new status request to re-enable LSE reporting
10100          * and load new status information into the hw struct
10101          * This completely ignores any state information
10102          * in the ARQ event info, instead choosing to always
10103          * issue the AQ update link status command.
10104          */
10105         i40e_link_event(pf);
10106
10107         /* Check if module meets thermal requirements */
10108         if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
10109                 dev_err(&pf->pdev->dev,
10110                         "Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
10111                 dev_err(&pf->pdev->dev,
10112                         "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10113         } else {
10114                 /* check for unqualified module, if link is down, suppress
10115                  * the message if link was forced to be down.
10116                  */
10117                 if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
10118                     (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
10119                     (!(status->link_info & I40E_AQ_LINK_UP)) &&
10120                     (!test_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags))) {
10121                         dev_err(&pf->pdev->dev,
10122                                 "Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
10123                         dev_err(&pf->pdev->dev,
10124                                 "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
10125                 }
10126         }
10127 }
10128
10129 /**
10130  * i40e_clean_adminq_subtask - Clean the AdminQ rings
10131  * @pf: board private structure
10132  **/
10133 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
10134 {
10135         struct i40e_arq_event_info event;
10136         struct i40e_hw *hw = &pf->hw;
10137         u16 pending, i = 0;
10138         u16 opcode;
10139         u32 oldval;
10140         int ret;
10141         u32 val;
10142
10143         /* Do not run clean AQ when PF reset fails */
10144         if (test_bit(__I40E_RESET_FAILED, pf->state))
10145                 return;
10146
10147         /* check for error indications */
10148         val = rd32(&pf->hw, I40E_PF_ARQLEN);
10149         oldval = val;
10150         if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
10151                 if (hw->debug_mask & I40E_DEBUG_AQ)
10152                         dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
10153                 val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
10154         }
10155         if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
10156                 if (hw->debug_mask & I40E_DEBUG_AQ)
10157                         dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
10158                 val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
10159                 pf->arq_overflows++;
10160         }
10161         if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
10162                 if (hw->debug_mask & I40E_DEBUG_AQ)
10163                         dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
10164                 val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
10165         }
10166         if (oldval != val)
10167                 wr32(&pf->hw, I40E_PF_ARQLEN, val);
10168
10169         val = rd32(&pf->hw, I40E_PF_ATQLEN);
10170         oldval = val;
10171         if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
10172                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10173                         dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
10174                 val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
10175         }
10176         if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
10177                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10178                         dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10179                 val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10180         }
10181         if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10182                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10183                         dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10184                 val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10185         }
10186         if (oldval != val)
10187                 wr32(&pf->hw, I40E_PF_ATQLEN, val);
10188
10189         event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10190         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10191         if (!event.msg_buf)
10192                 return;
10193
10194         do {
10195                 ret = i40e_clean_arq_element(hw, &event, &pending);
10196                 if (ret == -EALREADY)
10197                         break;
10198                 else if (ret) {
10199                         dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10200                         break;
10201                 }
10202
10203                 opcode = le16_to_cpu(event.desc.opcode);
10204                 switch (opcode) {
10205
10206                 case i40e_aqc_opc_get_link_status:
10207                         rtnl_lock();
10208                         i40e_handle_link_event(pf, &event);
10209                         rtnl_unlock();
10210                         break;
10211                 case i40e_aqc_opc_send_msg_to_pf:
10212                         ret = i40e_vc_process_vf_msg(pf,
10213                                         le16_to_cpu(event.desc.retval),
10214                                         le32_to_cpu(event.desc.cookie_high),
10215                                         le32_to_cpu(event.desc.cookie_low),
10216                                         event.msg_buf,
10217                                         event.msg_len);
10218                         break;
10219                 case i40e_aqc_opc_lldp_update_mib:
10220                         dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10221 #ifdef CONFIG_I40E_DCB
10222                         rtnl_lock();
10223                         i40e_handle_lldp_event(pf, &event);
10224                         rtnl_unlock();
10225 #endif /* CONFIG_I40E_DCB */
10226                         break;
10227                 case i40e_aqc_opc_event_lan_overflow:
10228                         dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10229                         i40e_handle_lan_overflow_event(pf, &event);
10230                         break;
10231                 case i40e_aqc_opc_send_msg_to_peer:
10232                         dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10233                         break;
10234                 case i40e_aqc_opc_nvm_erase:
10235                 case i40e_aqc_opc_nvm_update:
10236                 case i40e_aqc_opc_oem_post_update:
10237                         i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10238                                    "ARQ NVM operation 0x%04x completed\n",
10239                                    opcode);
10240                         break;
10241                 default:
10242                         dev_info(&pf->pdev->dev,
10243                                  "ARQ: Unknown event 0x%04x ignored\n",
10244                                  opcode);
10245                         break;
10246                 }
10247         } while (i++ < I40E_AQ_WORK_LIMIT);
10248
10249         if (i < I40E_AQ_WORK_LIMIT)
10250                 clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10251
10252         /* re-enable Admin queue interrupt cause */
10253         val = rd32(hw, I40E_PFINT_ICR0_ENA);
10254         val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10255         wr32(hw, I40E_PFINT_ICR0_ENA, val);
10256         i40e_flush(hw);
10257
10258         kfree(event.msg_buf);
10259 }
10260
10261 /**
10262  * i40e_verify_eeprom - make sure eeprom is good to use
10263  * @pf: board private structure
10264  **/
10265 static void i40e_verify_eeprom(struct i40e_pf *pf)
10266 {
10267         int err;
10268
10269         err = i40e_diag_eeprom_test(&pf->hw);
10270         if (err) {
10271                 /* retry in case of garbage read */
10272                 err = i40e_diag_eeprom_test(&pf->hw);
10273                 if (err) {
10274                         dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10275                                  err);
10276                         set_bit(__I40E_BAD_EEPROM, pf->state);
10277                 }
10278         }
10279
10280         if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10281                 dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10282                 clear_bit(__I40E_BAD_EEPROM, pf->state);
10283         }
10284 }
10285
10286 /**
10287  * i40e_enable_pf_switch_lb
10288  * @pf: pointer to the PF structure
10289  *
10290  * enable switch loop back or die - no point in a return value
10291  **/
10292 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10293 {
10294         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10295         struct i40e_vsi_context ctxt;
10296         int ret;
10297
10298         ctxt.seid = pf->main_vsi_seid;
10299         ctxt.pf_num = pf->hw.pf_id;
10300         ctxt.vf_num = 0;
10301         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10302         if (ret) {
10303                 dev_info(&pf->pdev->dev,
10304                          "couldn't get PF vsi config, err %pe aq_err %s\n",
10305                          ERR_PTR(ret),
10306                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10307                 return;
10308         }
10309         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10310         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10311         ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10312
10313         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10314         if (ret) {
10315                 dev_info(&pf->pdev->dev,
10316                          "update vsi switch failed, err %pe aq_err %s\n",
10317                          ERR_PTR(ret),
10318                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10319         }
10320 }
10321
10322 /**
10323  * i40e_disable_pf_switch_lb
10324  * @pf: pointer to the PF structure
10325  *
10326  * disable switch loop back or die - no point in a return value
10327  **/
10328 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10329 {
10330         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10331         struct i40e_vsi_context ctxt;
10332         int ret;
10333
10334         ctxt.seid = pf->main_vsi_seid;
10335         ctxt.pf_num = pf->hw.pf_id;
10336         ctxt.vf_num = 0;
10337         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10338         if (ret) {
10339                 dev_info(&pf->pdev->dev,
10340                          "couldn't get PF vsi config, err %pe aq_err %s\n",
10341                          ERR_PTR(ret),
10342                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10343                 return;
10344         }
10345         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10346         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10347         ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10348
10349         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10350         if (ret) {
10351                 dev_info(&pf->pdev->dev,
10352                          "update vsi switch failed, err %pe aq_err %s\n",
10353                          ERR_PTR(ret),
10354                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10355         }
10356 }
10357
10358 /**
10359  * i40e_config_bridge_mode - Configure the HW bridge mode
10360  * @veb: pointer to the bridge instance
10361  *
10362  * Configure the loop back mode for the LAN VSI that is downlink to the
10363  * specified HW bridge instance. It is expected this function is called
10364  * when a new HW bridge is instantiated.
10365  **/
10366 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10367 {
10368         struct i40e_pf *pf = veb->pf;
10369
10370         if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10371                 dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10372                          veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10373         if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10374                 i40e_disable_pf_switch_lb(pf);
10375         else
10376                 i40e_enable_pf_switch_lb(pf);
10377 }
10378
10379 /**
10380  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10381  * @veb: pointer to the VEB instance
10382  *
10383  * This is a recursive function that first builds the attached VSIs then
10384  * recurses in to build the next layer of VEB.  We track the connections
10385  * through our own index numbers because the seid's from the HW could
10386  * change across the reset.
10387  **/
10388 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10389 {
10390         struct i40e_vsi *ctl_vsi = NULL;
10391         struct i40e_pf *pf = veb->pf;
10392         int v, veb_idx;
10393         int ret;
10394
10395         /* build VSI that owns this VEB, temporarily attached to base VEB */
10396         for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10397                 if (pf->vsi[v] &&
10398                     pf->vsi[v]->veb_idx == veb->idx &&
10399                     pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10400                         ctl_vsi = pf->vsi[v];
10401                         break;
10402                 }
10403         }
10404         if (!ctl_vsi) {
10405                 dev_info(&pf->pdev->dev,
10406                          "missing owner VSI for veb_idx %d\n", veb->idx);
10407                 ret = -ENOENT;
10408                 goto end_reconstitute;
10409         }
10410         if (ctl_vsi != pf->vsi[pf->lan_vsi])
10411                 ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10412         ret = i40e_add_vsi(ctl_vsi);
10413         if (ret) {
10414                 dev_info(&pf->pdev->dev,
10415                          "rebuild of veb_idx %d owner VSI failed: %d\n",
10416                          veb->idx, ret);
10417                 goto end_reconstitute;
10418         }
10419         i40e_vsi_reset_stats(ctl_vsi);
10420
10421         /* create the VEB in the switch and move the VSI onto the VEB */
10422         ret = i40e_add_veb(veb, ctl_vsi);
10423         if (ret)
10424                 goto end_reconstitute;
10425
10426         if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
10427                 veb->bridge_mode = BRIDGE_MODE_VEB;
10428         else
10429                 veb->bridge_mode = BRIDGE_MODE_VEPA;
10430         i40e_config_bridge_mode(veb);
10431
10432         /* create the remaining VSIs attached to this VEB */
10433         for (v = 0; v < pf->num_alloc_vsi; v++) {
10434                 if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10435                         continue;
10436
10437                 if (pf->vsi[v]->veb_idx == veb->idx) {
10438                         struct i40e_vsi *vsi = pf->vsi[v];
10439
10440                         vsi->uplink_seid = veb->seid;
10441                         ret = i40e_add_vsi(vsi);
10442                         if (ret) {
10443                                 dev_info(&pf->pdev->dev,
10444                                          "rebuild of vsi_idx %d failed: %d\n",
10445                                          v, ret);
10446                                 goto end_reconstitute;
10447                         }
10448                         i40e_vsi_reset_stats(vsi);
10449                 }
10450         }
10451
10452         /* create any VEBs attached to this VEB - RECURSION */
10453         for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10454                 if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10455                         pf->veb[veb_idx]->uplink_seid = veb->seid;
10456                         ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10457                         if (ret)
10458                                 break;
10459                 }
10460         }
10461
10462 end_reconstitute:
10463         return ret;
10464 }
10465
10466 /**
10467  * i40e_get_capabilities - get info about the HW
10468  * @pf: the PF struct
10469  * @list_type: AQ capability to be queried
10470  **/
10471 static int i40e_get_capabilities(struct i40e_pf *pf,
10472                                  enum i40e_admin_queue_opc list_type)
10473 {
10474         struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10475         u16 data_size;
10476         int buf_len;
10477         int err;
10478
10479         buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10480         do {
10481                 cap_buf = kzalloc(buf_len, GFP_KERNEL);
10482                 if (!cap_buf)
10483                         return -ENOMEM;
10484
10485                 /* this loads the data into the hw struct for us */
10486                 err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10487                                                     &data_size, list_type,
10488                                                     NULL);
10489                 /* data loaded, buffer no longer needed */
10490                 kfree(cap_buf);
10491
10492                 if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10493                         /* retry with a larger buffer */
10494                         buf_len = data_size;
10495                 } else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10496                         dev_info(&pf->pdev->dev,
10497                                  "capability discovery failed, err %pe aq_err %s\n",
10498                                  ERR_PTR(err),
10499                                  i40e_aq_str(&pf->hw,
10500                                              pf->hw.aq.asq_last_status));
10501                         return -ENODEV;
10502                 }
10503         } while (err);
10504
10505         if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10506                 if (list_type == i40e_aqc_opc_list_func_capabilities) {
10507                         dev_info(&pf->pdev->dev,
10508                                  "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",
10509                                  pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10510                                  pf->hw.func_caps.num_msix_vectors,
10511                                  pf->hw.func_caps.num_msix_vectors_vf,
10512                                  pf->hw.func_caps.fd_filters_guaranteed,
10513                                  pf->hw.func_caps.fd_filters_best_effort,
10514                                  pf->hw.func_caps.num_tx_qp,
10515                                  pf->hw.func_caps.num_vsis);
10516                 } else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10517                         dev_info(&pf->pdev->dev,
10518                                  "switch_mode=0x%04x, function_valid=0x%08x\n",
10519                                  pf->hw.dev_caps.switch_mode,
10520                                  pf->hw.dev_caps.valid_functions);
10521                         dev_info(&pf->pdev->dev,
10522                                  "SR-IOV=%d, num_vfs for all function=%u\n",
10523                                  pf->hw.dev_caps.sr_iov_1_1,
10524                                  pf->hw.dev_caps.num_vfs);
10525                         dev_info(&pf->pdev->dev,
10526                                  "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10527                                  pf->hw.dev_caps.num_vsis,
10528                                  pf->hw.dev_caps.num_rx_qp,
10529                                  pf->hw.dev_caps.num_tx_qp);
10530                 }
10531         }
10532         if (list_type == i40e_aqc_opc_list_func_capabilities) {
10533 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10534                        + pf->hw.func_caps.num_vfs)
10535                 if (pf->hw.revision_id == 0 &&
10536                     pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10537                         dev_info(&pf->pdev->dev,
10538                                  "got num_vsis %d, setting num_vsis to %d\n",
10539                                  pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10540                         pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10541                 }
10542         }
10543         return 0;
10544 }
10545
10546 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10547
10548 /**
10549  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10550  * @pf: board private structure
10551  **/
10552 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10553 {
10554         struct i40e_vsi *vsi;
10555
10556         /* quick workaround for an NVM issue that leaves a critical register
10557          * uninitialized
10558          */
10559         if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10560                 static const u32 hkey[] = {
10561                         0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10562                         0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10563                         0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10564                         0x95b3a76d};
10565                 int i;
10566
10567                 for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10568                         wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10569         }
10570
10571         if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
10572                 return;
10573
10574         /* find existing VSI and see if it needs configuring */
10575         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10576
10577         /* create a new VSI if none exists */
10578         if (!vsi) {
10579                 vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10580                                      pf->vsi[pf->lan_vsi]->seid, 0);
10581                 if (!vsi) {
10582                         dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10583                         clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
10584                         set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
10585                         return;
10586                 }
10587         }
10588
10589         i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10590 }
10591
10592 /**
10593  * i40e_fdir_teardown - release the Flow Director resources
10594  * @pf: board private structure
10595  **/
10596 static void i40e_fdir_teardown(struct i40e_pf *pf)
10597 {
10598         struct i40e_vsi *vsi;
10599
10600         i40e_fdir_filter_exit(pf);
10601         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10602         if (vsi)
10603                 i40e_vsi_release(vsi);
10604 }
10605
10606 /**
10607  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10608  * @vsi: PF main vsi
10609  * @seid: seid of main or channel VSIs
10610  *
10611  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10612  * existed before reset
10613  **/
10614 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10615 {
10616         struct i40e_cloud_filter *cfilter;
10617         struct i40e_pf *pf = vsi->back;
10618         struct hlist_node *node;
10619         int ret;
10620
10621         /* Add cloud filters back if they exist */
10622         hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10623                                   cloud_node) {
10624                 if (cfilter->seid != seid)
10625                         continue;
10626
10627                 if (cfilter->dst_port)
10628                         ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10629                                                                 true);
10630                 else
10631                         ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10632
10633                 if (ret) {
10634                         dev_dbg(&pf->pdev->dev,
10635                                 "Failed to rebuild cloud filter, err %pe aq_err %s\n",
10636                                 ERR_PTR(ret),
10637                                 i40e_aq_str(&pf->hw,
10638                                             pf->hw.aq.asq_last_status));
10639                         return ret;
10640                 }
10641         }
10642         return 0;
10643 }
10644
10645 /**
10646  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10647  * @vsi: PF main vsi
10648  *
10649  * Rebuilds channel VSIs if they existed before reset
10650  **/
10651 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10652 {
10653         struct i40e_channel *ch, *ch_tmp;
10654         int ret;
10655
10656         if (list_empty(&vsi->ch_list))
10657                 return 0;
10658
10659         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10660                 if (!ch->initialized)
10661                         break;
10662                 /* Proceed with creation of channel (VMDq2) VSI */
10663                 ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10664                 if (ret) {
10665                         dev_info(&vsi->back->pdev->dev,
10666                                  "failed to rebuild channels using uplink_seid %u\n",
10667                                  vsi->uplink_seid);
10668                         return ret;
10669                 }
10670                 /* Reconfigure TX queues using QTX_CTL register */
10671                 ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10672                 if (ret) {
10673                         dev_info(&vsi->back->pdev->dev,
10674                                  "failed to configure TX rings for channel %u\n",
10675                                  ch->seid);
10676                         return ret;
10677                 }
10678                 /* update 'next_base_queue' */
10679                 vsi->next_base_queue = vsi->next_base_queue +
10680                                                         ch->num_queue_pairs;
10681                 if (ch->max_tx_rate) {
10682                         u64 credits = ch->max_tx_rate;
10683
10684                         if (i40e_set_bw_limit(vsi, ch->seid,
10685                                               ch->max_tx_rate))
10686                                 return -EINVAL;
10687
10688                         do_div(credits, I40E_BW_CREDIT_DIVISOR);
10689                         dev_dbg(&vsi->back->pdev->dev,
10690                                 "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10691                                 ch->max_tx_rate,
10692                                 credits,
10693                                 ch->seid);
10694                 }
10695                 ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10696                 if (ret) {
10697                         dev_dbg(&vsi->back->pdev->dev,
10698                                 "Failed to rebuild cloud filters for channel VSI %u\n",
10699                                 ch->seid);
10700                         return ret;
10701                 }
10702         }
10703         return 0;
10704 }
10705
10706 /**
10707  * i40e_clean_xps_state - clean xps state for every tx_ring
10708  * @vsi: ptr to the VSI
10709  **/
10710 static void i40e_clean_xps_state(struct i40e_vsi *vsi)
10711 {
10712         int i;
10713
10714         if (vsi->tx_rings)
10715                 for (i = 0; i < vsi->num_queue_pairs; i++)
10716                         if (vsi->tx_rings[i])
10717                                 clear_bit(__I40E_TX_XPS_INIT_DONE,
10718                                           vsi->tx_rings[i]->state);
10719 }
10720
10721 /**
10722  * i40e_prep_for_reset - prep for the core to reset
10723  * @pf: board private structure
10724  *
10725  * Close up the VFs and other things in prep for PF Reset.
10726   **/
10727 static void i40e_prep_for_reset(struct i40e_pf *pf)
10728 {
10729         struct i40e_hw *hw = &pf->hw;
10730         int ret = 0;
10731         u32 v;
10732
10733         clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10734         if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10735                 return;
10736         if (i40e_check_asq_alive(&pf->hw))
10737                 i40e_vc_notify_reset(pf);
10738
10739         dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10740
10741         /* quiesce the VSIs and their queues that are not already DOWN */
10742         i40e_pf_quiesce_all_vsi(pf);
10743
10744         for (v = 0; v < pf->num_alloc_vsi; v++) {
10745                 if (pf->vsi[v]) {
10746                         i40e_clean_xps_state(pf->vsi[v]);
10747                         pf->vsi[v]->seid = 0;
10748                 }
10749         }
10750
10751         i40e_shutdown_adminq(&pf->hw);
10752
10753         /* call shutdown HMC */
10754         if (hw->hmc.hmc_obj) {
10755                 ret = i40e_shutdown_lan_hmc(hw);
10756                 if (ret)
10757                         dev_warn(&pf->pdev->dev,
10758                                  "shutdown_lan_hmc failed: %d\n", ret);
10759         }
10760
10761         /* Save the current PTP time so that we can restore the time after the
10762          * reset completes.
10763          */
10764         i40e_ptp_save_hw_time(pf);
10765 }
10766
10767 /**
10768  * i40e_send_version - update firmware with driver version
10769  * @pf: PF struct
10770  */
10771 static void i40e_send_version(struct i40e_pf *pf)
10772 {
10773         struct i40e_driver_version dv;
10774
10775         dv.major_version = 0xff;
10776         dv.minor_version = 0xff;
10777         dv.build_version = 0xff;
10778         dv.subbuild_version = 0;
10779         strscpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10780         i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10781 }
10782
10783 /**
10784  * i40e_get_oem_version - get OEM specific version information
10785  * @hw: pointer to the hardware structure
10786  **/
10787 static void i40e_get_oem_version(struct i40e_hw *hw)
10788 {
10789         u16 block_offset = 0xffff;
10790         u16 block_length = 0;
10791         u16 capabilities = 0;
10792         u16 gen_snap = 0;
10793         u16 release = 0;
10794
10795 #define I40E_SR_NVM_OEM_VERSION_PTR             0x1B
10796 #define I40E_NVM_OEM_LENGTH_OFFSET              0x00
10797 #define I40E_NVM_OEM_CAPABILITIES_OFFSET        0x01
10798 #define I40E_NVM_OEM_GEN_OFFSET                 0x02
10799 #define I40E_NVM_OEM_RELEASE_OFFSET             0x03
10800 #define I40E_NVM_OEM_CAPABILITIES_MASK          0x000F
10801 #define I40E_NVM_OEM_LENGTH                     3
10802
10803         /* Check if pointer to OEM version block is valid. */
10804         i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10805         if (block_offset == 0xffff)
10806                 return;
10807
10808         /* Check if OEM version block has correct length. */
10809         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10810                            &block_length);
10811         if (block_length < I40E_NVM_OEM_LENGTH)
10812                 return;
10813
10814         /* Check if OEM version format is as expected. */
10815         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10816                            &capabilities);
10817         if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10818                 return;
10819
10820         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10821                            &gen_snap);
10822         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10823                            &release);
10824         hw->nvm.oem_ver =
10825                 FIELD_PREP(I40E_OEM_GEN_MASK | I40E_OEM_SNAP_MASK, gen_snap) |
10826                 FIELD_PREP(I40E_OEM_RELEASE_MASK, release);
10827         hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10828 }
10829
10830 /**
10831  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10832  * @pf: board private structure
10833  **/
10834 static int i40e_reset(struct i40e_pf *pf)
10835 {
10836         struct i40e_hw *hw = &pf->hw;
10837         int ret;
10838
10839         ret = i40e_pf_reset(hw);
10840         if (ret) {
10841                 dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10842                 set_bit(__I40E_RESET_FAILED, pf->state);
10843                 clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10844         } else {
10845                 pf->pfr_count++;
10846         }
10847         return ret;
10848 }
10849
10850 /**
10851  * i40e_rebuild - rebuild using a saved config
10852  * @pf: board private structure
10853  * @reinit: if the Main VSI needs to re-initialized.
10854  * @lock_acquired: indicates whether or not the lock has been acquired
10855  * before this function was called.
10856  **/
10857 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10858 {
10859         const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10860         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10861         struct i40e_hw *hw = &pf->hw;
10862         int ret;
10863         u32 val;
10864         int v;
10865
10866         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10867             is_recovery_mode_reported)
10868                 i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10869
10870         if (test_bit(__I40E_DOWN, pf->state) &&
10871             !test_bit(__I40E_RECOVERY_MODE, pf->state))
10872                 goto clear_recovery;
10873         dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10874
10875         /* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10876         ret = i40e_init_adminq(&pf->hw);
10877         if (ret) {
10878                 dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %pe aq_err %s\n",
10879                          ERR_PTR(ret),
10880                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10881                 goto clear_recovery;
10882         }
10883         i40e_get_oem_version(&pf->hw);
10884
10885         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10886                 /* The following delay is necessary for firmware update. */
10887                 mdelay(1000);
10888         }
10889
10890         /* re-verify the eeprom if we just had an EMP reset */
10891         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10892                 i40e_verify_eeprom(pf);
10893
10894         /* if we are going out of or into recovery mode we have to act
10895          * accordingly with regard to resources initialization
10896          * and deinitialization
10897          */
10898         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10899                 if (i40e_get_capabilities(pf,
10900                                           i40e_aqc_opc_list_func_capabilities))
10901                         goto end_unlock;
10902
10903                 if (is_recovery_mode_reported) {
10904                         /* we're staying in recovery mode so we'll reinitialize
10905                          * misc vector here
10906                          */
10907                         if (i40e_setup_misc_vector_for_recovery_mode(pf))
10908                                 goto end_unlock;
10909                 } else {
10910                         if (!lock_acquired)
10911                                 rtnl_lock();
10912                         /* we're going out of recovery mode so we'll free
10913                          * the IRQ allocated specifically for recovery mode
10914                          * and restore the interrupt scheme
10915                          */
10916                         free_irq(pf->pdev->irq, pf);
10917                         i40e_clear_interrupt_scheme(pf);
10918                         if (i40e_restore_interrupt_scheme(pf))
10919                                 goto end_unlock;
10920                 }
10921
10922                 /* tell the firmware that we're starting */
10923                 i40e_send_version(pf);
10924
10925                 /* bail out in case recovery mode was detected, as there is
10926                  * no need for further configuration.
10927                  */
10928                 goto end_unlock;
10929         }
10930
10931         i40e_clear_pxe_mode(hw);
10932         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10933         if (ret)
10934                 goto end_core_reset;
10935
10936         ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10937                                 hw->func_caps.num_rx_qp, 0, 0);
10938         if (ret) {
10939                 dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10940                 goto end_core_reset;
10941         }
10942         ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10943         if (ret) {
10944                 dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10945                 goto end_core_reset;
10946         }
10947
10948 #ifdef CONFIG_I40E_DCB
10949         /* Enable FW to write a default DCB config on link-up
10950          * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10951          * is not supported with new link speed
10952          */
10953         if (i40e_is_tc_mqprio_enabled(pf)) {
10954                 i40e_aq_set_dcb_parameters(hw, false, NULL);
10955         } else {
10956                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10957                     (hw->phy.link_info.link_speed &
10958                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10959                         i40e_aq_set_dcb_parameters(hw, false, NULL);
10960                         dev_warn(&pf->pdev->dev,
10961                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10962                         clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10963                 } else {
10964                         i40e_aq_set_dcb_parameters(hw, true, NULL);
10965                         ret = i40e_init_pf_dcb(pf);
10966                         if (ret) {
10967                                 dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10968                                          ret);
10969                                 clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
10970                                 /* Continue without DCB enabled */
10971                         }
10972                 }
10973         }
10974
10975 #endif /* CONFIG_I40E_DCB */
10976         if (!lock_acquired)
10977                 rtnl_lock();
10978         ret = i40e_setup_pf_switch(pf, reinit, true);
10979         if (ret)
10980                 goto end_unlock;
10981
10982         /* The driver only wants link up/down and module qualification
10983          * reports from firmware.  Note the negative logic.
10984          */
10985         ret = i40e_aq_set_phy_int_mask(&pf->hw,
10986                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
10987                                          I40E_AQ_EVENT_MEDIA_NA |
10988                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10989         if (ret)
10990                 dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
10991                          ERR_PTR(ret),
10992                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10993
10994         /* Rebuild the VSIs and VEBs that existed before reset.
10995          * They are still in our local switch element arrays, so only
10996          * need to rebuild the switch model in the HW.
10997          *
10998          * If there were VEBs but the reconstitution failed, we'll try
10999          * to recover minimal use by getting the basic PF VSI working.
11000          */
11001         if (vsi->uplink_seid != pf->mac_seid) {
11002                 dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
11003                 /* find the one VEB connected to the MAC, and find orphans */
11004                 for (v = 0; v < I40E_MAX_VEB; v++) {
11005                         if (!pf->veb[v])
11006                                 continue;
11007
11008                         if (pf->veb[v]->uplink_seid == pf->mac_seid ||
11009                             pf->veb[v]->uplink_seid == 0) {
11010                                 ret = i40e_reconstitute_veb(pf->veb[v]);
11011
11012                                 if (!ret)
11013                                         continue;
11014
11015                                 /* If Main VEB failed, we're in deep doodoo,
11016                                  * so give up rebuilding the switch and set up
11017                                  * for minimal rebuild of PF VSI.
11018                                  * If orphan failed, we'll report the error
11019                                  * but try to keep going.
11020                                  */
11021                                 if (pf->veb[v]->uplink_seid == pf->mac_seid) {
11022                                         dev_info(&pf->pdev->dev,
11023                                                  "rebuild of switch failed: %d, will try to set up simple PF connection\n",
11024                                                  ret);
11025                                         vsi->uplink_seid = pf->mac_seid;
11026                                         break;
11027                                 } else if (pf->veb[v]->uplink_seid == 0) {
11028                                         dev_info(&pf->pdev->dev,
11029                                                  "rebuild of orphan VEB failed: %d\n",
11030                                                  ret);
11031                                 }
11032                         }
11033                 }
11034         }
11035
11036         if (vsi->uplink_seid == pf->mac_seid) {
11037                 dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
11038                 /* no VEB, so rebuild only the Main VSI */
11039                 ret = i40e_add_vsi(vsi);
11040                 if (ret) {
11041                         dev_info(&pf->pdev->dev,
11042                                  "rebuild of Main VSI failed: %d\n", ret);
11043                         goto end_unlock;
11044                 }
11045         }
11046
11047         if (vsi->mqprio_qopt.max_rate[0]) {
11048                 u64 max_tx_rate = i40e_bw_bytes_to_mbits(vsi,
11049                                                   vsi->mqprio_qopt.max_rate[0]);
11050                 u64 credits = 0;
11051
11052                 ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
11053                 if (ret)
11054                         goto end_unlock;
11055
11056                 credits = max_tx_rate;
11057                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
11058                 dev_dbg(&vsi->back->pdev->dev,
11059                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
11060                         max_tx_rate,
11061                         credits,
11062                         vsi->seid);
11063         }
11064
11065         ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
11066         if (ret)
11067                 goto end_unlock;
11068
11069         /* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
11070          * for this main VSI if they exist
11071          */
11072         ret = i40e_rebuild_channels(vsi);
11073         if (ret)
11074                 goto end_unlock;
11075
11076         /* Reconfigure hardware for allowing smaller MSS in the case
11077          * of TSO, so that we avoid the MDD being fired and causing
11078          * a reset in the case of small MSS+TSO.
11079          */
11080 #define I40E_REG_MSS          0x000E64DC
11081 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
11082 #define I40E_64BYTE_MSS       0x400000
11083         val = rd32(hw, I40E_REG_MSS);
11084         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11085                 val &= ~I40E_REG_MSS_MIN_MASK;
11086                 val |= I40E_64BYTE_MSS;
11087                 wr32(hw, I40E_REG_MSS, val);
11088         }
11089
11090         if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
11091                 msleep(75);
11092                 ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11093                 if (ret)
11094                         dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
11095                                  ERR_PTR(ret),
11096                                  i40e_aq_str(&pf->hw,
11097                                              pf->hw.aq.asq_last_status));
11098         }
11099         /* reinit the misc interrupt */
11100         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
11101                 ret = i40e_setup_misc_vector(pf);
11102                 if (ret)
11103                         goto end_unlock;
11104         }
11105
11106         /* Add a filter to drop all Flow control frames from any VSI from being
11107          * transmitted. By doing so we stop a malicious VF from sending out
11108          * PAUSE or PFC frames and potentially controlling traffic for other
11109          * PF/VF VSIs.
11110          * The FW can still send Flow control frames if enabled.
11111          */
11112         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11113                                                        pf->main_vsi_seid);
11114
11115         /* restart the VSIs that were rebuilt and running before the reset */
11116         i40e_pf_unquiesce_all_vsi(pf);
11117
11118         /* Release the RTNL lock before we start resetting VFs */
11119         if (!lock_acquired)
11120                 rtnl_unlock();
11121
11122         /* Restore promiscuous settings */
11123         ret = i40e_set_promiscuous(pf, pf->cur_promisc);
11124         if (ret)
11125                 dev_warn(&pf->pdev->dev,
11126                          "Failed to restore promiscuous setting: %s, err %pe aq_err %s\n",
11127                          pf->cur_promisc ? "on" : "off",
11128                          ERR_PTR(ret),
11129                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11130
11131         i40e_reset_all_vfs(pf, true);
11132
11133         /* tell the firmware that we're starting */
11134         i40e_send_version(pf);
11135
11136         /* We've already released the lock, so don't do it again */
11137         goto end_core_reset;
11138
11139 end_unlock:
11140         if (!lock_acquired)
11141                 rtnl_unlock();
11142 end_core_reset:
11143         clear_bit(__I40E_RESET_FAILED, pf->state);
11144 clear_recovery:
11145         clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
11146         clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
11147 }
11148
11149 /**
11150  * i40e_reset_and_rebuild - reset and rebuild using a saved config
11151  * @pf: board private structure
11152  * @reinit: if the Main VSI needs to re-initialized.
11153  * @lock_acquired: indicates whether or not the lock has been acquired
11154  * before this function was called.
11155  **/
11156 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
11157                                    bool lock_acquired)
11158 {
11159         int ret;
11160
11161         if (test_bit(__I40E_IN_REMOVE, pf->state))
11162                 return;
11163         /* Now we wait for GRST to settle out.
11164          * We don't have to delete the VEBs or VSIs from the hw switch
11165          * because the reset will make them disappear.
11166          */
11167         ret = i40e_reset(pf);
11168         if (!ret)
11169                 i40e_rebuild(pf, reinit, lock_acquired);
11170 }
11171
11172 /**
11173  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
11174  * @pf: board private structure
11175  *
11176  * Close up the VFs and other things in prep for a Core Reset,
11177  * then get ready to rebuild the world.
11178  * @lock_acquired: indicates whether or not the lock has been acquired
11179  * before this function was called.
11180  **/
11181 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
11182 {
11183         i40e_prep_for_reset(pf);
11184         i40e_reset_and_rebuild(pf, false, lock_acquired);
11185 }
11186
11187 /**
11188  * i40e_handle_mdd_event
11189  * @pf: pointer to the PF structure
11190  *
11191  * Called from the MDD irq handler to identify possibly malicious vfs
11192  **/
11193 static void i40e_handle_mdd_event(struct i40e_pf *pf)
11194 {
11195         struct i40e_hw *hw = &pf->hw;
11196         bool mdd_detected = false;
11197         struct i40e_vf *vf;
11198         u32 reg;
11199         int i;
11200
11201         if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11202                 return;
11203
11204         /* find what triggered the MDD event */
11205         reg = rd32(hw, I40E_GL_MDET_TX);
11206         if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11207                 u8 pf_num = FIELD_GET(I40E_GL_MDET_TX_PF_NUM_MASK, reg);
11208                 u16 vf_num = FIELD_GET(I40E_GL_MDET_TX_VF_NUM_MASK, reg);
11209                 u8 event = FIELD_GET(I40E_GL_MDET_TX_EVENT_MASK, reg);
11210                 u16 queue = FIELD_GET(I40E_GL_MDET_TX_QUEUE_MASK, reg) -
11211                                 pf->hw.func_caps.base_queue;
11212                 if (netif_msg_tx_err(pf))
11213                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11214                                  event, queue, pf_num, vf_num);
11215                 wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11216                 mdd_detected = true;
11217         }
11218         reg = rd32(hw, I40E_GL_MDET_RX);
11219         if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11220                 u8 func = FIELD_GET(I40E_GL_MDET_RX_FUNCTION_MASK, reg);
11221                 u8 event = FIELD_GET(I40E_GL_MDET_RX_EVENT_MASK, reg);
11222                 u16 queue = FIELD_GET(I40E_GL_MDET_RX_QUEUE_MASK, reg) -
11223                                 pf->hw.func_caps.base_queue;
11224                 if (netif_msg_rx_err(pf))
11225                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11226                                  event, queue, func);
11227                 wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11228                 mdd_detected = true;
11229         }
11230
11231         if (mdd_detected) {
11232                 reg = rd32(hw, I40E_PF_MDET_TX);
11233                 if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11234                         wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11235                         dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11236                 }
11237                 reg = rd32(hw, I40E_PF_MDET_RX);
11238                 if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11239                         wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11240                         dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11241                 }
11242         }
11243
11244         /* see if one of the VFs needs its hand slapped */
11245         for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11246                 vf = &(pf->vf[i]);
11247                 reg = rd32(hw, I40E_VP_MDET_TX(i));
11248                 if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11249                         wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11250                         vf->num_mdd_events++;
11251                         dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11252                                  i);
11253                         dev_info(&pf->pdev->dev,
11254                                  "Use PF Control I/F to re-enable the VF\n");
11255                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11256                 }
11257
11258                 reg = rd32(hw, I40E_VP_MDET_RX(i));
11259                 if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11260                         wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11261                         vf->num_mdd_events++;
11262                         dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11263                                  i);
11264                         dev_info(&pf->pdev->dev,
11265                                  "Use PF Control I/F to re-enable the VF\n");
11266                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11267                 }
11268         }
11269
11270         /* re-enable mdd interrupt cause */
11271         clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11272         reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11273         reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11274         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11275         i40e_flush(hw);
11276 }
11277
11278 /**
11279  * i40e_service_task - Run the driver's async subtasks
11280  * @work: pointer to work_struct containing our data
11281  **/
11282 static void i40e_service_task(struct work_struct *work)
11283 {
11284         struct i40e_pf *pf = container_of(work,
11285                                           struct i40e_pf,
11286                                           service_task);
11287         unsigned long start_time = jiffies;
11288
11289         /* don't bother with service tasks if a reset is in progress */
11290         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11291             test_bit(__I40E_SUSPENDED, pf->state))
11292                 return;
11293
11294         if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11295                 return;
11296
11297         if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11298                 i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11299                 i40e_sync_filters_subtask(pf);
11300                 i40e_reset_subtask(pf);
11301                 i40e_handle_mdd_event(pf);
11302                 i40e_vc_process_vflr_event(pf);
11303                 i40e_watchdog_subtask(pf);
11304                 i40e_fdir_reinit_subtask(pf);
11305                 if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11306                         /* Client subtask will reopen next time through. */
11307                         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11308                                                            true);
11309                 } else {
11310                         i40e_client_subtask(pf);
11311                         if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11312                                                pf->state))
11313                                 i40e_notify_client_of_l2_param_changes(
11314                                                                 pf->vsi[pf->lan_vsi]);
11315                 }
11316                 i40e_sync_filters_subtask(pf);
11317         } else {
11318                 i40e_reset_subtask(pf);
11319         }
11320
11321         i40e_clean_adminq_subtask(pf);
11322
11323         /* flush memory to make sure state is correct before next watchdog */
11324         smp_mb__before_atomic();
11325         clear_bit(__I40E_SERVICE_SCHED, pf->state);
11326
11327         /* If the tasks have taken longer than one timer cycle or there
11328          * is more work to be done, reschedule the service task now
11329          * rather than wait for the timer to tick again.
11330          */
11331         if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11332             test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)             ||
11333             test_bit(__I40E_MDD_EVENT_PENDING, pf->state)                ||
11334             test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11335                 i40e_service_event_schedule(pf);
11336 }
11337
11338 /**
11339  * i40e_service_timer - timer callback
11340  * @t: timer list pointer
11341  **/
11342 static void i40e_service_timer(struct timer_list *t)
11343 {
11344         struct i40e_pf *pf = from_timer(pf, t, service_timer);
11345
11346         mod_timer(&pf->service_timer,
11347                   round_jiffies(jiffies + pf->service_timer_period));
11348         i40e_service_event_schedule(pf);
11349 }
11350
11351 /**
11352  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11353  * @vsi: the VSI being configured
11354  **/
11355 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11356 {
11357         struct i40e_pf *pf = vsi->back;
11358
11359         switch (vsi->type) {
11360         case I40E_VSI_MAIN:
11361                 vsi->alloc_queue_pairs = pf->num_lan_qps;
11362                 if (!vsi->num_tx_desc)
11363                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11364                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11365                 if (!vsi->num_rx_desc)
11366                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11367                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11368                 if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11369                         vsi->num_q_vectors = pf->num_lan_msix;
11370                 else
11371                         vsi->num_q_vectors = 1;
11372
11373                 break;
11374
11375         case I40E_VSI_FDIR:
11376                 vsi->alloc_queue_pairs = 1;
11377                 vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11378                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
11379                 vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11380                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
11381                 vsi->num_q_vectors = pf->num_fdsb_msix;
11382                 break;
11383
11384         case I40E_VSI_VMDQ2:
11385                 vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11386                 if (!vsi->num_tx_desc)
11387                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11388                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11389                 if (!vsi->num_rx_desc)
11390                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11391                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11392                 vsi->num_q_vectors = pf->num_vmdq_msix;
11393                 break;
11394
11395         case I40E_VSI_SRIOV:
11396                 vsi->alloc_queue_pairs = pf->num_vf_qps;
11397                 if (!vsi->num_tx_desc)
11398                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11399                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11400                 if (!vsi->num_rx_desc)
11401                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11402                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11403                 break;
11404
11405         default:
11406                 WARN_ON(1);
11407                 return -ENODATA;
11408         }
11409
11410         if (is_kdump_kernel()) {
11411                 vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11412                 vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11413         }
11414
11415         return 0;
11416 }
11417
11418 /**
11419  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11420  * @vsi: VSI pointer
11421  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11422  *
11423  * On error: returns error code (negative)
11424  * On success: returns 0
11425  **/
11426 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11427 {
11428         struct i40e_ring **next_rings;
11429         int size;
11430         int ret = 0;
11431
11432         /* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11433         size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11434                (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11435         vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11436         if (!vsi->tx_rings)
11437                 return -ENOMEM;
11438         next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11439         if (i40e_enabled_xdp_vsi(vsi)) {
11440                 vsi->xdp_rings = next_rings;
11441                 next_rings += vsi->alloc_queue_pairs;
11442         }
11443         vsi->rx_rings = next_rings;
11444
11445         if (alloc_qvectors) {
11446                 /* allocate memory for q_vector pointers */
11447                 size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11448                 vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11449                 if (!vsi->q_vectors) {
11450                         ret = -ENOMEM;
11451                         goto err_vectors;
11452                 }
11453         }
11454         return ret;
11455
11456 err_vectors:
11457         kfree(vsi->tx_rings);
11458         return ret;
11459 }
11460
11461 /**
11462  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11463  * @pf: board private structure
11464  * @type: type of VSI
11465  *
11466  * On error: returns error code (negative)
11467  * On success: returns vsi index in PF (positive)
11468  **/
11469 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11470 {
11471         int ret = -ENODEV;
11472         struct i40e_vsi *vsi;
11473         int vsi_idx;
11474         int i;
11475
11476         /* Need to protect the allocation of the VSIs at the PF level */
11477         mutex_lock(&pf->switch_mutex);
11478
11479         /* VSI list may be fragmented if VSI creation/destruction has
11480          * been happening.  We can afford to do a quick scan to look
11481          * for any free VSIs in the list.
11482          *
11483          * find next empty vsi slot, looping back around if necessary
11484          */
11485         i = pf->next_vsi;
11486         while (i < pf->num_alloc_vsi && pf->vsi[i])
11487                 i++;
11488         if (i >= pf->num_alloc_vsi) {
11489                 i = 0;
11490                 while (i < pf->next_vsi && pf->vsi[i])
11491                         i++;
11492         }
11493
11494         if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11495                 vsi_idx = i;             /* Found one! */
11496         } else {
11497                 ret = -ENODEV;
11498                 goto unlock_pf;  /* out of VSI slots! */
11499         }
11500         pf->next_vsi = ++i;
11501
11502         vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11503         if (!vsi) {
11504                 ret = -ENOMEM;
11505                 goto unlock_pf;
11506         }
11507         vsi->type = type;
11508         vsi->back = pf;
11509         set_bit(__I40E_VSI_DOWN, vsi->state);
11510         vsi->flags = 0;
11511         vsi->idx = vsi_idx;
11512         vsi->int_rate_limit = 0;
11513         vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11514                                 pf->rss_table_size : 64;
11515         vsi->netdev_registered = false;
11516         vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11517         hash_init(vsi->mac_filter_hash);
11518         vsi->irqs_ready = false;
11519
11520         if (type == I40E_VSI_MAIN) {
11521                 vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11522                 if (!vsi->af_xdp_zc_qps)
11523                         goto err_rings;
11524         }
11525
11526         ret = i40e_set_num_rings_in_vsi(vsi);
11527         if (ret)
11528                 goto err_rings;
11529
11530         ret = i40e_vsi_alloc_arrays(vsi, true);
11531         if (ret)
11532                 goto err_rings;
11533
11534         /* Setup default MSIX irq handler for VSI */
11535         i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11536
11537         /* Initialize VSI lock */
11538         spin_lock_init(&vsi->mac_filter_hash_lock);
11539         pf->vsi[vsi_idx] = vsi;
11540         ret = vsi_idx;
11541         goto unlock_pf;
11542
11543 err_rings:
11544         bitmap_free(vsi->af_xdp_zc_qps);
11545         pf->next_vsi = i - 1;
11546         kfree(vsi);
11547 unlock_pf:
11548         mutex_unlock(&pf->switch_mutex);
11549         return ret;
11550 }
11551
11552 /**
11553  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11554  * @vsi: VSI pointer
11555  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11556  *
11557  * On error: returns error code (negative)
11558  * On success: returns 0
11559  **/
11560 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11561 {
11562         /* free the ring and vector containers */
11563         if (free_qvectors) {
11564                 kfree(vsi->q_vectors);
11565                 vsi->q_vectors = NULL;
11566         }
11567         kfree(vsi->tx_rings);
11568         vsi->tx_rings = NULL;
11569         vsi->rx_rings = NULL;
11570         vsi->xdp_rings = NULL;
11571 }
11572
11573 /**
11574  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11575  * and lookup table
11576  * @vsi: Pointer to VSI structure
11577  */
11578 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11579 {
11580         if (!vsi)
11581                 return;
11582
11583         kfree(vsi->rss_hkey_user);
11584         vsi->rss_hkey_user = NULL;
11585
11586         kfree(vsi->rss_lut_user);
11587         vsi->rss_lut_user = NULL;
11588 }
11589
11590 /**
11591  * i40e_vsi_clear - Deallocate the VSI provided
11592  * @vsi: the VSI being un-configured
11593  **/
11594 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11595 {
11596         struct i40e_pf *pf;
11597
11598         if (!vsi)
11599                 return 0;
11600
11601         if (!vsi->back)
11602                 goto free_vsi;
11603         pf = vsi->back;
11604
11605         mutex_lock(&pf->switch_mutex);
11606         if (!pf->vsi[vsi->idx]) {
11607                 dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11608                         vsi->idx, vsi->idx, vsi->type);
11609                 goto unlock_vsi;
11610         }
11611
11612         if (pf->vsi[vsi->idx] != vsi) {
11613                 dev_err(&pf->pdev->dev,
11614                         "pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11615                         pf->vsi[vsi->idx]->idx,
11616                         pf->vsi[vsi->idx]->type,
11617                         vsi->idx, vsi->type);
11618                 goto unlock_vsi;
11619         }
11620
11621         /* updates the PF for this cleared vsi */
11622         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11623         i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11624
11625         bitmap_free(vsi->af_xdp_zc_qps);
11626         i40e_vsi_free_arrays(vsi, true);
11627         i40e_clear_rss_config_user(vsi);
11628
11629         pf->vsi[vsi->idx] = NULL;
11630         if (vsi->idx < pf->next_vsi)
11631                 pf->next_vsi = vsi->idx;
11632
11633 unlock_vsi:
11634         mutex_unlock(&pf->switch_mutex);
11635 free_vsi:
11636         kfree(vsi);
11637
11638         return 0;
11639 }
11640
11641 /**
11642  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11643  * @vsi: the VSI being cleaned
11644  **/
11645 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11646 {
11647         int i;
11648
11649         if (vsi->tx_rings && vsi->tx_rings[0]) {
11650                 for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11651                         kfree_rcu(vsi->tx_rings[i], rcu);
11652                         WRITE_ONCE(vsi->tx_rings[i], NULL);
11653                         WRITE_ONCE(vsi->rx_rings[i], NULL);
11654                         if (vsi->xdp_rings)
11655                                 WRITE_ONCE(vsi->xdp_rings[i], NULL);
11656                 }
11657         }
11658 }
11659
11660 /**
11661  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11662  * @vsi: the VSI being configured
11663  **/
11664 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11665 {
11666         int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11667         struct i40e_pf *pf = vsi->back;
11668         struct i40e_ring *ring;
11669
11670         /* Set basic values in the rings to be used later during open() */
11671         for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11672                 /* allocate space for both Tx and Rx in one shot */
11673                 ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11674                 if (!ring)
11675                         goto err_out;
11676
11677                 ring->queue_index = i;
11678                 ring->reg_idx = vsi->base_queue + i;
11679                 ring->ring_active = false;
11680                 ring->vsi = vsi;
11681                 ring->netdev = vsi->netdev;
11682                 ring->dev = &pf->pdev->dev;
11683                 ring->count = vsi->num_tx_desc;
11684                 ring->size = 0;
11685                 ring->dcb_tc = 0;
11686                 if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11687                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11688                 ring->itr_setting = pf->tx_itr_default;
11689                 WRITE_ONCE(vsi->tx_rings[i], ring++);
11690
11691                 if (!i40e_enabled_xdp_vsi(vsi))
11692                         goto setup_rx;
11693
11694                 ring->queue_index = vsi->alloc_queue_pairs + i;
11695                 ring->reg_idx = vsi->base_queue + ring->queue_index;
11696                 ring->ring_active = false;
11697                 ring->vsi = vsi;
11698                 ring->netdev = NULL;
11699                 ring->dev = &pf->pdev->dev;
11700                 ring->count = vsi->num_tx_desc;
11701                 ring->size = 0;
11702                 ring->dcb_tc = 0;
11703                 if (test_bit(I40E_HW_CAP_WB_ON_ITR, vsi->back->hw.caps))
11704                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11705                 set_ring_xdp(ring);
11706                 ring->itr_setting = pf->tx_itr_default;
11707                 WRITE_ONCE(vsi->xdp_rings[i], ring++);
11708
11709 setup_rx:
11710                 ring->queue_index = i;
11711                 ring->reg_idx = vsi->base_queue + i;
11712                 ring->ring_active = false;
11713                 ring->vsi = vsi;
11714                 ring->netdev = vsi->netdev;
11715                 ring->dev = &pf->pdev->dev;
11716                 ring->count = vsi->num_rx_desc;
11717                 ring->size = 0;
11718                 ring->dcb_tc = 0;
11719                 ring->itr_setting = pf->rx_itr_default;
11720                 WRITE_ONCE(vsi->rx_rings[i], ring);
11721         }
11722
11723         return 0;
11724
11725 err_out:
11726         i40e_vsi_clear_rings(vsi);
11727         return -ENOMEM;
11728 }
11729
11730 /**
11731  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11732  * @pf: board private structure
11733  * @vectors: the number of MSI-X vectors to request
11734  *
11735  * Returns the number of vectors reserved, or error
11736  **/
11737 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11738 {
11739         vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11740                                         I40E_MIN_MSIX, vectors);
11741         if (vectors < 0) {
11742                 dev_info(&pf->pdev->dev,
11743                          "MSI-X vector reservation failed: %d\n", vectors);
11744                 vectors = 0;
11745         }
11746
11747         return vectors;
11748 }
11749
11750 /**
11751  * i40e_init_msix - Setup the MSIX capability
11752  * @pf: board private structure
11753  *
11754  * Work with the OS to set up the MSIX vectors needed.
11755  *
11756  * Returns the number of vectors reserved or negative on failure
11757  **/
11758 static int i40e_init_msix(struct i40e_pf *pf)
11759 {
11760         struct i40e_hw *hw = &pf->hw;
11761         int cpus, extra_vectors;
11762         int vectors_left;
11763         int v_budget, i;
11764         int v_actual;
11765         int iwarp_requested = 0;
11766
11767         if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
11768                 return -ENODEV;
11769
11770         /* The number of vectors we'll request will be comprised of:
11771          *   - Add 1 for "other" cause for Admin Queue events, etc.
11772          *   - The number of LAN queue pairs
11773          *      - Queues being used for RSS.
11774          *              We don't need as many as max_rss_size vectors.
11775          *              use rss_size instead in the calculation since that
11776          *              is governed by number of cpus in the system.
11777          *      - assumes symmetric Tx/Rx pairing
11778          *   - The number of VMDq pairs
11779          *   - The CPU count within the NUMA node if iWARP is enabled
11780          * Once we count this up, try the request.
11781          *
11782          * If we can't get what we want, we'll simplify to nearly nothing
11783          * and try again.  If that still fails, we punt.
11784          */
11785         vectors_left = hw->func_caps.num_msix_vectors;
11786         v_budget = 0;
11787
11788         /* reserve one vector for miscellaneous handler */
11789         if (vectors_left) {
11790                 v_budget++;
11791                 vectors_left--;
11792         }
11793
11794         /* reserve some vectors for the main PF traffic queues. Initially we
11795          * only reserve at most 50% of the available vectors, in the case that
11796          * the number of online CPUs is large. This ensures that we can enable
11797          * extra features as well. Once we've enabled the other features, we
11798          * will use any remaining vectors to reach as close as we can to the
11799          * number of online CPUs.
11800          */
11801         cpus = num_online_cpus();
11802         pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11803         vectors_left -= pf->num_lan_msix;
11804
11805         /* reserve one vector for sideband flow director */
11806         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11807                 if (vectors_left) {
11808                         pf->num_fdsb_msix = 1;
11809                         v_budget++;
11810                         vectors_left--;
11811                 } else {
11812                         pf->num_fdsb_msix = 0;
11813                 }
11814         }
11815
11816         /* can we reserve enough for iWARP? */
11817         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11818                 iwarp_requested = pf->num_iwarp_msix;
11819
11820                 if (!vectors_left)
11821                         pf->num_iwarp_msix = 0;
11822                 else if (vectors_left < pf->num_iwarp_msix)
11823                         pf->num_iwarp_msix = 1;
11824                 v_budget += pf->num_iwarp_msix;
11825                 vectors_left -= pf->num_iwarp_msix;
11826         }
11827
11828         /* any vectors left over go for VMDq support */
11829         if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags)) {
11830                 if (!vectors_left) {
11831                         pf->num_vmdq_msix = 0;
11832                         pf->num_vmdq_qps = 0;
11833                 } else {
11834                         int vmdq_vecs_wanted =
11835                                 pf->num_vmdq_vsis * pf->num_vmdq_qps;
11836                         int vmdq_vecs =
11837                                 min_t(int, vectors_left, vmdq_vecs_wanted);
11838
11839                         /* if we're short on vectors for what's desired, we limit
11840                          * the queues per vmdq.  If this is still more than are
11841                          * available, the user will need to change the number of
11842                          * queues/vectors used by the PF later with the ethtool
11843                          * channels command
11844                          */
11845                         if (vectors_left < vmdq_vecs_wanted) {
11846                                 pf->num_vmdq_qps = 1;
11847                                 vmdq_vecs_wanted = pf->num_vmdq_vsis;
11848                                 vmdq_vecs = min_t(int,
11849                                                   vectors_left,
11850                                                   vmdq_vecs_wanted);
11851                         }
11852                         pf->num_vmdq_msix = pf->num_vmdq_qps;
11853
11854                         v_budget += vmdq_vecs;
11855                         vectors_left -= vmdq_vecs;
11856                 }
11857         }
11858
11859         /* On systems with a large number of SMP cores, we previously limited
11860          * the number of vectors for num_lan_msix to be at most 50% of the
11861          * available vectors, to allow for other features. Now, we add back
11862          * the remaining vectors. However, we ensure that the total
11863          * num_lan_msix will not exceed num_online_cpus(). To do this, we
11864          * calculate the number of vectors we can add without going over the
11865          * cap of CPUs. For systems with a small number of CPUs this will be
11866          * zero.
11867          */
11868         extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11869         pf->num_lan_msix += extra_vectors;
11870         vectors_left -= extra_vectors;
11871
11872         WARN(vectors_left < 0,
11873              "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11874
11875         v_budget += pf->num_lan_msix;
11876         pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11877                                    GFP_KERNEL);
11878         if (!pf->msix_entries)
11879                 return -ENOMEM;
11880
11881         for (i = 0; i < v_budget; i++)
11882                 pf->msix_entries[i].entry = i;
11883         v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11884
11885         if (v_actual < I40E_MIN_MSIX) {
11886                 clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
11887                 kfree(pf->msix_entries);
11888                 pf->msix_entries = NULL;
11889                 pci_disable_msix(pf->pdev);
11890                 return -ENODEV;
11891
11892         } else if (v_actual == I40E_MIN_MSIX) {
11893                 /* Adjust for minimal MSIX use */
11894                 pf->num_vmdq_vsis = 0;
11895                 pf->num_vmdq_qps = 0;
11896                 pf->num_lan_qps = 1;
11897                 pf->num_lan_msix = 1;
11898
11899         } else if (v_actual != v_budget) {
11900                 /* If we have limited resources, we will start with no vectors
11901                  * for the special features and then allocate vectors to some
11902                  * of these features based on the policy and at the end disable
11903                  * the features that did not get any vectors.
11904                  */
11905                 int vec;
11906
11907                 dev_info(&pf->pdev->dev,
11908                          "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11909                          v_actual, v_budget);
11910                 /* reserve the misc vector */
11911                 vec = v_actual - 1;
11912
11913                 /* Scale vector usage down */
11914                 pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11915                 pf->num_vmdq_vsis = 1;
11916                 pf->num_vmdq_qps = 1;
11917
11918                 /* partition out the remaining vectors */
11919                 switch (vec) {
11920                 case 2:
11921                         pf->num_lan_msix = 1;
11922                         break;
11923                 case 3:
11924                         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11925                                 pf->num_lan_msix = 1;
11926                                 pf->num_iwarp_msix = 1;
11927                         } else {
11928                                 pf->num_lan_msix = 2;
11929                         }
11930                         break;
11931                 default:
11932                         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
11933                                 pf->num_iwarp_msix = min_t(int, (vec / 3),
11934                                                  iwarp_requested);
11935                                 pf->num_vmdq_vsis = min_t(int, (vec / 3),
11936                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11937                         } else {
11938                                 pf->num_vmdq_vsis = min_t(int, (vec / 2),
11939                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11940                         }
11941                         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
11942                                 pf->num_fdsb_msix = 1;
11943                                 vec--;
11944                         }
11945                         pf->num_lan_msix = min_t(int,
11946                                (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11947                                                               pf->num_lan_msix);
11948                         pf->num_lan_qps = pf->num_lan_msix;
11949                         break;
11950                 }
11951         }
11952
11953         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) && pf->num_fdsb_msix == 0) {
11954                 dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11955                 clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
11956                 set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
11957         }
11958         if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) && pf->num_vmdq_msix == 0) {
11959                 dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11960                 clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
11961         }
11962
11963         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags) &&
11964             pf->num_iwarp_msix == 0) {
11965                 dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11966                 clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
11967         }
11968         i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11969                    "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11970                    pf->num_lan_msix,
11971                    pf->num_vmdq_msix * pf->num_vmdq_vsis,
11972                    pf->num_fdsb_msix,
11973                    pf->num_iwarp_msix);
11974
11975         return v_actual;
11976 }
11977
11978 /**
11979  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11980  * @vsi: the VSI being configured
11981  * @v_idx: index of the vector in the vsi struct
11982  *
11983  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11984  **/
11985 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11986 {
11987         struct i40e_q_vector *q_vector;
11988
11989         /* allocate q_vector */
11990         q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11991         if (!q_vector)
11992                 return -ENOMEM;
11993
11994         q_vector->vsi = vsi;
11995         q_vector->v_idx = v_idx;
11996         cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11997
11998         if (vsi->netdev)
11999                 netif_napi_add(vsi->netdev, &q_vector->napi, i40e_napi_poll);
12000
12001         /* tie q_vector and vsi together */
12002         vsi->q_vectors[v_idx] = q_vector;
12003
12004         return 0;
12005 }
12006
12007 /**
12008  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
12009  * @vsi: the VSI being configured
12010  *
12011  * We allocate one q_vector per queue interrupt.  If allocation fails we
12012  * return -ENOMEM.
12013  **/
12014 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
12015 {
12016         struct i40e_pf *pf = vsi->back;
12017         int err, v_idx, num_q_vectors;
12018
12019         /* if not MSIX, give the one vector only to the LAN VSI */
12020         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12021                 num_q_vectors = vsi->num_q_vectors;
12022         else if (vsi == pf->vsi[pf->lan_vsi])
12023                 num_q_vectors = 1;
12024         else
12025                 return -EINVAL;
12026
12027         for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
12028                 err = i40e_vsi_alloc_q_vector(vsi, v_idx);
12029                 if (err)
12030                         goto err_out;
12031         }
12032
12033         return 0;
12034
12035 err_out:
12036         while (v_idx--)
12037                 i40e_free_q_vector(vsi, v_idx);
12038
12039         return err;
12040 }
12041
12042 /**
12043  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
12044  * @pf: board private structure to initialize
12045  **/
12046 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
12047 {
12048         int vectors = 0;
12049         ssize_t size;
12050
12051         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12052                 vectors = i40e_init_msix(pf);
12053                 if (vectors < 0) {
12054                         clear_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12055                         clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12056                         clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
12057                         clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
12058                         clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
12059                         clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12060                         clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12061                         clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12062                         clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12063                         set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12064
12065                         /* rework the queue expectations without MSIX */
12066                         i40e_determine_queue_usage(pf);
12067                 }
12068         }
12069
12070         if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
12071             test_bit(I40E_FLAG_MSI_ENA, pf->flags)) {
12072                 dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
12073                 vectors = pci_enable_msi(pf->pdev);
12074                 if (vectors < 0) {
12075                         dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
12076                                  vectors);
12077                         clear_bit(I40E_FLAG_MSI_ENA, pf->flags);
12078                 }
12079                 vectors = 1;  /* one MSI or Legacy vector */
12080         }
12081
12082         if (!test_bit(I40E_FLAG_MSI_ENA, pf->flags) &&
12083             !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
12084                 dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
12085
12086         /* set up vector assignment tracking */
12087         size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
12088         pf->irq_pile = kzalloc(size, GFP_KERNEL);
12089         if (!pf->irq_pile)
12090                 return -ENOMEM;
12091
12092         pf->irq_pile->num_entries = vectors;
12093
12094         /* track first vector for misc interrupts, ignore return */
12095         (void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
12096
12097         return 0;
12098 }
12099
12100 /**
12101  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
12102  * @pf: private board data structure
12103  *
12104  * Restore the interrupt scheme that was cleared when we suspended the
12105  * device. This should be called during resume to re-allocate the q_vectors
12106  * and reacquire IRQs.
12107  */
12108 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
12109 {
12110         int err, i;
12111
12112         /* We cleared the MSI and MSI-X flags when disabling the old interrupt
12113          * scheme. We need to re-enabled them here in order to attempt to
12114          * re-acquire the MSI or MSI-X vectors
12115          */
12116         set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12117         set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12118
12119         err = i40e_init_interrupt_scheme(pf);
12120         if (err)
12121                 return err;
12122
12123         /* Now that we've re-acquired IRQs, we need to remap the vectors and
12124          * rings together again.
12125          */
12126         for (i = 0; i < pf->num_alloc_vsi; i++) {
12127                 if (pf->vsi[i]) {
12128                         err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
12129                         if (err)
12130                                 goto err_unwind;
12131                         i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
12132                 }
12133         }
12134
12135         err = i40e_setup_misc_vector(pf);
12136         if (err)
12137                 goto err_unwind;
12138
12139         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags))
12140                 i40e_client_update_msix_info(pf);
12141
12142         return 0;
12143
12144 err_unwind:
12145         while (i--) {
12146                 if (pf->vsi[i])
12147                         i40e_vsi_free_q_vectors(pf->vsi[i]);
12148         }
12149
12150         return err;
12151 }
12152
12153 /**
12154  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
12155  * non queue events in recovery mode
12156  * @pf: board private structure
12157  *
12158  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
12159  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
12160  * This is handled differently than in recovery mode since no Tx/Rx resources
12161  * are being allocated.
12162  **/
12163 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
12164 {
12165         int err;
12166
12167         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
12168                 err = i40e_setup_misc_vector(pf);
12169
12170                 if (err) {
12171                         dev_info(&pf->pdev->dev,
12172                                  "MSI-X misc vector request failed, error %d\n",
12173                                  err);
12174                         return err;
12175                 }
12176         } else {
12177                 u32 flags = test_bit(I40E_FLAG_MSI_ENA, pf->flags) ? 0 : IRQF_SHARED;
12178
12179                 err = request_irq(pf->pdev->irq, i40e_intr, flags,
12180                                   pf->int_name, pf);
12181
12182                 if (err) {
12183                         dev_info(&pf->pdev->dev,
12184                                  "MSI/legacy misc vector request failed, error %d\n",
12185                                  err);
12186                         return err;
12187                 }
12188                 i40e_enable_misc_int_causes(pf);
12189                 i40e_irq_dynamic_enable_icr0(pf);
12190         }
12191
12192         return 0;
12193 }
12194
12195 /**
12196  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12197  * @pf: board private structure
12198  *
12199  * This sets up the handler for MSIX 0, which is used to manage the
12200  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12201  * when in MSI or Legacy interrupt mode.
12202  **/
12203 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12204 {
12205         struct i40e_hw *hw = &pf->hw;
12206         int err = 0;
12207
12208         /* Only request the IRQ once, the first time through. */
12209         if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12210                 err = request_irq(pf->msix_entries[0].vector,
12211                                   i40e_intr, 0, pf->int_name, pf);
12212                 if (err) {
12213                         clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12214                         dev_info(&pf->pdev->dev,
12215                                  "request_irq for %s failed: %d\n",
12216                                  pf->int_name, err);
12217                         return -EFAULT;
12218                 }
12219         }
12220
12221         i40e_enable_misc_int_causes(pf);
12222
12223         /* associate no queues to the misc vector */
12224         wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12225         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12226
12227         i40e_flush(hw);
12228
12229         i40e_irq_dynamic_enable_icr0(pf);
12230
12231         return err;
12232 }
12233
12234 /**
12235  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12236  * @vsi: Pointer to vsi structure
12237  * @seed: Buffter to store the hash keys
12238  * @lut: Buffer to store the lookup table entries
12239  * @lut_size: Size of buffer to store the lookup table entries
12240  *
12241  * Return 0 on success, negative on failure
12242  */
12243 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12244                            u8 *lut, u16 lut_size)
12245 {
12246         struct i40e_pf *pf = vsi->back;
12247         struct i40e_hw *hw = &pf->hw;
12248         int ret = 0;
12249
12250         if (seed) {
12251                 ret = i40e_aq_get_rss_key(hw, vsi->id,
12252                         (struct i40e_aqc_get_set_rss_key_data *)seed);
12253                 if (ret) {
12254                         dev_info(&pf->pdev->dev,
12255                                  "Cannot get RSS key, err %pe aq_err %s\n",
12256                                  ERR_PTR(ret),
12257                                  i40e_aq_str(&pf->hw,
12258                                              pf->hw.aq.asq_last_status));
12259                         return ret;
12260                 }
12261         }
12262
12263         if (lut) {
12264                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
12265
12266                 ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12267                 if (ret) {
12268                         dev_info(&pf->pdev->dev,
12269                                  "Cannot get RSS lut, err %pe aq_err %s\n",
12270                                  ERR_PTR(ret),
12271                                  i40e_aq_str(&pf->hw,
12272                                              pf->hw.aq.asq_last_status));
12273                         return ret;
12274                 }
12275         }
12276
12277         return ret;
12278 }
12279
12280 /**
12281  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12282  * @vsi: Pointer to vsi structure
12283  * @seed: RSS hash seed
12284  * @lut: Lookup table
12285  * @lut_size: Lookup table size
12286  *
12287  * Returns 0 on success, negative on failure
12288  **/
12289 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12290                                const u8 *lut, u16 lut_size)
12291 {
12292         struct i40e_pf *pf = vsi->back;
12293         struct i40e_hw *hw = &pf->hw;
12294         u16 vf_id = vsi->vf_id;
12295         u8 i;
12296
12297         /* Fill out hash function seed */
12298         if (seed) {
12299                 u32 *seed_dw = (u32 *)seed;
12300
12301                 if (vsi->type == I40E_VSI_MAIN) {
12302                         for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12303                                 wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12304                 } else if (vsi->type == I40E_VSI_SRIOV) {
12305                         for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12306                                 wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12307                 } else {
12308                         dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12309                 }
12310         }
12311
12312         if (lut) {
12313                 u32 *lut_dw = (u32 *)lut;
12314
12315                 if (vsi->type == I40E_VSI_MAIN) {
12316                         if (lut_size != I40E_HLUT_ARRAY_SIZE)
12317                                 return -EINVAL;
12318                         for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12319                                 wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12320                 } else if (vsi->type == I40E_VSI_SRIOV) {
12321                         if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12322                                 return -EINVAL;
12323                         for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12324                                 wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12325                 } else {
12326                         dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12327                 }
12328         }
12329         i40e_flush(hw);
12330
12331         return 0;
12332 }
12333
12334 /**
12335  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12336  * @vsi: Pointer to VSI structure
12337  * @seed: Buffer to store the keys
12338  * @lut: Buffer to store the lookup table entries
12339  * @lut_size: Size of buffer to store the lookup table entries
12340  *
12341  * Returns 0 on success, negative on failure
12342  */
12343 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12344                             u8 *lut, u16 lut_size)
12345 {
12346         struct i40e_pf *pf = vsi->back;
12347         struct i40e_hw *hw = &pf->hw;
12348         u16 i;
12349
12350         if (seed) {
12351                 u32 *seed_dw = (u32 *)seed;
12352
12353                 for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12354                         seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12355         }
12356         if (lut) {
12357                 u32 *lut_dw = (u32 *)lut;
12358
12359                 if (lut_size != I40E_HLUT_ARRAY_SIZE)
12360                         return -EINVAL;
12361                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12362                         lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12363         }
12364
12365         return 0;
12366 }
12367
12368 /**
12369  * i40e_config_rss - Configure RSS keys and lut
12370  * @vsi: Pointer to VSI structure
12371  * @seed: RSS hash seed
12372  * @lut: Lookup table
12373  * @lut_size: Lookup table size
12374  *
12375  * Returns 0 on success, negative on failure
12376  */
12377 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12378 {
12379         struct i40e_pf *pf = vsi->back;
12380
12381         if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12382                 return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12383         else
12384                 return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12385 }
12386
12387 /**
12388  * i40e_get_rss - Get RSS keys and lut
12389  * @vsi: Pointer to VSI structure
12390  * @seed: Buffer to store the keys
12391  * @lut: Buffer to store the lookup table entries
12392  * @lut_size: Size of buffer to store the lookup table entries
12393  *
12394  * Returns 0 on success, negative on failure
12395  */
12396 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12397 {
12398         struct i40e_pf *pf = vsi->back;
12399
12400         if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps))
12401                 return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12402         else
12403                 return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12404 }
12405
12406 /**
12407  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12408  * @pf: Pointer to board private structure
12409  * @lut: Lookup table
12410  * @rss_table_size: Lookup table size
12411  * @rss_size: Range of queue number for hashing
12412  */
12413 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12414                        u16 rss_table_size, u16 rss_size)
12415 {
12416         u16 i;
12417
12418         for (i = 0; i < rss_table_size; i++)
12419                 lut[i] = i % rss_size;
12420 }
12421
12422 /**
12423  * i40e_pf_config_rss - Prepare for RSS if used
12424  * @pf: board private structure
12425  **/
12426 static int i40e_pf_config_rss(struct i40e_pf *pf)
12427 {
12428         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12429         u8 seed[I40E_HKEY_ARRAY_SIZE];
12430         u8 *lut;
12431         struct i40e_hw *hw = &pf->hw;
12432         u32 reg_val;
12433         u64 hena;
12434         int ret;
12435
12436         /* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12437         hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12438                 ((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12439         hena |= i40e_pf_get_default_rss_hena(pf);
12440
12441         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12442         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12443
12444         /* Determine the RSS table size based on the hardware capabilities */
12445         reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12446         reg_val = (pf->rss_table_size == 512) ?
12447                         (reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12448                         (reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12449         i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12450
12451         /* Determine the RSS size of the VSI */
12452         if (!vsi->rss_size) {
12453                 u16 qcount;
12454                 /* If the firmware does something weird during VSI init, we
12455                  * could end up with zero TCs. Check for that to avoid
12456                  * divide-by-zero. It probably won't pass traffic, but it also
12457                  * won't panic.
12458                  */
12459                 qcount = vsi->num_queue_pairs /
12460                          (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12461                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12462         }
12463         if (!vsi->rss_size)
12464                 return -EINVAL;
12465
12466         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12467         if (!lut)
12468                 return -ENOMEM;
12469
12470         /* Use user configured lut if there is one, otherwise use default */
12471         if (vsi->rss_lut_user)
12472                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12473         else
12474                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12475
12476         /* Use user configured hash key if there is one, otherwise
12477          * use default.
12478          */
12479         if (vsi->rss_hkey_user)
12480                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12481         else
12482                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12483         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12484         kfree(lut);
12485
12486         return ret;
12487 }
12488
12489 /**
12490  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12491  * @pf: board private structure
12492  * @queue_count: the requested queue count for rss.
12493  *
12494  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12495  * count which may be different from the requested queue count.
12496  * Note: expects to be called while under rtnl_lock()
12497  **/
12498 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12499 {
12500         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12501         int new_rss_size;
12502
12503         if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags))
12504                 return 0;
12505
12506         queue_count = min_t(int, queue_count, num_online_cpus());
12507         new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12508
12509         if (queue_count != vsi->num_queue_pairs) {
12510                 u16 qcount;
12511
12512                 vsi->req_queue_pairs = queue_count;
12513                 i40e_prep_for_reset(pf);
12514                 if (test_bit(__I40E_IN_REMOVE, pf->state))
12515                         return pf->alloc_rss_size;
12516
12517                 pf->alloc_rss_size = new_rss_size;
12518
12519                 i40e_reset_and_rebuild(pf, true, true);
12520
12521                 /* Discard the user configured hash keys and lut, if less
12522                  * queues are enabled.
12523                  */
12524                 if (queue_count < vsi->rss_size) {
12525                         i40e_clear_rss_config_user(vsi);
12526                         dev_dbg(&pf->pdev->dev,
12527                                 "discard user configured hash keys and lut\n");
12528                 }
12529
12530                 /* Reset vsi->rss_size, as number of enabled queues changed */
12531                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12532                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12533
12534                 i40e_pf_config_rss(pf);
12535         }
12536         dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12537                  vsi->req_queue_pairs, pf->rss_size_max);
12538         return pf->alloc_rss_size;
12539 }
12540
12541 /**
12542  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12543  * @pf: board private structure
12544  **/
12545 int i40e_get_partition_bw_setting(struct i40e_pf *pf)
12546 {
12547         bool min_valid, max_valid;
12548         u32 max_bw, min_bw;
12549         int status;
12550
12551         status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12552                                            &min_valid, &max_valid);
12553
12554         if (!status) {
12555                 if (min_valid)
12556                         pf->min_bw = min_bw;
12557                 if (max_valid)
12558                         pf->max_bw = max_bw;
12559         }
12560
12561         return status;
12562 }
12563
12564 /**
12565  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12566  * @pf: board private structure
12567  **/
12568 int i40e_set_partition_bw_setting(struct i40e_pf *pf)
12569 {
12570         struct i40e_aqc_configure_partition_bw_data bw_data;
12571         int status;
12572
12573         memset(&bw_data, 0, sizeof(bw_data));
12574
12575         /* Set the valid bit for this PF */
12576         bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12577         bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12578         bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12579
12580         /* Set the new bandwidths */
12581         status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12582
12583         return status;
12584 }
12585
12586 /**
12587  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12588  * @pf: board private structure
12589  **/
12590 int i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12591 {
12592         /* Commit temporary BW setting to permanent NVM image */
12593         enum i40e_admin_queue_err last_aq_status;
12594         u16 nvm_word;
12595         int ret;
12596
12597         if (pf->hw.partition_id != 1) {
12598                 dev_info(&pf->pdev->dev,
12599                          "Commit BW only works on partition 1! This is partition %d",
12600                          pf->hw.partition_id);
12601                 ret = -EOPNOTSUPP;
12602                 goto bw_commit_out;
12603         }
12604
12605         /* Acquire NVM for read access */
12606         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12607         last_aq_status = pf->hw.aq.asq_last_status;
12608         if (ret) {
12609                 dev_info(&pf->pdev->dev,
12610                          "Cannot acquire NVM for read access, err %pe aq_err %s\n",
12611                          ERR_PTR(ret),
12612                          i40e_aq_str(&pf->hw, last_aq_status));
12613                 goto bw_commit_out;
12614         }
12615
12616         /* Read word 0x10 of NVM - SW compatibility word 1 */
12617         ret = i40e_aq_read_nvm(&pf->hw,
12618                                I40E_SR_NVM_CONTROL_WORD,
12619                                0x10, sizeof(nvm_word), &nvm_word,
12620                                false, NULL);
12621         /* Save off last admin queue command status before releasing
12622          * the NVM
12623          */
12624         last_aq_status = pf->hw.aq.asq_last_status;
12625         i40e_release_nvm(&pf->hw);
12626         if (ret) {
12627                 dev_info(&pf->pdev->dev, "NVM read error, err %pe aq_err %s\n",
12628                          ERR_PTR(ret),
12629                          i40e_aq_str(&pf->hw, last_aq_status));
12630                 goto bw_commit_out;
12631         }
12632
12633         /* Wait a bit for NVM release to complete */
12634         msleep(50);
12635
12636         /* Acquire NVM for write access */
12637         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12638         last_aq_status = pf->hw.aq.asq_last_status;
12639         if (ret) {
12640                 dev_info(&pf->pdev->dev,
12641                          "Cannot acquire NVM for write access, err %pe aq_err %s\n",
12642                          ERR_PTR(ret),
12643                          i40e_aq_str(&pf->hw, last_aq_status));
12644                 goto bw_commit_out;
12645         }
12646         /* Write it back out unchanged to initiate update NVM,
12647          * which will force a write of the shadow (alt) RAM to
12648          * the NVM - thus storing the bandwidth values permanently.
12649          */
12650         ret = i40e_aq_update_nvm(&pf->hw,
12651                                  I40E_SR_NVM_CONTROL_WORD,
12652                                  0x10, sizeof(nvm_word),
12653                                  &nvm_word, true, 0, NULL);
12654         /* Save off last admin queue command status before releasing
12655          * the NVM
12656          */
12657         last_aq_status = pf->hw.aq.asq_last_status;
12658         i40e_release_nvm(&pf->hw);
12659         if (ret)
12660                 dev_info(&pf->pdev->dev,
12661                          "BW settings NOT SAVED, err %pe aq_err %s\n",
12662                          ERR_PTR(ret),
12663                          i40e_aq_str(&pf->hw, last_aq_status));
12664 bw_commit_out:
12665
12666         return ret;
12667 }
12668
12669 /**
12670  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12671  * if total port shutdown feature is enabled for this PF
12672  * @pf: board private structure
12673  **/
12674 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12675 {
12676 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED        BIT(4)
12677 #define I40E_FEATURES_ENABLE_PTR                0x2A
12678 #define I40E_CURRENT_SETTING_PTR                0x2B
12679 #define I40E_LINK_BEHAVIOR_WORD_OFFSET          0x2D
12680 #define I40E_LINK_BEHAVIOR_WORD_LENGTH          0x1
12681 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED    BIT(0)
12682 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH      4
12683         u16 sr_emp_sr_settings_ptr = 0;
12684         u16 features_enable = 0;
12685         u16 link_behavior = 0;
12686         int read_status = 0;
12687         bool ret = false;
12688
12689         read_status = i40e_read_nvm_word(&pf->hw,
12690                                          I40E_SR_EMP_SR_SETTINGS_PTR,
12691                                          &sr_emp_sr_settings_ptr);
12692         if (read_status)
12693                 goto err_nvm;
12694         read_status = i40e_read_nvm_word(&pf->hw,
12695                                          sr_emp_sr_settings_ptr +
12696                                          I40E_FEATURES_ENABLE_PTR,
12697                                          &features_enable);
12698         if (read_status)
12699                 goto err_nvm;
12700         if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12701                 read_status = i40e_read_nvm_module_data(&pf->hw,
12702                                                         I40E_SR_EMP_SR_SETTINGS_PTR,
12703                                                         I40E_CURRENT_SETTING_PTR,
12704                                                         I40E_LINK_BEHAVIOR_WORD_OFFSET,
12705                                                         I40E_LINK_BEHAVIOR_WORD_LENGTH,
12706                                                         &link_behavior);
12707                 if (read_status)
12708                         goto err_nvm;
12709                 link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12710                 ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12711         }
12712         return ret;
12713
12714 err_nvm:
12715         dev_warn(&pf->pdev->dev,
12716                  "total-port-shutdown feature is off due to read nvm error: %pe\n",
12717                  ERR_PTR(read_status));
12718         return ret;
12719 }
12720
12721 /**
12722  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12723  * @pf: board private structure to initialize
12724  *
12725  * i40e_sw_init initializes the Adapter private data structure.
12726  * Fields are initialized based on PCI device information and
12727  * OS network device settings (MTU size).
12728  **/
12729 static int i40e_sw_init(struct i40e_pf *pf)
12730 {
12731         int err = 0;
12732         int size;
12733         u16 pow;
12734
12735         /* Set default capability flags */
12736         bitmap_zero(pf->flags, I40E_PF_FLAGS_NBITS);
12737         set_bit(I40E_FLAG_MSI_ENA, pf->flags);
12738         set_bit(I40E_FLAG_MSIX_ENA, pf->flags);
12739
12740         /* Set default ITR */
12741         pf->rx_itr_default = I40E_ITR_RX_DEF;
12742         pf->tx_itr_default = I40E_ITR_TX_DEF;
12743
12744         /* Depending on PF configurations, it is possible that the RSS
12745          * maximum might end up larger than the available queues
12746          */
12747         pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12748         pf->alloc_rss_size = 1;
12749         pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12750         pf->rss_size_max = min_t(int, pf->rss_size_max,
12751                                  pf->hw.func_caps.num_tx_qp);
12752
12753         /* find the next higher power-of-2 of num cpus */
12754         pow = roundup_pow_of_two(num_online_cpus());
12755         pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12756
12757         if (pf->hw.func_caps.rss) {
12758                 set_bit(I40E_FLAG_RSS_ENA, pf->flags);
12759                 pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12760                                            num_online_cpus());
12761         }
12762
12763         /* MFP mode enabled */
12764         if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12765                 set_bit(I40E_FLAG_MFP_ENA, pf->flags);
12766                 dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12767                 if (i40e_get_partition_bw_setting(pf)) {
12768                         dev_warn(&pf->pdev->dev,
12769                                  "Could not get partition bw settings\n");
12770                 } else {
12771                         dev_info(&pf->pdev->dev,
12772                                  "Partition BW Min = %8.8x, Max = %8.8x\n",
12773                                  pf->min_bw, pf->max_bw);
12774
12775                         /* nudge the Tx scheduler */
12776                         i40e_set_partition_bw_setting(pf);
12777                 }
12778         }
12779
12780         if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12781             (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12782                 set_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
12783                 if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
12784                     pf->hw.num_partitions > 1)
12785                         dev_info(&pf->pdev->dev,
12786                                  "Flow Director Sideband mode Disabled in MFP mode\n");
12787                 else
12788                         set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12789                 pf->fdir_pf_filter_count =
12790                                  pf->hw.func_caps.fd_filters_guaranteed;
12791                 pf->hw.fdir_shared_filter_count =
12792                                  pf->hw.func_caps.fd_filters_best_effort;
12793         }
12794
12795         /* Enable HW ATR eviction if possible */
12796         if (test_bit(I40E_HW_CAP_ATR_EVICT, pf->hw.caps))
12797                 set_bit(I40E_FLAG_HW_ATR_EVICT_ENA, pf->flags);
12798
12799         if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12800                 pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12801                 set_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
12802                 pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12803         }
12804
12805         if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12806                 set_bit(I40E_FLAG_IWARP_ENA, pf->flags);
12807                 /* IWARP needs one extra vector for CQP just like MISC.*/
12808                 pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12809         }
12810         /* Stopping FW LLDP engine is supported on XL710 and X722
12811          * starting from FW versions determined in i40e_init_adminq.
12812          * Stopping the FW LLDP engine is not supported on XL710
12813          * if NPAR is functioning so unset this hw flag in this case.
12814          */
12815         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12816             pf->hw.func_caps.npar_enable)
12817                 clear_bit(I40E_HW_CAP_FW_LLDP_STOPPABLE, pf->hw.caps);
12818
12819 #ifdef CONFIG_PCI_IOV
12820         if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12821                 pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12822                 set_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
12823                 pf->num_req_vfs = min_t(int,
12824                                         pf->hw.func_caps.num_vfs,
12825                                         I40E_MAX_VF_COUNT);
12826         }
12827 #endif /* CONFIG_PCI_IOV */
12828         pf->lan_veb = I40E_NO_VEB;
12829         pf->lan_vsi = I40E_NO_VSI;
12830
12831         /* By default FW has this off for performance reasons */
12832         clear_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
12833
12834         /* set up queue assignment tracking */
12835         size = sizeof(struct i40e_lump_tracking)
12836                 + (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12837         pf->qp_pile = kzalloc(size, GFP_KERNEL);
12838         if (!pf->qp_pile) {
12839                 err = -ENOMEM;
12840                 goto sw_init_done;
12841         }
12842         pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12843
12844         pf->tx_timeout_recovery_level = 1;
12845
12846         if (pf->hw.mac.type != I40E_MAC_X722 &&
12847             i40e_is_total_port_shutdown_enabled(pf)) {
12848                 /* Link down on close must be on when total port shutdown
12849                  * is enabled for a given port
12850                  */
12851                 set_bit(I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENA, pf->flags);
12852                 set_bit(I40E_FLAG_LINK_DOWN_ON_CLOSE_ENA, pf->flags);
12853                 dev_info(&pf->pdev->dev,
12854                          "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12855         }
12856         mutex_init(&pf->switch_mutex);
12857
12858 sw_init_done:
12859         return err;
12860 }
12861
12862 /**
12863  * i40e_set_ntuple - set the ntuple feature flag and take action
12864  * @pf: board private structure to initialize
12865  * @features: the feature set that the stack is suggesting
12866  *
12867  * returns a bool to indicate if reset needs to happen
12868  **/
12869 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12870 {
12871         bool need_reset = false;
12872
12873         /* Check if Flow Director n-tuple support was enabled or disabled.  If
12874          * the state changed, we need to reset.
12875          */
12876         if (features & NETIF_F_NTUPLE) {
12877                 /* Enable filters and mark for reset */
12878                 if (!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags))
12879                         need_reset = true;
12880                 /* enable FD_SB only if there is MSI-X vector and no cloud
12881                  * filters exist
12882                  */
12883                 if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12884                         set_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12885                         clear_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12886                 }
12887         } else {
12888                 /* turn off filters, mark for reset and clear SW filter list */
12889                 if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
12890                         need_reset = true;
12891                         i40e_fdir_filter_exit(pf);
12892                 }
12893                 clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
12894                 clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12895                 set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
12896
12897                 /* reset fd counters */
12898                 pf->fd_add_err = 0;
12899                 pf->fd_atr_cnt = 0;
12900                 /* if ATR was auto disabled it can be re-enabled. */
12901                 if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12902                         if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
12903                             (I40E_DEBUG_FD & pf->hw.debug_mask))
12904                                 dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12905         }
12906         return need_reset;
12907 }
12908
12909 /**
12910  * i40e_clear_rss_lut - clear the rx hash lookup table
12911  * @vsi: the VSI being configured
12912  **/
12913 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12914 {
12915         struct i40e_pf *pf = vsi->back;
12916         struct i40e_hw *hw = &pf->hw;
12917         u16 vf_id = vsi->vf_id;
12918         u8 i;
12919
12920         if (vsi->type == I40E_VSI_MAIN) {
12921                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12922                         wr32(hw, I40E_PFQF_HLUT(i), 0);
12923         } else if (vsi->type == I40E_VSI_SRIOV) {
12924                 for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12925                         i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12926         } else {
12927                 dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12928         }
12929 }
12930
12931 /**
12932  * i40e_set_loopback - turn on/off loopback mode on underlying PF
12933  * @vsi: ptr to VSI
12934  * @ena: flag to indicate the on/off setting
12935  */
12936 static int i40e_set_loopback(struct i40e_vsi *vsi, bool ena)
12937 {
12938         bool if_running = netif_running(vsi->netdev) &&
12939                           !test_and_set_bit(__I40E_VSI_DOWN, vsi->state);
12940         int ret;
12941
12942         if (if_running)
12943                 i40e_down(vsi);
12944
12945         ret = i40e_aq_set_mac_loopback(&vsi->back->hw, ena, NULL);
12946         if (ret)
12947                 netdev_err(vsi->netdev, "Failed to toggle loopback state\n");
12948         if (if_running)
12949                 i40e_up(vsi);
12950
12951         return ret;
12952 }
12953
12954 /**
12955  * i40e_set_features - set the netdev feature flags
12956  * @netdev: ptr to the netdev being adjusted
12957  * @features: the feature set that the stack is suggesting
12958  * Note: expects to be called while under rtnl_lock()
12959  **/
12960 static int i40e_set_features(struct net_device *netdev,
12961                              netdev_features_t features)
12962 {
12963         struct i40e_netdev_priv *np = netdev_priv(netdev);
12964         struct i40e_vsi *vsi = np->vsi;
12965         struct i40e_pf *pf = vsi->back;
12966         bool need_reset;
12967
12968         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12969                 i40e_pf_config_rss(pf);
12970         else if (!(features & NETIF_F_RXHASH) &&
12971                  netdev->features & NETIF_F_RXHASH)
12972                 i40e_clear_rss_lut(vsi);
12973
12974         if (features & NETIF_F_HW_VLAN_CTAG_RX)
12975                 i40e_vlan_stripping_enable(vsi);
12976         else
12977                 i40e_vlan_stripping_disable(vsi);
12978
12979         if (!(features & NETIF_F_HW_TC) &&
12980             (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12981                 dev_err(&pf->pdev->dev,
12982                         "Offloaded tc filters active, can't turn hw_tc_offload off");
12983                 return -EINVAL;
12984         }
12985
12986         if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12987                 i40e_del_all_macvlans(vsi);
12988
12989         need_reset = i40e_set_ntuple(pf, features);
12990
12991         if (need_reset)
12992                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12993
12994         if ((features ^ netdev->features) & NETIF_F_LOOPBACK)
12995                 return i40e_set_loopback(vsi, !!(features & NETIF_F_LOOPBACK));
12996
12997         return 0;
12998 }
12999
13000 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
13001                                     unsigned int table, unsigned int idx,
13002                                     struct udp_tunnel_info *ti)
13003 {
13004         struct i40e_netdev_priv *np = netdev_priv(netdev);
13005         struct i40e_hw *hw = &np->vsi->back->hw;
13006         u8 type, filter_index;
13007         int ret;
13008
13009         type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
13010                                                    I40E_AQC_TUNNEL_TYPE_NGE;
13011
13012         ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
13013                                      NULL);
13014         if (ret) {
13015                 netdev_info(netdev, "add UDP port failed, err %pe aq_err %s\n",
13016                             ERR_PTR(ret),
13017                             i40e_aq_str(hw, hw->aq.asq_last_status));
13018                 return -EIO;
13019         }
13020
13021         udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
13022         return 0;
13023 }
13024
13025 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
13026                                       unsigned int table, unsigned int idx,
13027                                       struct udp_tunnel_info *ti)
13028 {
13029         struct i40e_netdev_priv *np = netdev_priv(netdev);
13030         struct i40e_hw *hw = &np->vsi->back->hw;
13031         int ret;
13032
13033         ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
13034         if (ret) {
13035                 netdev_info(netdev, "delete UDP port failed, err %pe aq_err %s\n",
13036                             ERR_PTR(ret),
13037                             i40e_aq_str(hw, hw->aq.asq_last_status));
13038                 return -EIO;
13039         }
13040
13041         return 0;
13042 }
13043
13044 static int i40e_get_phys_port_id(struct net_device *netdev,
13045                                  struct netdev_phys_item_id *ppid)
13046 {
13047         struct i40e_netdev_priv *np = netdev_priv(netdev);
13048         struct i40e_pf *pf = np->vsi->back;
13049         struct i40e_hw *hw = &pf->hw;
13050
13051         if (!test_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps))
13052                 return -EOPNOTSUPP;
13053
13054         ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
13055         memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
13056
13057         return 0;
13058 }
13059
13060 /**
13061  * i40e_ndo_fdb_add - add an entry to the hardware database
13062  * @ndm: the input from the stack
13063  * @tb: pointer to array of nladdr (unused)
13064  * @dev: the net device pointer
13065  * @addr: the MAC address entry being added
13066  * @vid: VLAN ID
13067  * @flags: instructions from stack about fdb operation
13068  * @extack: netlink extended ack, unused currently
13069  */
13070 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
13071                             struct net_device *dev,
13072                             const unsigned char *addr, u16 vid,
13073                             u16 flags,
13074                             struct netlink_ext_ack *extack)
13075 {
13076         struct i40e_netdev_priv *np = netdev_priv(dev);
13077         struct i40e_pf *pf = np->vsi->back;
13078         int err = 0;
13079
13080         if (!test_bit(I40E_FLAG_SRIOV_ENA, pf->flags))
13081                 return -EOPNOTSUPP;
13082
13083         if (vid) {
13084                 pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
13085                 return -EINVAL;
13086         }
13087
13088         /* Hardware does not support aging addresses so if a
13089          * ndm_state is given only allow permanent addresses
13090          */
13091         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
13092                 netdev_info(dev, "FDB only supports static addresses\n");
13093                 return -EINVAL;
13094         }
13095
13096         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
13097                 err = dev_uc_add_excl(dev, addr);
13098         else if (is_multicast_ether_addr(addr))
13099                 err = dev_mc_add_excl(dev, addr);
13100         else
13101                 err = -EINVAL;
13102
13103         /* Only return duplicate errors if NLM_F_EXCL is set */
13104         if (err == -EEXIST && !(flags & NLM_F_EXCL))
13105                 err = 0;
13106
13107         return err;
13108 }
13109
13110 /**
13111  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
13112  * @dev: the netdev being configured
13113  * @nlh: RTNL message
13114  * @flags: bridge flags
13115  * @extack: netlink extended ack
13116  *
13117  * Inserts a new hardware bridge if not already created and
13118  * enables the bridging mode requested (VEB or VEPA). If the
13119  * hardware bridge has already been inserted and the request
13120  * is to change the mode then that requires a PF reset to
13121  * allow rebuild of the components with required hardware
13122  * bridge mode enabled.
13123  *
13124  * Note: expects to be called while under rtnl_lock()
13125  **/
13126 static int i40e_ndo_bridge_setlink(struct net_device *dev,
13127                                    struct nlmsghdr *nlh,
13128                                    u16 flags,
13129                                    struct netlink_ext_ack *extack)
13130 {
13131         struct i40e_netdev_priv *np = netdev_priv(dev);
13132         struct i40e_vsi *vsi = np->vsi;
13133         struct i40e_pf *pf = vsi->back;
13134         struct i40e_veb *veb = NULL;
13135         struct nlattr *attr, *br_spec;
13136         int i, rem;
13137
13138         /* Only for PF VSI for now */
13139         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13140                 return -EOPNOTSUPP;
13141
13142         /* Find the HW bridge for PF VSI */
13143         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13144                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13145                         veb = pf->veb[i];
13146         }
13147
13148         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
13149         if (!br_spec)
13150                 return -EINVAL;
13151
13152         nla_for_each_nested(attr, br_spec, rem) {
13153                 __u16 mode;
13154
13155                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
13156                         continue;
13157
13158                 mode = nla_get_u16(attr);
13159                 if ((mode != BRIDGE_MODE_VEPA) &&
13160                     (mode != BRIDGE_MODE_VEB))
13161                         return -EINVAL;
13162
13163                 /* Insert a new HW bridge */
13164                 if (!veb) {
13165                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13166                                              vsi->tc_config.enabled_tc);
13167                         if (veb) {
13168                                 veb->bridge_mode = mode;
13169                                 i40e_config_bridge_mode(veb);
13170                         } else {
13171                                 /* No Bridge HW offload available */
13172                                 return -ENOENT;
13173                         }
13174                         break;
13175                 } else if (mode != veb->bridge_mode) {
13176                         /* Existing HW bridge but different mode needs reset */
13177                         veb->bridge_mode = mode;
13178                         /* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13179                         if (mode == BRIDGE_MODE_VEB)
13180                                 set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13181                         else
13182                                 clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
13183                         i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13184                         break;
13185                 }
13186         }
13187
13188         return 0;
13189 }
13190
13191 /**
13192  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13193  * @skb: skb buff
13194  * @pid: process id
13195  * @seq: RTNL message seq #
13196  * @dev: the netdev being configured
13197  * @filter_mask: unused
13198  * @nlflags: netlink flags passed in
13199  *
13200  * Return the mode in which the hardware bridge is operating in
13201  * i.e VEB or VEPA.
13202  **/
13203 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13204                                    struct net_device *dev,
13205                                    u32 __always_unused filter_mask,
13206                                    int nlflags)
13207 {
13208         struct i40e_netdev_priv *np = netdev_priv(dev);
13209         struct i40e_vsi *vsi = np->vsi;
13210         struct i40e_pf *pf = vsi->back;
13211         struct i40e_veb *veb = NULL;
13212         int i;
13213
13214         /* Only for PF VSI for now */
13215         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13216                 return -EOPNOTSUPP;
13217
13218         /* Find the HW bridge for the PF VSI */
13219         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13220                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13221                         veb = pf->veb[i];
13222         }
13223
13224         if (!veb)
13225                 return 0;
13226
13227         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13228                                        0, 0, nlflags, filter_mask, NULL);
13229 }
13230
13231 /**
13232  * i40e_features_check - Validate encapsulated packet conforms to limits
13233  * @skb: skb buff
13234  * @dev: This physical port's netdev
13235  * @features: Offload features that the stack believes apply
13236  **/
13237 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13238                                              struct net_device *dev,
13239                                              netdev_features_t features)
13240 {
13241         size_t len;
13242
13243         /* No point in doing any of this if neither checksum nor GSO are
13244          * being requested for this frame.  We can rule out both by just
13245          * checking for CHECKSUM_PARTIAL
13246          */
13247         if (skb->ip_summed != CHECKSUM_PARTIAL)
13248                 return features;
13249
13250         /* We cannot support GSO if the MSS is going to be less than
13251          * 64 bytes.  If it is then we need to drop support for GSO.
13252          */
13253         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13254                 features &= ~NETIF_F_GSO_MASK;
13255
13256         /* MACLEN can support at most 63 words */
13257         len = skb_network_header(skb) - skb->data;
13258         if (len & ~(63 * 2))
13259                 goto out_err;
13260
13261         /* IPLEN and EIPLEN can support at most 127 dwords */
13262         len = skb_transport_header(skb) - skb_network_header(skb);
13263         if (len & ~(127 * 4))
13264                 goto out_err;
13265
13266         if (skb->encapsulation) {
13267                 /* L4TUNLEN can support 127 words */
13268                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
13269                 if (len & ~(127 * 2))
13270                         goto out_err;
13271
13272                 /* IPLEN can support at most 127 dwords */
13273                 len = skb_inner_transport_header(skb) -
13274                       skb_inner_network_header(skb);
13275                 if (len & ~(127 * 4))
13276                         goto out_err;
13277         }
13278
13279         /* No need to validate L4LEN as TCP is the only protocol with a
13280          * flexible value and we support all possible values supported
13281          * by TCP, which is at most 15 dwords
13282          */
13283
13284         return features;
13285 out_err:
13286         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13287 }
13288
13289 /**
13290  * i40e_xdp_setup - add/remove an XDP program
13291  * @vsi: VSI to changed
13292  * @prog: XDP program
13293  * @extack: netlink extended ack
13294  **/
13295 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13296                           struct netlink_ext_ack *extack)
13297 {
13298         int frame_size = i40e_max_vsi_frame_size(vsi, prog);
13299         struct i40e_pf *pf = vsi->back;
13300         struct bpf_prog *old_prog;
13301         bool need_reset;
13302         int i;
13303
13304         /* Don't allow frames that span over multiple buffers */
13305         if (vsi->netdev->mtu > frame_size - I40E_PACKET_HDR_PAD) {
13306                 NL_SET_ERR_MSG_MOD(extack, "MTU too large for linear frames and XDP prog does not support frags");
13307                 return -EINVAL;
13308         }
13309
13310         /* When turning XDP on->off/off->on we reset and rebuild the rings. */
13311         need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13312
13313         if (need_reset)
13314                 i40e_prep_for_reset(pf);
13315
13316         /* VSI shall be deleted in a moment, just return EINVAL */
13317         if (test_bit(__I40E_IN_REMOVE, pf->state))
13318                 return -EINVAL;
13319
13320         old_prog = xchg(&vsi->xdp_prog, prog);
13321
13322         if (need_reset) {
13323                 if (!prog) {
13324                         xdp_features_clear_redirect_target(vsi->netdev);
13325                         /* Wait until ndo_xsk_wakeup completes. */
13326                         synchronize_rcu();
13327                 }
13328                 i40e_reset_and_rebuild(pf, true, true);
13329         }
13330
13331         if (!i40e_enabled_xdp_vsi(vsi) && prog) {
13332                 if (i40e_realloc_rx_bi_zc(vsi, true))
13333                         return -ENOMEM;
13334         } else if (i40e_enabled_xdp_vsi(vsi) && !prog) {
13335                 if (i40e_realloc_rx_bi_zc(vsi, false))
13336                         return -ENOMEM;
13337         }
13338
13339         for (i = 0; i < vsi->num_queue_pairs; i++)
13340                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13341
13342         if (old_prog)
13343                 bpf_prog_put(old_prog);
13344
13345         /* Kick start the NAPI context if there is an AF_XDP socket open
13346          * on that queue id. This so that receiving will start.
13347          */
13348         if (need_reset && prog) {
13349                 for (i = 0; i < vsi->num_queue_pairs; i++)
13350                         if (vsi->xdp_rings[i]->xsk_pool)
13351                                 (void)i40e_xsk_wakeup(vsi->netdev, i,
13352                                                       XDP_WAKEUP_RX);
13353                 xdp_features_set_redirect_target(vsi->netdev, true);
13354         }
13355
13356         return 0;
13357 }
13358
13359 /**
13360  * i40e_enter_busy_conf - Enters busy config state
13361  * @vsi: vsi
13362  *
13363  * Returns 0 on success, <0 for failure.
13364  **/
13365 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13366 {
13367         struct i40e_pf *pf = vsi->back;
13368         int timeout = 50;
13369
13370         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13371                 timeout--;
13372                 if (!timeout)
13373                         return -EBUSY;
13374                 usleep_range(1000, 2000);
13375         }
13376
13377         return 0;
13378 }
13379
13380 /**
13381  * i40e_exit_busy_conf - Exits busy config state
13382  * @vsi: vsi
13383  **/
13384 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13385 {
13386         struct i40e_pf *pf = vsi->back;
13387
13388         clear_bit(__I40E_CONFIG_BUSY, pf->state);
13389 }
13390
13391 /**
13392  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13393  * @vsi: vsi
13394  * @queue_pair: queue pair
13395  **/
13396 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13397 {
13398         memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13399                sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13400         memset(&vsi->tx_rings[queue_pair]->stats, 0,
13401                sizeof(vsi->tx_rings[queue_pair]->stats));
13402         if (i40e_enabled_xdp_vsi(vsi)) {
13403                 memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13404                        sizeof(vsi->xdp_rings[queue_pair]->stats));
13405         }
13406 }
13407
13408 /**
13409  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13410  * @vsi: vsi
13411  * @queue_pair: queue pair
13412  **/
13413 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13414 {
13415         i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13416         if (i40e_enabled_xdp_vsi(vsi)) {
13417                 /* Make sure that in-progress ndo_xdp_xmit calls are
13418                  * completed.
13419                  */
13420                 synchronize_rcu();
13421                 i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13422         }
13423         i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13424 }
13425
13426 /**
13427  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13428  * @vsi: vsi
13429  * @queue_pair: queue pair
13430  * @enable: true for enable, false for disable
13431  **/
13432 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13433                                         bool enable)
13434 {
13435         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13436         struct i40e_q_vector *q_vector = rxr->q_vector;
13437
13438         if (!vsi->netdev)
13439                 return;
13440
13441         /* All rings in a qp belong to the same qvector. */
13442         if (q_vector->rx.ring || q_vector->tx.ring) {
13443                 if (enable)
13444                         napi_enable(&q_vector->napi);
13445                 else
13446                         napi_disable(&q_vector->napi);
13447         }
13448 }
13449
13450 /**
13451  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13452  * @vsi: vsi
13453  * @queue_pair: queue pair
13454  * @enable: true for enable, false for disable
13455  *
13456  * Returns 0 on success, <0 on failure.
13457  **/
13458 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13459                                         bool enable)
13460 {
13461         struct i40e_pf *pf = vsi->back;
13462         int pf_q, ret = 0;
13463
13464         pf_q = vsi->base_queue + queue_pair;
13465         ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13466                                      false /*is xdp*/, enable);
13467         if (ret) {
13468                 dev_info(&pf->pdev->dev,
13469                          "VSI seid %d Tx ring %d %sable timeout\n",
13470                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13471                 return ret;
13472         }
13473
13474         i40e_control_rx_q(pf, pf_q, enable);
13475         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13476         if (ret) {
13477                 dev_info(&pf->pdev->dev,
13478                          "VSI seid %d Rx ring %d %sable timeout\n",
13479                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13480                 return ret;
13481         }
13482
13483         /* Due to HW errata, on Rx disable only, the register can
13484          * indicate done before it really is. Needs 50ms to be sure
13485          */
13486         if (!enable)
13487                 mdelay(50);
13488
13489         if (!i40e_enabled_xdp_vsi(vsi))
13490                 return ret;
13491
13492         ret = i40e_control_wait_tx_q(vsi->seid, pf,
13493                                      pf_q + vsi->alloc_queue_pairs,
13494                                      true /*is xdp*/, enable);
13495         if (ret) {
13496                 dev_info(&pf->pdev->dev,
13497                          "VSI seid %d XDP Tx ring %d %sable timeout\n",
13498                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13499         }
13500
13501         return ret;
13502 }
13503
13504 /**
13505  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13506  * @vsi: vsi
13507  * @queue_pair: queue_pair
13508  **/
13509 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13510 {
13511         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13512         struct i40e_pf *pf = vsi->back;
13513         struct i40e_hw *hw = &pf->hw;
13514
13515         /* All rings in a qp belong to the same qvector. */
13516         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
13517                 i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13518         else
13519                 i40e_irq_dynamic_enable_icr0(pf);
13520
13521         i40e_flush(hw);
13522 }
13523
13524 /**
13525  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13526  * @vsi: vsi
13527  * @queue_pair: queue_pair
13528  **/
13529 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13530 {
13531         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13532         struct i40e_pf *pf = vsi->back;
13533         struct i40e_hw *hw = &pf->hw;
13534
13535         /* For simplicity, instead of removing the qp interrupt causes
13536          * from the interrupt linked list, we simply disable the interrupt, and
13537          * leave the list intact.
13538          *
13539          * All rings in a qp belong to the same qvector.
13540          */
13541         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
13542                 u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13543
13544                 wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13545                 i40e_flush(hw);
13546                 synchronize_irq(pf->msix_entries[intpf].vector);
13547         } else {
13548                 /* Legacy and MSI mode - this stops all interrupt handling */
13549                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13550                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13551                 i40e_flush(hw);
13552                 synchronize_irq(pf->pdev->irq);
13553         }
13554 }
13555
13556 /**
13557  * i40e_queue_pair_disable - Disables a queue pair
13558  * @vsi: vsi
13559  * @queue_pair: queue pair
13560  *
13561  * Returns 0 on success, <0 on failure.
13562  **/
13563 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13564 {
13565         int err;
13566
13567         err = i40e_enter_busy_conf(vsi);
13568         if (err)
13569                 return err;
13570
13571         i40e_queue_pair_disable_irq(vsi, queue_pair);
13572         i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13573         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13574         i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13575         i40e_queue_pair_clean_rings(vsi, queue_pair);
13576         i40e_queue_pair_reset_stats(vsi, queue_pair);
13577
13578         return err;
13579 }
13580
13581 /**
13582  * i40e_queue_pair_enable - Enables a queue pair
13583  * @vsi: vsi
13584  * @queue_pair: queue pair
13585  *
13586  * Returns 0 on success, <0 on failure.
13587  **/
13588 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13589 {
13590         int err;
13591
13592         err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13593         if (err)
13594                 return err;
13595
13596         if (i40e_enabled_xdp_vsi(vsi)) {
13597                 err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13598                 if (err)
13599                         return err;
13600         }
13601
13602         err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13603         if (err)
13604                 return err;
13605
13606         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13607         i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13608         i40e_queue_pair_enable_irq(vsi, queue_pair);
13609
13610         i40e_exit_busy_conf(vsi);
13611
13612         return err;
13613 }
13614
13615 /**
13616  * i40e_xdp - implements ndo_bpf for i40e
13617  * @dev: netdevice
13618  * @xdp: XDP command
13619  **/
13620 static int i40e_xdp(struct net_device *dev,
13621                     struct netdev_bpf *xdp)
13622 {
13623         struct i40e_netdev_priv *np = netdev_priv(dev);
13624         struct i40e_vsi *vsi = np->vsi;
13625
13626         if (vsi->type != I40E_VSI_MAIN)
13627                 return -EINVAL;
13628
13629         switch (xdp->command) {
13630         case XDP_SETUP_PROG:
13631                 return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13632         case XDP_SETUP_XSK_POOL:
13633                 return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13634                                            xdp->xsk.queue_id);
13635         default:
13636                 return -EINVAL;
13637         }
13638 }
13639
13640 static const struct net_device_ops i40e_netdev_ops = {
13641         .ndo_open               = i40e_open,
13642         .ndo_stop               = i40e_close,
13643         .ndo_start_xmit         = i40e_lan_xmit_frame,
13644         .ndo_get_stats64        = i40e_get_netdev_stats_struct,
13645         .ndo_set_rx_mode        = i40e_set_rx_mode,
13646         .ndo_validate_addr      = eth_validate_addr,
13647         .ndo_set_mac_address    = i40e_set_mac,
13648         .ndo_change_mtu         = i40e_change_mtu,
13649         .ndo_eth_ioctl          = i40e_ioctl,
13650         .ndo_tx_timeout         = i40e_tx_timeout,
13651         .ndo_vlan_rx_add_vid    = i40e_vlan_rx_add_vid,
13652         .ndo_vlan_rx_kill_vid   = i40e_vlan_rx_kill_vid,
13653 #ifdef CONFIG_NET_POLL_CONTROLLER
13654         .ndo_poll_controller    = i40e_netpoll,
13655 #endif
13656         .ndo_setup_tc           = __i40e_setup_tc,
13657         .ndo_select_queue       = i40e_lan_select_queue,
13658         .ndo_set_features       = i40e_set_features,
13659         .ndo_set_vf_mac         = i40e_ndo_set_vf_mac,
13660         .ndo_set_vf_vlan        = i40e_ndo_set_vf_port_vlan,
13661         .ndo_get_vf_stats       = i40e_get_vf_stats,
13662         .ndo_set_vf_rate        = i40e_ndo_set_vf_bw,
13663         .ndo_get_vf_config      = i40e_ndo_get_vf_config,
13664         .ndo_set_vf_link_state  = i40e_ndo_set_vf_link_state,
13665         .ndo_set_vf_spoofchk    = i40e_ndo_set_vf_spoofchk,
13666         .ndo_set_vf_trust       = i40e_ndo_set_vf_trust,
13667         .ndo_get_phys_port_id   = i40e_get_phys_port_id,
13668         .ndo_fdb_add            = i40e_ndo_fdb_add,
13669         .ndo_features_check     = i40e_features_check,
13670         .ndo_bridge_getlink     = i40e_ndo_bridge_getlink,
13671         .ndo_bridge_setlink     = i40e_ndo_bridge_setlink,
13672         .ndo_bpf                = i40e_xdp,
13673         .ndo_xdp_xmit           = i40e_xdp_xmit,
13674         .ndo_xsk_wakeup         = i40e_xsk_wakeup,
13675         .ndo_dfwd_add_station   = i40e_fwd_add,
13676         .ndo_dfwd_del_station   = i40e_fwd_del,
13677 };
13678
13679 /**
13680  * i40e_config_netdev - Setup the netdev flags
13681  * @vsi: the VSI being configured
13682  *
13683  * Returns 0 on success, negative value on failure
13684  **/
13685 static int i40e_config_netdev(struct i40e_vsi *vsi)
13686 {
13687         struct i40e_pf *pf = vsi->back;
13688         struct i40e_hw *hw = &pf->hw;
13689         struct i40e_netdev_priv *np;
13690         struct net_device *netdev;
13691         u8 broadcast[ETH_ALEN];
13692         u8 mac_addr[ETH_ALEN];
13693         int etherdev_size;
13694         netdev_features_t hw_enc_features;
13695         netdev_features_t hw_features;
13696
13697         etherdev_size = sizeof(struct i40e_netdev_priv);
13698         netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13699         if (!netdev)
13700                 return -ENOMEM;
13701
13702         vsi->netdev = netdev;
13703         np = netdev_priv(netdev);
13704         np->vsi = vsi;
13705
13706         hw_enc_features = NETIF_F_SG                    |
13707                           NETIF_F_HW_CSUM               |
13708                           NETIF_F_HIGHDMA               |
13709                           NETIF_F_SOFT_FEATURES         |
13710                           NETIF_F_TSO                   |
13711                           NETIF_F_TSO_ECN               |
13712                           NETIF_F_TSO6                  |
13713                           NETIF_F_GSO_GRE               |
13714                           NETIF_F_GSO_GRE_CSUM          |
13715                           NETIF_F_GSO_PARTIAL           |
13716                           NETIF_F_GSO_IPXIP4            |
13717                           NETIF_F_GSO_IPXIP6            |
13718                           NETIF_F_GSO_UDP_TUNNEL        |
13719                           NETIF_F_GSO_UDP_TUNNEL_CSUM   |
13720                           NETIF_F_GSO_UDP_L4            |
13721                           NETIF_F_SCTP_CRC              |
13722                           NETIF_F_RXHASH                |
13723                           NETIF_F_RXCSUM                |
13724                           0;
13725
13726         if (!test_bit(I40E_HW_CAP_OUTER_UDP_CSUM, pf->hw.caps))
13727                 netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13728
13729         netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13730
13731         netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13732
13733         netdev->hw_enc_features |= hw_enc_features;
13734
13735         /* record features VLANs can make use of */
13736         netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13737
13738 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |            \
13739                                    NETIF_F_GSO_GRE_CSUM |       \
13740                                    NETIF_F_GSO_IPXIP4 |         \
13741                                    NETIF_F_GSO_IPXIP6 |         \
13742                                    NETIF_F_GSO_UDP_TUNNEL |     \
13743                                    NETIF_F_GSO_UDP_TUNNEL_CSUM)
13744
13745         netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13746         netdev->features |= NETIF_F_GSO_PARTIAL |
13747                             I40E_GSO_PARTIAL_FEATURES;
13748
13749         netdev->mpls_features |= NETIF_F_SG;
13750         netdev->mpls_features |= NETIF_F_HW_CSUM;
13751         netdev->mpls_features |= NETIF_F_TSO;
13752         netdev->mpls_features |= NETIF_F_TSO6;
13753         netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13754
13755         /* enable macvlan offloads */
13756         netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13757
13758         hw_features = hw_enc_features           |
13759                       NETIF_F_HW_VLAN_CTAG_TX   |
13760                       NETIF_F_HW_VLAN_CTAG_RX;
13761
13762         if (!test_bit(I40E_FLAG_MFP_ENA, pf->flags))
13763                 hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13764
13765         netdev->hw_features |= hw_features | NETIF_F_LOOPBACK;
13766
13767         netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13768         netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13769
13770         netdev->features &= ~NETIF_F_HW_TC;
13771
13772         if (vsi->type == I40E_VSI_MAIN) {
13773                 SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13774                 ether_addr_copy(mac_addr, hw->mac.perm_addr);
13775                 /* The following steps are necessary for two reasons. First,
13776                  * some older NVM configurations load a default MAC-VLAN
13777                  * filter that will accept any tagged packet, and we want to
13778                  * replace this with a normal filter. Additionally, it is
13779                  * possible our MAC address was provided by the platform using
13780                  * Open Firmware or similar.
13781                  *
13782                  * Thus, we need to remove the default filter and install one
13783                  * specific to the MAC address.
13784                  */
13785                 i40e_rm_default_mac_filter(vsi, mac_addr);
13786                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13787                 i40e_add_mac_filter(vsi, mac_addr);
13788                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13789
13790                 netdev->xdp_features = NETDEV_XDP_ACT_BASIC |
13791                                        NETDEV_XDP_ACT_REDIRECT |
13792                                        NETDEV_XDP_ACT_XSK_ZEROCOPY |
13793                                        NETDEV_XDP_ACT_RX_SG;
13794                 netdev->xdp_zc_max_segs = I40E_MAX_BUFFER_TXD;
13795         } else {
13796                 /* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13797                  * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13798                  * the end, which is 4 bytes long, so force truncation of the
13799                  * original name by IFNAMSIZ - 4
13800                  */
13801                 snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13802                          IFNAMSIZ - 4,
13803                          pf->vsi[pf->lan_vsi]->netdev->name);
13804                 eth_random_addr(mac_addr);
13805
13806                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13807                 i40e_add_mac_filter(vsi, mac_addr);
13808                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13809         }
13810
13811         /* Add the broadcast filter so that we initially will receive
13812          * broadcast packets. Note that when a new VLAN is first added the
13813          * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13814          * specific filters as part of transitioning into "vlan" operation.
13815          * When more VLANs are added, the driver will copy each existing MAC
13816          * filter and add it for the new VLAN.
13817          *
13818          * Broadcast filters are handled specially by
13819          * i40e_sync_filters_subtask, as the driver must to set the broadcast
13820          * promiscuous bit instead of adding this directly as a MAC/VLAN
13821          * filter. The subtask will update the correct broadcast promiscuous
13822          * bits as VLANs become active or inactive.
13823          */
13824         eth_broadcast_addr(broadcast);
13825         spin_lock_bh(&vsi->mac_filter_hash_lock);
13826         i40e_add_mac_filter(vsi, broadcast);
13827         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13828
13829         eth_hw_addr_set(netdev, mac_addr);
13830         ether_addr_copy(netdev->perm_addr, mac_addr);
13831
13832         /* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13833         netdev->neigh_priv_len = sizeof(u32) * 4;
13834
13835         netdev->priv_flags |= IFF_UNICAST_FLT;
13836         netdev->priv_flags |= IFF_SUPP_NOFCS;
13837         /* Setup netdev TC information */
13838         i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13839
13840         netdev->netdev_ops = &i40e_netdev_ops;
13841         netdev->watchdog_timeo = 5 * HZ;
13842         i40e_set_ethtool_ops(netdev);
13843
13844         /* MTU range: 68 - 9706 */
13845         netdev->min_mtu = ETH_MIN_MTU;
13846         netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13847
13848         return 0;
13849 }
13850
13851 /**
13852  * i40e_vsi_delete - Delete a VSI from the switch
13853  * @vsi: the VSI being removed
13854  *
13855  * Returns 0 on success, negative value on failure
13856  **/
13857 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13858 {
13859         /* remove default VSI is not allowed */
13860         if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13861                 return;
13862
13863         i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13864 }
13865
13866 /**
13867  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13868  * @vsi: the VSI being queried
13869  *
13870  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13871  **/
13872 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13873 {
13874         struct i40e_veb *veb;
13875         struct i40e_pf *pf = vsi->back;
13876
13877         /* Uplink is not a bridge so default to VEB */
13878         if (vsi->veb_idx >= I40E_MAX_VEB)
13879                 return 1;
13880
13881         veb = pf->veb[vsi->veb_idx];
13882         if (!veb) {
13883                 dev_info(&pf->pdev->dev,
13884                          "There is no veb associated with the bridge\n");
13885                 return -ENOENT;
13886         }
13887
13888         /* Uplink is a bridge in VEPA mode */
13889         if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13890                 return 0;
13891         } else {
13892                 /* Uplink is a bridge in VEB mode */
13893                 return 1;
13894         }
13895
13896         /* VEPA is now default bridge, so return 0 */
13897         return 0;
13898 }
13899
13900 /**
13901  * i40e_add_vsi - Add a VSI to the switch
13902  * @vsi: the VSI being configured
13903  *
13904  * This initializes a VSI context depending on the VSI type to be added and
13905  * passes it down to the add_vsi aq command.
13906  **/
13907 static int i40e_add_vsi(struct i40e_vsi *vsi)
13908 {
13909         int ret = -ENODEV;
13910         struct i40e_pf *pf = vsi->back;
13911         struct i40e_hw *hw = &pf->hw;
13912         struct i40e_vsi_context ctxt;
13913         struct i40e_mac_filter *f;
13914         struct hlist_node *h;
13915         int bkt;
13916
13917         u8 enabled_tc = 0x1; /* TC0 enabled */
13918         int f_count = 0;
13919
13920         memset(&ctxt, 0, sizeof(ctxt));
13921         switch (vsi->type) {
13922         case I40E_VSI_MAIN:
13923                 /* The PF's main VSI is already setup as part of the
13924                  * device initialization, so we'll not bother with
13925                  * the add_vsi call, but we will retrieve the current
13926                  * VSI context.
13927                  */
13928                 ctxt.seid = pf->main_vsi_seid;
13929                 ctxt.pf_num = pf->hw.pf_id;
13930                 ctxt.vf_num = 0;
13931                 ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13932                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13933                 if (ret) {
13934                         dev_info(&pf->pdev->dev,
13935                                  "couldn't get PF vsi config, err %pe aq_err %s\n",
13936                                  ERR_PTR(ret),
13937                                  i40e_aq_str(&pf->hw,
13938                                              pf->hw.aq.asq_last_status));
13939                         return -ENOENT;
13940                 }
13941                 vsi->info = ctxt.info;
13942                 vsi->info.valid_sections = 0;
13943
13944                 vsi->seid = ctxt.seid;
13945                 vsi->id = ctxt.vsi_number;
13946
13947                 enabled_tc = i40e_pf_get_tc_map(pf);
13948
13949                 /* Source pruning is enabled by default, so the flag is
13950                  * negative logic - if it's set, we need to fiddle with
13951                  * the VSI to disable source pruning.
13952                  */
13953                 if (test_bit(I40E_FLAG_SOURCE_PRUNING_DIS, pf->flags)) {
13954                         memset(&ctxt, 0, sizeof(ctxt));
13955                         ctxt.seid = pf->main_vsi_seid;
13956                         ctxt.pf_num = pf->hw.pf_id;
13957                         ctxt.vf_num = 0;
13958                         ctxt.info.valid_sections |=
13959                                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13960                         ctxt.info.switch_id =
13961                                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13962                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13963                         if (ret) {
13964                                 dev_info(&pf->pdev->dev,
13965                                          "update vsi failed, err %d aq_err %s\n",
13966                                          ret,
13967                                          i40e_aq_str(&pf->hw,
13968                                                      pf->hw.aq.asq_last_status));
13969                                 ret = -ENOENT;
13970                                 goto err;
13971                         }
13972                 }
13973
13974                 /* MFP mode setup queue map and update VSI */
13975                 if (test_bit(I40E_FLAG_MFP_ENA, pf->flags) &&
13976                     !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13977                         memset(&ctxt, 0, sizeof(ctxt));
13978                         ctxt.seid = pf->main_vsi_seid;
13979                         ctxt.pf_num = pf->hw.pf_id;
13980                         ctxt.vf_num = 0;
13981                         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13982                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13983                         if (ret) {
13984                                 dev_info(&pf->pdev->dev,
13985                                          "update vsi failed, err %pe aq_err %s\n",
13986                                          ERR_PTR(ret),
13987                                          i40e_aq_str(&pf->hw,
13988                                                     pf->hw.aq.asq_last_status));
13989                                 ret = -ENOENT;
13990                                 goto err;
13991                         }
13992                         /* update the local VSI info queue map */
13993                         i40e_vsi_update_queue_map(vsi, &ctxt);
13994                         vsi->info.valid_sections = 0;
13995                 } else {
13996                         /* Default/Main VSI is only enabled for TC0
13997                          * reconfigure it to enable all TCs that are
13998                          * available on the port in SFP mode.
13999                          * For MFP case the iSCSI PF would use this
14000                          * flow to enable LAN+iSCSI TC.
14001                          */
14002                         ret = i40e_vsi_config_tc(vsi, enabled_tc);
14003                         if (ret) {
14004                                 /* Single TC condition is not fatal,
14005                                  * message and continue
14006                                  */
14007                                 dev_info(&pf->pdev->dev,
14008                                          "failed to configure TCs for main VSI tc_map 0x%08x, err %pe aq_err %s\n",
14009                                          enabled_tc,
14010                                          ERR_PTR(ret),
14011                                          i40e_aq_str(&pf->hw,
14012                                                     pf->hw.aq.asq_last_status));
14013                         }
14014                 }
14015                 break;
14016
14017         case I40E_VSI_FDIR:
14018                 ctxt.pf_num = hw->pf_id;
14019                 ctxt.vf_num = 0;
14020                 ctxt.uplink_seid = vsi->uplink_seid;
14021                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14022                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
14023                 if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags) &&
14024                     (i40e_is_vsi_uplink_mode_veb(vsi))) {
14025                         ctxt.info.valid_sections |=
14026                              cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14027                         ctxt.info.switch_id =
14028                            cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14029                 }
14030                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14031                 break;
14032
14033         case I40E_VSI_VMDQ2:
14034                 ctxt.pf_num = hw->pf_id;
14035                 ctxt.vf_num = 0;
14036                 ctxt.uplink_seid = vsi->uplink_seid;
14037                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14038                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
14039
14040                 /* This VSI is connected to VEB so the switch_id
14041                  * should be set to zero by default.
14042                  */
14043                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14044                         ctxt.info.valid_sections |=
14045                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14046                         ctxt.info.switch_id =
14047                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14048                 }
14049
14050                 /* Setup the VSI tx/rx queue map for TC0 only for now */
14051                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14052                 break;
14053
14054         case I40E_VSI_SRIOV:
14055                 ctxt.pf_num = hw->pf_id;
14056                 ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
14057                 ctxt.uplink_seid = vsi->uplink_seid;
14058                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
14059                 ctxt.flags = I40E_AQ_VSI_TYPE_VF;
14060
14061                 /* This VSI is connected to VEB so the switch_id
14062                  * should be set to zero by default.
14063                  */
14064                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
14065                         ctxt.info.valid_sections |=
14066                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
14067                         ctxt.info.switch_id =
14068                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
14069                 }
14070
14071                 if (test_bit(I40E_FLAG_IWARP_ENA, vsi->back->flags)) {
14072                         ctxt.info.valid_sections |=
14073                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
14074                         ctxt.info.queueing_opt_flags |=
14075                                 (I40E_AQ_VSI_QUE_OPT_TCP_ENA |
14076                                  I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
14077                 }
14078
14079                 ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
14080                 ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
14081                 if (pf->vf[vsi->vf_id].spoofchk) {
14082                         ctxt.info.valid_sections |=
14083                                 cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
14084                         ctxt.info.sec_flags |=
14085                                 (I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
14086                                  I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
14087                 }
14088                 /* Setup the VSI tx/rx queue map for TC0 only for now */
14089                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
14090                 break;
14091
14092         case I40E_VSI_IWARP:
14093                 /* send down message to iWARP */
14094                 break;
14095
14096         default:
14097                 return -ENODEV;
14098         }
14099
14100         if (vsi->type != I40E_VSI_MAIN) {
14101                 ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
14102                 if (ret) {
14103                         dev_info(&vsi->back->pdev->dev,
14104                                  "add vsi failed, err %pe aq_err %s\n",
14105                                  ERR_PTR(ret),
14106                                  i40e_aq_str(&pf->hw,
14107                                              pf->hw.aq.asq_last_status));
14108                         ret = -ENOENT;
14109                         goto err;
14110                 }
14111                 vsi->info = ctxt.info;
14112                 vsi->info.valid_sections = 0;
14113                 vsi->seid = ctxt.seid;
14114                 vsi->id = ctxt.vsi_number;
14115         }
14116
14117         spin_lock_bh(&vsi->mac_filter_hash_lock);
14118         vsi->active_filters = 0;
14119         /* If macvlan filters already exist, force them to get loaded */
14120         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
14121                 f->state = I40E_FILTER_NEW;
14122                 f_count++;
14123         }
14124         spin_unlock_bh(&vsi->mac_filter_hash_lock);
14125         clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
14126
14127         if (f_count) {
14128                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
14129                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
14130         }
14131
14132         /* Update VSI BW information */
14133         ret = i40e_vsi_get_bw_info(vsi);
14134         if (ret) {
14135                 dev_info(&pf->pdev->dev,
14136                          "couldn't get vsi bw info, err %pe aq_err %s\n",
14137                          ERR_PTR(ret),
14138                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14139                 /* VSI is already added so not tearing that up */
14140                 ret = 0;
14141         }
14142
14143 err:
14144         return ret;
14145 }
14146
14147 /**
14148  * i40e_vsi_release - Delete a VSI and free its resources
14149  * @vsi: the VSI being removed
14150  *
14151  * Returns 0 on success or < 0 on error
14152  **/
14153 int i40e_vsi_release(struct i40e_vsi *vsi)
14154 {
14155         struct i40e_mac_filter *f;
14156         struct hlist_node *h;
14157         struct i40e_veb *veb = NULL;
14158         struct i40e_pf *pf;
14159         u16 uplink_seid;
14160         int i, n, bkt;
14161
14162         pf = vsi->back;
14163
14164         /* release of a VEB-owner or last VSI is not allowed */
14165         if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
14166                 dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
14167                          vsi->seid, vsi->uplink_seid);
14168                 return -ENODEV;
14169         }
14170         if (vsi == pf->vsi[pf->lan_vsi] &&
14171             !test_bit(__I40E_DOWN, pf->state)) {
14172                 dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
14173                 return -ENODEV;
14174         }
14175         set_bit(__I40E_VSI_RELEASING, vsi->state);
14176         uplink_seid = vsi->uplink_seid;
14177
14178         if (vsi->type != I40E_VSI_SRIOV) {
14179                 if (vsi->netdev_registered) {
14180                         vsi->netdev_registered = false;
14181                         if (vsi->netdev) {
14182                                 /* results in a call to i40e_close() */
14183                                 unregister_netdev(vsi->netdev);
14184                         }
14185                 } else {
14186                         i40e_vsi_close(vsi);
14187                 }
14188                 i40e_vsi_disable_irq(vsi);
14189         }
14190
14191         if (vsi->type == I40E_VSI_MAIN)
14192                 i40e_devlink_destroy_port(pf);
14193
14194         spin_lock_bh(&vsi->mac_filter_hash_lock);
14195
14196         /* clear the sync flag on all filters */
14197         if (vsi->netdev) {
14198                 __dev_uc_unsync(vsi->netdev, NULL);
14199                 __dev_mc_unsync(vsi->netdev, NULL);
14200         }
14201
14202         /* make sure any remaining filters are marked for deletion */
14203         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14204                 __i40e_del_filter(vsi, f);
14205
14206         spin_unlock_bh(&vsi->mac_filter_hash_lock);
14207
14208         i40e_sync_vsi_filters(vsi);
14209
14210         i40e_vsi_delete(vsi);
14211         i40e_vsi_free_q_vectors(vsi);
14212         if (vsi->netdev) {
14213                 free_netdev(vsi->netdev);
14214                 vsi->netdev = NULL;
14215         }
14216         i40e_vsi_clear_rings(vsi);
14217         i40e_vsi_clear(vsi);
14218
14219         /* If this was the last thing on the VEB, except for the
14220          * controlling VSI, remove the VEB, which puts the controlling
14221          * VSI onto the next level down in the switch.
14222          *
14223          * Well, okay, there's one more exception here: don't remove
14224          * the orphan VEBs yet.  We'll wait for an explicit remove request
14225          * from up the network stack.
14226          */
14227         for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14228                 if (pf->vsi[i] &&
14229                     pf->vsi[i]->uplink_seid == uplink_seid &&
14230                     (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14231                         n++;      /* count the VSIs */
14232                 }
14233         }
14234         for (i = 0; i < I40E_MAX_VEB; i++) {
14235                 if (!pf->veb[i])
14236                         continue;
14237                 if (pf->veb[i]->uplink_seid == uplink_seid)
14238                         n++;     /* count the VEBs */
14239                 if (pf->veb[i]->seid == uplink_seid)
14240                         veb = pf->veb[i];
14241         }
14242         if (n == 0 && veb && veb->uplink_seid != 0)
14243                 i40e_veb_release(veb);
14244
14245         return 0;
14246 }
14247
14248 /**
14249  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14250  * @vsi: ptr to the VSI
14251  *
14252  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14253  * corresponding SW VSI structure and initializes num_queue_pairs for the
14254  * newly allocated VSI.
14255  *
14256  * Returns 0 on success or negative on failure
14257  **/
14258 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14259 {
14260         int ret = -ENOENT;
14261         struct i40e_pf *pf = vsi->back;
14262
14263         if (vsi->q_vectors[0]) {
14264                 dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14265                          vsi->seid);
14266                 return -EEXIST;
14267         }
14268
14269         if (vsi->base_vector) {
14270                 dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14271                          vsi->seid, vsi->base_vector);
14272                 return -EEXIST;
14273         }
14274
14275         ret = i40e_vsi_alloc_q_vectors(vsi);
14276         if (ret) {
14277                 dev_info(&pf->pdev->dev,
14278                          "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14279                          vsi->num_q_vectors, vsi->seid, ret);
14280                 vsi->num_q_vectors = 0;
14281                 goto vector_setup_out;
14282         }
14283
14284         /* In Legacy mode, we do not have to get any other vector since we
14285          * piggyback on the misc/ICR0 for queue interrupts.
14286         */
14287         if (!test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
14288                 return ret;
14289         if (vsi->num_q_vectors)
14290                 vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14291                                                  vsi->num_q_vectors, vsi->idx);
14292         if (vsi->base_vector < 0) {
14293                 dev_info(&pf->pdev->dev,
14294                          "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14295                          vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14296                 i40e_vsi_free_q_vectors(vsi);
14297                 ret = -ENOENT;
14298                 goto vector_setup_out;
14299         }
14300
14301 vector_setup_out:
14302         return ret;
14303 }
14304
14305 /**
14306  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14307  * @vsi: pointer to the vsi.
14308  *
14309  * This re-allocates a vsi's queue resources.
14310  *
14311  * Returns pointer to the successfully allocated and configured VSI sw struct
14312  * on success, otherwise returns NULL on failure.
14313  **/
14314 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14315 {
14316         u16 alloc_queue_pairs;
14317         struct i40e_pf *pf;
14318         u8 enabled_tc;
14319         int ret;
14320
14321         if (!vsi)
14322                 return NULL;
14323
14324         pf = vsi->back;
14325
14326         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14327         i40e_vsi_clear_rings(vsi);
14328
14329         i40e_vsi_free_arrays(vsi, false);
14330         i40e_set_num_rings_in_vsi(vsi);
14331         ret = i40e_vsi_alloc_arrays(vsi, false);
14332         if (ret)
14333                 goto err_vsi;
14334
14335         alloc_queue_pairs = vsi->alloc_queue_pairs *
14336                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14337
14338         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14339         if (ret < 0) {
14340                 dev_info(&pf->pdev->dev,
14341                          "failed to get tracking for %d queues for VSI %d err %d\n",
14342                          alloc_queue_pairs, vsi->seid, ret);
14343                 goto err_vsi;
14344         }
14345         vsi->base_queue = ret;
14346
14347         /* Update the FW view of the VSI. Force a reset of TC and queue
14348          * layout configurations.
14349          */
14350         enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14351         pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14352         pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14353         i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14354         if (vsi->type == I40E_VSI_MAIN)
14355                 i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14356
14357         /* assign it some queues */
14358         ret = i40e_alloc_rings(vsi);
14359         if (ret)
14360                 goto err_rings;
14361
14362         /* map all of the rings to the q_vectors */
14363         i40e_vsi_map_rings_to_vectors(vsi);
14364         return vsi;
14365
14366 err_rings:
14367         i40e_vsi_free_q_vectors(vsi);
14368         if (vsi->netdev_registered) {
14369                 vsi->netdev_registered = false;
14370                 unregister_netdev(vsi->netdev);
14371                 free_netdev(vsi->netdev);
14372                 vsi->netdev = NULL;
14373         }
14374         if (vsi->type == I40E_VSI_MAIN)
14375                 i40e_devlink_destroy_port(pf);
14376         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14377 err_vsi:
14378         i40e_vsi_clear(vsi);
14379         return NULL;
14380 }
14381
14382 /**
14383  * i40e_vsi_setup - Set up a VSI by a given type
14384  * @pf: board private structure
14385  * @type: VSI type
14386  * @uplink_seid: the switch element to link to
14387  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14388  *
14389  * This allocates the sw VSI structure and its queue resources, then add a VSI
14390  * to the identified VEB.
14391  *
14392  * Returns pointer to the successfully allocated and configure VSI sw struct on
14393  * success, otherwise returns NULL on failure.
14394  **/
14395 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14396                                 u16 uplink_seid, u32 param1)
14397 {
14398         struct i40e_vsi *vsi = NULL;
14399         struct i40e_veb *veb = NULL;
14400         u16 alloc_queue_pairs;
14401         int ret, i;
14402         int v_idx;
14403
14404         /* The requested uplink_seid must be either
14405          *     - the PF's port seid
14406          *              no VEB is needed because this is the PF
14407          *              or this is a Flow Director special case VSI
14408          *     - seid of an existing VEB
14409          *     - seid of a VSI that owns an existing VEB
14410          *     - seid of a VSI that doesn't own a VEB
14411          *              a new VEB is created and the VSI becomes the owner
14412          *     - seid of the PF VSI, which is what creates the first VEB
14413          *              this is a special case of the previous
14414          *
14415          * Find which uplink_seid we were given and create a new VEB if needed
14416          */
14417         for (i = 0; i < I40E_MAX_VEB; i++) {
14418                 if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14419                         veb = pf->veb[i];
14420                         break;
14421                 }
14422         }
14423
14424         if (!veb && uplink_seid != pf->mac_seid) {
14425
14426                 for (i = 0; i < pf->num_alloc_vsi; i++) {
14427                         if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14428                                 vsi = pf->vsi[i];
14429                                 break;
14430                         }
14431                 }
14432                 if (!vsi) {
14433                         dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14434                                  uplink_seid);
14435                         return NULL;
14436                 }
14437
14438                 if (vsi->uplink_seid == pf->mac_seid)
14439                         veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14440                                              vsi->tc_config.enabled_tc);
14441                 else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14442                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14443                                              vsi->tc_config.enabled_tc);
14444                 if (veb) {
14445                         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14446                                 dev_info(&vsi->back->pdev->dev,
14447                                          "New VSI creation error, uplink seid of LAN VSI expected.\n");
14448                                 return NULL;
14449                         }
14450                         /* We come up by default in VEPA mode if SRIOV is not
14451                          * already enabled, in which case we can't force VEPA
14452                          * mode.
14453                          */
14454                         if (!test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags)) {
14455                                 veb->bridge_mode = BRIDGE_MODE_VEPA;
14456                                 clear_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
14457                         }
14458                         i40e_config_bridge_mode(veb);
14459                 }
14460                 for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14461                         if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14462                                 veb = pf->veb[i];
14463                 }
14464                 if (!veb) {
14465                         dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14466                         return NULL;
14467                 }
14468
14469                 vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14470                 uplink_seid = veb->seid;
14471         }
14472
14473         /* get vsi sw struct */
14474         v_idx = i40e_vsi_mem_alloc(pf, type);
14475         if (v_idx < 0)
14476                 goto err_alloc;
14477         vsi = pf->vsi[v_idx];
14478         if (!vsi)
14479                 goto err_alloc;
14480         vsi->type = type;
14481         vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14482
14483         if (type == I40E_VSI_MAIN)
14484                 pf->lan_vsi = v_idx;
14485         else if (type == I40E_VSI_SRIOV)
14486                 vsi->vf_id = param1;
14487         /* assign it some queues */
14488         alloc_queue_pairs = vsi->alloc_queue_pairs *
14489                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14490
14491         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14492         if (ret < 0) {
14493                 dev_info(&pf->pdev->dev,
14494                          "failed to get tracking for %d queues for VSI %d err=%d\n",
14495                          alloc_queue_pairs, vsi->seid, ret);
14496                 goto err_vsi;
14497         }
14498         vsi->base_queue = ret;
14499
14500         /* get a VSI from the hardware */
14501         vsi->uplink_seid = uplink_seid;
14502         ret = i40e_add_vsi(vsi);
14503         if (ret)
14504                 goto err_vsi;
14505
14506         switch (vsi->type) {
14507         /* setup the netdev if needed */
14508         case I40E_VSI_MAIN:
14509         case I40E_VSI_VMDQ2:
14510                 ret = i40e_config_netdev(vsi);
14511                 if (ret)
14512                         goto err_netdev;
14513                 ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14514                 if (ret)
14515                         goto err_netdev;
14516                 if (vsi->type == I40E_VSI_MAIN) {
14517                         ret = i40e_devlink_create_port(pf);
14518                         if (ret)
14519                                 goto err_netdev;
14520                         SET_NETDEV_DEVLINK_PORT(vsi->netdev, &pf->devlink_port);
14521                 }
14522                 ret = register_netdev(vsi->netdev);
14523                 if (ret)
14524                         goto err_dl_port;
14525                 vsi->netdev_registered = true;
14526                 netif_carrier_off(vsi->netdev);
14527 #ifdef CONFIG_I40E_DCB
14528                 /* Setup DCB netlink interface */
14529                 i40e_dcbnl_setup(vsi);
14530 #endif /* CONFIG_I40E_DCB */
14531                 fallthrough;
14532         case I40E_VSI_FDIR:
14533                 /* set up vectors and rings if needed */
14534                 ret = i40e_vsi_setup_vectors(vsi);
14535                 if (ret)
14536                         goto err_msix;
14537
14538                 ret = i40e_alloc_rings(vsi);
14539                 if (ret)
14540                         goto err_rings;
14541
14542                 /* map all of the rings to the q_vectors */
14543                 i40e_vsi_map_rings_to_vectors(vsi);
14544
14545                 i40e_vsi_reset_stats(vsi);
14546                 break;
14547         default:
14548                 /* no netdev or rings for the other VSI types */
14549                 break;
14550         }
14551
14552         if (test_bit(I40E_HW_CAP_RSS_AQ, pf->hw.caps) &&
14553             vsi->type == I40E_VSI_VMDQ2) {
14554                 ret = i40e_vsi_config_rss(vsi);
14555                 if (ret)
14556                         goto err_config;
14557         }
14558         return vsi;
14559
14560 err_config:
14561         i40e_vsi_clear_rings(vsi);
14562 err_rings:
14563         i40e_vsi_free_q_vectors(vsi);
14564 err_msix:
14565         if (vsi->netdev_registered) {
14566                 vsi->netdev_registered = false;
14567                 unregister_netdev(vsi->netdev);
14568                 free_netdev(vsi->netdev);
14569                 vsi->netdev = NULL;
14570         }
14571 err_dl_port:
14572         if (vsi->type == I40E_VSI_MAIN)
14573                 i40e_devlink_destroy_port(pf);
14574 err_netdev:
14575         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14576 err_vsi:
14577         i40e_vsi_clear(vsi);
14578 err_alloc:
14579         return NULL;
14580 }
14581
14582 /**
14583  * i40e_veb_get_bw_info - Query VEB BW information
14584  * @veb: the veb to query
14585  *
14586  * Query the Tx scheduler BW configuration data for given VEB
14587  **/
14588 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14589 {
14590         struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14591         struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14592         struct i40e_pf *pf = veb->pf;
14593         struct i40e_hw *hw = &pf->hw;
14594         u32 tc_bw_max;
14595         int ret = 0;
14596         int i;
14597
14598         ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14599                                                   &bw_data, NULL);
14600         if (ret) {
14601                 dev_info(&pf->pdev->dev,
14602                          "query veb bw config failed, err %pe aq_err %s\n",
14603                          ERR_PTR(ret),
14604                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14605                 goto out;
14606         }
14607
14608         ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14609                                                    &ets_data, NULL);
14610         if (ret) {
14611                 dev_info(&pf->pdev->dev,
14612                          "query veb bw ets config failed, err %pe aq_err %s\n",
14613                          ERR_PTR(ret),
14614                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14615                 goto out;
14616         }
14617
14618         veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14619         veb->bw_max_quanta = ets_data.tc_bw_max;
14620         veb->is_abs_credits = bw_data.absolute_credits_enable;
14621         veb->enabled_tc = ets_data.tc_valid_bits;
14622         tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14623                     (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14624         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14625                 veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14626                 veb->bw_tc_limit_credits[i] =
14627                                         le16_to_cpu(bw_data.tc_bw_limits[i]);
14628                 veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14629         }
14630
14631 out:
14632         return ret;
14633 }
14634
14635 /**
14636  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14637  * @pf: board private structure
14638  *
14639  * On error: returns error code (negative)
14640  * On success: returns vsi index in PF (positive)
14641  **/
14642 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14643 {
14644         int ret = -ENOENT;
14645         struct i40e_veb *veb;
14646         int i;
14647
14648         /* Need to protect the allocation of switch elements at the PF level */
14649         mutex_lock(&pf->switch_mutex);
14650
14651         /* VEB list may be fragmented if VEB creation/destruction has
14652          * been happening.  We can afford to do a quick scan to look
14653          * for any free slots in the list.
14654          *
14655          * find next empty veb slot, looping back around if necessary
14656          */
14657         i = 0;
14658         while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14659                 i++;
14660         if (i >= I40E_MAX_VEB) {
14661                 ret = -ENOMEM;
14662                 goto err_alloc_veb;  /* out of VEB slots! */
14663         }
14664
14665         veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14666         if (!veb) {
14667                 ret = -ENOMEM;
14668                 goto err_alloc_veb;
14669         }
14670         veb->pf = pf;
14671         veb->idx = i;
14672         veb->enabled_tc = 1;
14673
14674         pf->veb[i] = veb;
14675         ret = i;
14676 err_alloc_veb:
14677         mutex_unlock(&pf->switch_mutex);
14678         return ret;
14679 }
14680
14681 /**
14682  * i40e_switch_branch_release - Delete a branch of the switch tree
14683  * @branch: where to start deleting
14684  *
14685  * This uses recursion to find the tips of the branch to be
14686  * removed, deleting until we get back to and can delete this VEB.
14687  **/
14688 static void i40e_switch_branch_release(struct i40e_veb *branch)
14689 {
14690         struct i40e_pf *pf = branch->pf;
14691         u16 branch_seid = branch->seid;
14692         u16 veb_idx = branch->idx;
14693         int i;
14694
14695         /* release any VEBs on this VEB - RECURSION */
14696         for (i = 0; i < I40E_MAX_VEB; i++) {
14697                 if (!pf->veb[i])
14698                         continue;
14699                 if (pf->veb[i]->uplink_seid == branch->seid)
14700                         i40e_switch_branch_release(pf->veb[i]);
14701         }
14702
14703         /* Release the VSIs on this VEB, but not the owner VSI.
14704          *
14705          * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14706          *       the VEB itself, so don't use (*branch) after this loop.
14707          */
14708         for (i = 0; i < pf->num_alloc_vsi; i++) {
14709                 if (!pf->vsi[i])
14710                         continue;
14711                 if (pf->vsi[i]->uplink_seid == branch_seid &&
14712                    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14713                         i40e_vsi_release(pf->vsi[i]);
14714                 }
14715         }
14716
14717         /* There's one corner case where the VEB might not have been
14718          * removed, so double check it here and remove it if needed.
14719          * This case happens if the veb was created from the debugfs
14720          * commands and no VSIs were added to it.
14721          */
14722         if (pf->veb[veb_idx])
14723                 i40e_veb_release(pf->veb[veb_idx]);
14724 }
14725
14726 /**
14727  * i40e_veb_clear - remove veb struct
14728  * @veb: the veb to remove
14729  **/
14730 static void i40e_veb_clear(struct i40e_veb *veb)
14731 {
14732         if (!veb)
14733                 return;
14734
14735         if (veb->pf) {
14736                 struct i40e_pf *pf = veb->pf;
14737
14738                 mutex_lock(&pf->switch_mutex);
14739                 if (pf->veb[veb->idx] == veb)
14740                         pf->veb[veb->idx] = NULL;
14741                 mutex_unlock(&pf->switch_mutex);
14742         }
14743
14744         kfree(veb);
14745 }
14746
14747 /**
14748  * i40e_veb_release - Delete a VEB and free its resources
14749  * @veb: the VEB being removed
14750  **/
14751 void i40e_veb_release(struct i40e_veb *veb)
14752 {
14753         struct i40e_vsi *vsi = NULL;
14754         struct i40e_pf *pf;
14755         int i, n = 0;
14756
14757         pf = veb->pf;
14758
14759         /* find the remaining VSI and check for extras */
14760         for (i = 0; i < pf->num_alloc_vsi; i++) {
14761                 if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14762                         n++;
14763                         vsi = pf->vsi[i];
14764                 }
14765         }
14766         if (n != 1) {
14767                 dev_info(&pf->pdev->dev,
14768                          "can't remove VEB %d with %d VSIs left\n",
14769                          veb->seid, n);
14770                 return;
14771         }
14772
14773         /* move the remaining VSI to uplink veb */
14774         vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14775         if (veb->uplink_seid) {
14776                 vsi->uplink_seid = veb->uplink_seid;
14777                 if (veb->uplink_seid == pf->mac_seid)
14778                         vsi->veb_idx = I40E_NO_VEB;
14779                 else
14780                         vsi->veb_idx = veb->veb_idx;
14781         } else {
14782                 /* floating VEB */
14783                 vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14784                 vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14785         }
14786
14787         i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14788         i40e_veb_clear(veb);
14789 }
14790
14791 /**
14792  * i40e_add_veb - create the VEB in the switch
14793  * @veb: the VEB to be instantiated
14794  * @vsi: the controlling VSI
14795  **/
14796 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14797 {
14798         struct i40e_pf *pf = veb->pf;
14799         bool enable_stats = !!test_bit(I40E_FLAG_VEB_STATS_ENA, pf->flags);
14800         int ret;
14801
14802         ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14803                               veb->enabled_tc, false,
14804                               &veb->seid, enable_stats, NULL);
14805
14806         /* get a VEB from the hardware */
14807         if (ret) {
14808                 dev_info(&pf->pdev->dev,
14809                          "couldn't add VEB, err %pe aq_err %s\n",
14810                          ERR_PTR(ret),
14811                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14812                 return -EPERM;
14813         }
14814
14815         /* get statistics counter */
14816         ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14817                                          &veb->stats_idx, NULL, NULL, NULL);
14818         if (ret) {
14819                 dev_info(&pf->pdev->dev,
14820                          "couldn't get VEB statistics idx, err %pe aq_err %s\n",
14821                          ERR_PTR(ret),
14822                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14823                 return -EPERM;
14824         }
14825         ret = i40e_veb_get_bw_info(veb);
14826         if (ret) {
14827                 dev_info(&pf->pdev->dev,
14828                          "couldn't get VEB bw info, err %pe aq_err %s\n",
14829                          ERR_PTR(ret),
14830                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14831                 i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14832                 return -ENOENT;
14833         }
14834
14835         vsi->uplink_seid = veb->seid;
14836         vsi->veb_idx = veb->idx;
14837         vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14838
14839         return 0;
14840 }
14841
14842 /**
14843  * i40e_veb_setup - Set up a VEB
14844  * @pf: board private structure
14845  * @flags: VEB setup flags
14846  * @uplink_seid: the switch element to link to
14847  * @vsi_seid: the initial VSI seid
14848  * @enabled_tc: Enabled TC bit-map
14849  *
14850  * This allocates the sw VEB structure and links it into the switch
14851  * It is possible and legal for this to be a duplicate of an already
14852  * existing VEB.  It is also possible for both uplink and vsi seids
14853  * to be zero, in order to create a floating VEB.
14854  *
14855  * Returns pointer to the successfully allocated VEB sw struct on
14856  * success, otherwise returns NULL on failure.
14857  **/
14858 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14859                                 u16 uplink_seid, u16 vsi_seid,
14860                                 u8 enabled_tc)
14861 {
14862         struct i40e_veb *veb, *uplink_veb = NULL;
14863         int vsi_idx, veb_idx;
14864         int ret;
14865
14866         /* if one seid is 0, the other must be 0 to create a floating relay */
14867         if ((uplink_seid == 0 || vsi_seid == 0) &&
14868             (uplink_seid + vsi_seid != 0)) {
14869                 dev_info(&pf->pdev->dev,
14870                          "one, not both seid's are 0: uplink=%d vsi=%d\n",
14871                          uplink_seid, vsi_seid);
14872                 return NULL;
14873         }
14874
14875         /* make sure there is such a vsi and uplink */
14876         for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14877                 if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14878                         break;
14879         if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14880                 dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14881                          vsi_seid);
14882                 return NULL;
14883         }
14884
14885         if (uplink_seid && uplink_seid != pf->mac_seid) {
14886                 for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14887                         if (pf->veb[veb_idx] &&
14888                             pf->veb[veb_idx]->seid == uplink_seid) {
14889                                 uplink_veb = pf->veb[veb_idx];
14890                                 break;
14891                         }
14892                 }
14893                 if (!uplink_veb) {
14894                         dev_info(&pf->pdev->dev,
14895                                  "uplink seid %d not found\n", uplink_seid);
14896                         return NULL;
14897                 }
14898         }
14899
14900         /* get veb sw struct */
14901         veb_idx = i40e_veb_mem_alloc(pf);
14902         if (veb_idx < 0)
14903                 goto err_alloc;
14904         veb = pf->veb[veb_idx];
14905         veb->flags = flags;
14906         veb->uplink_seid = uplink_seid;
14907         veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14908         veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14909
14910         /* create the VEB in the switch */
14911         ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14912         if (ret)
14913                 goto err_veb;
14914         if (vsi_idx == pf->lan_vsi)
14915                 pf->lan_veb = veb->idx;
14916
14917         return veb;
14918
14919 err_veb:
14920         i40e_veb_clear(veb);
14921 err_alloc:
14922         return NULL;
14923 }
14924
14925 /**
14926  * i40e_setup_pf_switch_element - set PF vars based on switch type
14927  * @pf: board private structure
14928  * @ele: element we are building info from
14929  * @num_reported: total number of elements
14930  * @printconfig: should we print the contents
14931  *
14932  * helper function to assist in extracting a few useful SEID values.
14933  **/
14934 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14935                                 struct i40e_aqc_switch_config_element_resp *ele,
14936                                 u16 num_reported, bool printconfig)
14937 {
14938         u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14939         u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14940         u8 element_type = ele->element_type;
14941         u16 seid = le16_to_cpu(ele->seid);
14942
14943         if (printconfig)
14944                 dev_info(&pf->pdev->dev,
14945                          "type=%d seid=%d uplink=%d downlink=%d\n",
14946                          element_type, seid, uplink_seid, downlink_seid);
14947
14948         switch (element_type) {
14949         case I40E_SWITCH_ELEMENT_TYPE_MAC:
14950                 pf->mac_seid = seid;
14951                 break;
14952         case I40E_SWITCH_ELEMENT_TYPE_VEB:
14953                 /* Main VEB? */
14954                 if (uplink_seid != pf->mac_seid)
14955                         break;
14956                 if (pf->lan_veb >= I40E_MAX_VEB) {
14957                         int v;
14958
14959                         /* find existing or else empty VEB */
14960                         for (v = 0; v < I40E_MAX_VEB; v++) {
14961                                 if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14962                                         pf->lan_veb = v;
14963                                         break;
14964                                 }
14965                         }
14966                         if (pf->lan_veb >= I40E_MAX_VEB) {
14967                                 v = i40e_veb_mem_alloc(pf);
14968                                 if (v < 0)
14969                                         break;
14970                                 pf->lan_veb = v;
14971                         }
14972                 }
14973                 if (pf->lan_veb >= I40E_MAX_VEB)
14974                         break;
14975
14976                 pf->veb[pf->lan_veb]->seid = seid;
14977                 pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14978                 pf->veb[pf->lan_veb]->pf = pf;
14979                 pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14980                 break;
14981         case I40E_SWITCH_ELEMENT_TYPE_VSI:
14982                 if (num_reported != 1)
14983                         break;
14984                 /* This is immediately after a reset so we can assume this is
14985                  * the PF's VSI
14986                  */
14987                 pf->mac_seid = uplink_seid;
14988                 pf->main_vsi_seid = seid;
14989                 if (printconfig)
14990                         dev_info(&pf->pdev->dev,
14991                                  "pf_seid=%d main_vsi_seid=%d\n",
14992                                  downlink_seid, pf->main_vsi_seid);
14993                 break;
14994         case I40E_SWITCH_ELEMENT_TYPE_PF:
14995         case I40E_SWITCH_ELEMENT_TYPE_VF:
14996         case I40E_SWITCH_ELEMENT_TYPE_EMP:
14997         case I40E_SWITCH_ELEMENT_TYPE_BMC:
14998         case I40E_SWITCH_ELEMENT_TYPE_PE:
14999         case I40E_SWITCH_ELEMENT_TYPE_PA:
15000                 /* ignore these for now */
15001                 break;
15002         default:
15003                 dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
15004                          element_type, seid);
15005                 break;
15006         }
15007 }
15008
15009 /**
15010  * i40e_fetch_switch_configuration - Get switch config from firmware
15011  * @pf: board private structure
15012  * @printconfig: should we print the contents
15013  *
15014  * Get the current switch configuration from the device and
15015  * extract a few useful SEID values.
15016  **/
15017 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
15018 {
15019         struct i40e_aqc_get_switch_config_resp *sw_config;
15020         u16 next_seid = 0;
15021         int ret = 0;
15022         u8 *aq_buf;
15023         int i;
15024
15025         aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
15026         if (!aq_buf)
15027                 return -ENOMEM;
15028
15029         sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
15030         do {
15031                 u16 num_reported, num_total;
15032
15033                 ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
15034                                                 I40E_AQ_LARGE_BUF,
15035                                                 &next_seid, NULL);
15036                 if (ret) {
15037                         dev_info(&pf->pdev->dev,
15038                                  "get switch config failed err %d aq_err %s\n",
15039                                  ret,
15040                                  i40e_aq_str(&pf->hw,
15041                                              pf->hw.aq.asq_last_status));
15042                         kfree(aq_buf);
15043                         return -ENOENT;
15044                 }
15045
15046                 num_reported = le16_to_cpu(sw_config->header.num_reported);
15047                 num_total = le16_to_cpu(sw_config->header.num_total);
15048
15049                 if (printconfig)
15050                         dev_info(&pf->pdev->dev,
15051                                  "header: %d reported %d total\n",
15052                                  num_reported, num_total);
15053
15054                 for (i = 0; i < num_reported; i++) {
15055                         struct i40e_aqc_switch_config_element_resp *ele =
15056                                 &sw_config->element[i];
15057
15058                         i40e_setup_pf_switch_element(pf, ele, num_reported,
15059                                                      printconfig);
15060                 }
15061         } while (next_seid != 0);
15062
15063         kfree(aq_buf);
15064         return ret;
15065 }
15066
15067 /**
15068  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
15069  * @pf: board private structure
15070  * @reinit: if the Main VSI needs to re-initialized.
15071  * @lock_acquired: indicates whether or not the lock has been acquired
15072  *
15073  * Returns 0 on success, negative value on failure
15074  **/
15075 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
15076 {
15077         u16 flags = 0;
15078         int ret;
15079
15080         /* find out what's out there already */
15081         ret = i40e_fetch_switch_configuration(pf, false);
15082         if (ret) {
15083                 dev_info(&pf->pdev->dev,
15084                          "couldn't fetch switch config, err %pe aq_err %s\n",
15085                          ERR_PTR(ret),
15086                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15087                 return ret;
15088         }
15089         i40e_pf_reset_stats(pf);
15090
15091         /* set the switch config bit for the whole device to
15092          * support limited promisc or true promisc
15093          * when user requests promisc. The default is limited
15094          * promisc.
15095         */
15096
15097         if ((pf->hw.pf_id == 0) &&
15098             !test_bit(I40E_FLAG_TRUE_PROMISC_ENA, pf->flags)) {
15099                 flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15100                 pf->last_sw_conf_flags = flags;
15101         }
15102
15103         if (pf->hw.pf_id == 0) {
15104                 u16 valid_flags;
15105
15106                 valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
15107                 ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
15108                                                 NULL);
15109                 if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
15110                         dev_info(&pf->pdev->dev,
15111                                  "couldn't set switch config bits, err %pe aq_err %s\n",
15112                                  ERR_PTR(ret),
15113                                  i40e_aq_str(&pf->hw,
15114                                              pf->hw.aq.asq_last_status));
15115                         /* not a fatal problem, just keep going */
15116                 }
15117                 pf->last_sw_conf_valid_flags = valid_flags;
15118         }
15119
15120         /* first time setup */
15121         if (pf->lan_vsi == I40E_NO_VSI || reinit) {
15122                 struct i40e_vsi *vsi = NULL;
15123                 u16 uplink_seid;
15124
15125                 /* Set up the PF VSI associated with the PF's main VSI
15126                  * that is already in the HW switch
15127                  */
15128                 if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
15129                         uplink_seid = pf->veb[pf->lan_veb]->seid;
15130                 else
15131                         uplink_seid = pf->mac_seid;
15132                 if (pf->lan_vsi == I40E_NO_VSI)
15133                         vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
15134                 else if (reinit)
15135                         vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
15136                 if (!vsi) {
15137                         dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
15138                         i40e_cloud_filter_exit(pf);
15139                         i40e_fdir_teardown(pf);
15140                         return -EAGAIN;
15141                 }
15142         } else {
15143                 /* force a reset of TC and queue layout configurations */
15144                 u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
15145
15146                 pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
15147                 pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
15148                 i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
15149         }
15150         i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
15151
15152         i40e_fdir_sb_setup(pf);
15153
15154         /* Setup static PF queue filter control settings */
15155         ret = i40e_setup_pf_filter_control(pf);
15156         if (ret) {
15157                 dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
15158                          ret);
15159                 /* Failure here should not stop continuing other steps */
15160         }
15161
15162         /* enable RSS in the HW, even for only one queue, as the stack can use
15163          * the hash
15164          */
15165         if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15166                 i40e_pf_config_rss(pf);
15167
15168         /* fill in link information and enable LSE reporting */
15169         i40e_link_event(pf);
15170
15171         i40e_ptp_init(pf);
15172
15173         if (!lock_acquired)
15174                 rtnl_lock();
15175
15176         /* repopulate tunnel port filters */
15177         udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
15178
15179         if (!lock_acquired)
15180                 rtnl_unlock();
15181
15182         return ret;
15183 }
15184
15185 /**
15186  * i40e_determine_queue_usage - Work out queue distribution
15187  * @pf: board private structure
15188  **/
15189 static void i40e_determine_queue_usage(struct i40e_pf *pf)
15190 {
15191         int queues_left;
15192         int q_max;
15193
15194         pf->num_lan_qps = 0;
15195
15196         /* Find the max queues to be put into basic use.  We'll always be
15197          * using TC0, whether or not DCB is running, and TC0 will get the
15198          * big RSS set.
15199          */
15200         queues_left = pf->hw.func_caps.num_tx_qp;
15201
15202         if ((queues_left == 1) ||
15203             !test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
15204                 /* one qp for PF, no queues for anything else */
15205                 queues_left = 0;
15206                 pf->alloc_rss_size = pf->num_lan_qps = 1;
15207
15208                 /* make sure all the fancies are disabled */
15209                 clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15210                 clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15211                 clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15212                 clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15213                 clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15214                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15215                 clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
15216                 clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15217                 set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15218         } else if (!test_bit(I40E_FLAG_RSS_ENA, pf->flags) &&
15219                    !test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) &&
15220                    !test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags) &&
15221                    !test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags)) {
15222                 /* one qp for PF */
15223                 pf->alloc_rss_size = pf->num_lan_qps = 1;
15224                 queues_left -= pf->num_lan_qps;
15225
15226                 clear_bit(I40E_FLAG_RSS_ENA, pf->flags);
15227                 clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
15228                 clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15229                 clear_bit(I40E_FLAG_FD_ATR_ENA, pf->flags);
15230                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15231                 clear_bit(I40E_FLAG_VMDQ_ENA, pf->flags);
15232                 set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15233         } else {
15234                 /* Not enough queues for all TCs */
15235                 if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags) &&
15236                     queues_left < I40E_MAX_TRAFFIC_CLASS) {
15237                         clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15238                         clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15239                         dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15240                 }
15241
15242                 /* limit lan qps to the smaller of qps, cpus or msix */
15243                 q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15244                 q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15245                 q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15246                 pf->num_lan_qps = q_max;
15247
15248                 queues_left -= pf->num_lan_qps;
15249         }
15250
15251         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15252                 if (queues_left > 1) {
15253                         queues_left -= 1; /* save 1 queue for FD */
15254                 } else {
15255                         clear_bit(I40E_FLAG_FD_SB_ENA, pf->flags);
15256                         set_bit(I40E_FLAG_FD_SB_INACTIVE, pf->flags);
15257                         dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15258                 }
15259         }
15260
15261         if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15262             pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15263                 pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15264                                         (queues_left / pf->num_vf_qps));
15265                 queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15266         }
15267
15268         if (test_bit(I40E_FLAG_VMDQ_ENA, pf->flags) &&
15269             pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15270                 pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15271                                           (queues_left / pf->num_vmdq_qps));
15272                 queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15273         }
15274
15275         pf->queues_left = queues_left;
15276         dev_dbg(&pf->pdev->dev,
15277                 "qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15278                 pf->hw.func_caps.num_tx_qp,
15279                 !!test_bit(I40E_FLAG_FD_SB_ENA, pf->flags),
15280                 pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15281                 pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15282                 queues_left);
15283 }
15284
15285 /**
15286  * i40e_setup_pf_filter_control - Setup PF static filter control
15287  * @pf: PF to be setup
15288  *
15289  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15290  * settings. If PE/FCoE are enabled then it will also set the per PF
15291  * based filter sizes required for them. It also enables Flow director,
15292  * ethertype and macvlan type filter settings for the pf.
15293  *
15294  * Returns 0 on success, negative on failure
15295  **/
15296 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15297 {
15298         struct i40e_filter_control_settings *settings = &pf->filter_settings;
15299
15300         settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15301
15302         /* Flow Director is enabled */
15303         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags) ||
15304             test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15305                 settings->enable_fdir = true;
15306
15307         /* Ethtype and MACVLAN filters enabled for PF */
15308         settings->enable_ethtype = true;
15309         settings->enable_macvlan = true;
15310
15311         if (i40e_set_filter_control(&pf->hw, settings))
15312                 return -ENOENT;
15313
15314         return 0;
15315 }
15316
15317 #define INFO_STRING_LEN 255
15318 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15319 static void i40e_print_features(struct i40e_pf *pf)
15320 {
15321         struct i40e_hw *hw = &pf->hw;
15322         char *buf;
15323         int i;
15324
15325         buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15326         if (!buf)
15327                 return;
15328
15329         i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15330 #ifdef CONFIG_PCI_IOV
15331         i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15332 #endif
15333         i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15334                       pf->hw.func_caps.num_vsis,
15335                       pf->vsi[pf->lan_vsi]->num_queue_pairs);
15336         if (test_bit(I40E_FLAG_RSS_ENA, pf->flags))
15337                 i += scnprintf(&buf[i], REMAIN(i), " RSS");
15338         if (test_bit(I40E_FLAG_FD_ATR_ENA, pf->flags))
15339                 i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15340         if (test_bit(I40E_FLAG_FD_SB_ENA, pf->flags)) {
15341                 i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15342                 i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15343         }
15344         if (test_bit(I40E_FLAG_DCB_CAPABLE, pf->flags))
15345                 i += scnprintf(&buf[i], REMAIN(i), " DCB");
15346         i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15347         i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15348         if (test_bit(I40E_FLAG_PTP_ENA, pf->flags))
15349                 i += scnprintf(&buf[i], REMAIN(i), " PTP");
15350         if (test_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags))
15351                 i += scnprintf(&buf[i], REMAIN(i), " VEB");
15352         else
15353                 i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15354
15355         dev_info(&pf->pdev->dev, "%s\n", buf);
15356         kfree(buf);
15357         WARN_ON(i > INFO_STRING_LEN);
15358 }
15359
15360 /**
15361  * i40e_get_platform_mac_addr - get platform-specific MAC address
15362  * @pdev: PCI device information struct
15363  * @pf: board private structure
15364  *
15365  * Look up the MAC address for the device. First we'll try
15366  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15367  * specific fallback. Otherwise, we'll default to the stored value in
15368  * firmware.
15369  **/
15370 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15371 {
15372         if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15373                 i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15374 }
15375
15376 /**
15377  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15378  * @fec_cfg: FEC option to set in flags
15379  * @flags: ptr to flags in which we set FEC option
15380  **/
15381 void i40e_set_fec_in_flags(u8 fec_cfg, unsigned long *flags)
15382 {
15383         if (fec_cfg & I40E_AQ_SET_FEC_AUTO) {
15384                 set_bit(I40E_FLAG_RS_FEC, flags);
15385                 set_bit(I40E_FLAG_BASE_R_FEC, flags);
15386         }
15387         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15388             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15389                 set_bit(I40E_FLAG_RS_FEC, flags);
15390                 clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15391         }
15392         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15393             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15394                 set_bit(I40E_FLAG_BASE_R_FEC, flags);
15395                 clear_bit(I40E_FLAG_RS_FEC, flags);
15396         }
15397         if (fec_cfg == 0) {
15398                 clear_bit(I40E_FLAG_RS_FEC, flags);
15399                 clear_bit(I40E_FLAG_BASE_R_FEC, flags);
15400         }
15401 }
15402
15403 /**
15404  * i40e_check_recovery_mode - check if we are running transition firmware
15405  * @pf: board private structure
15406  *
15407  * Check registers indicating the firmware runs in recovery mode. Sets the
15408  * appropriate driver state.
15409  *
15410  * Returns true if the recovery mode was detected, false otherwise
15411  **/
15412 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15413 {
15414         u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15415
15416         if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15417                 dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15418                 dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15419                 set_bit(__I40E_RECOVERY_MODE, pf->state);
15420
15421                 return true;
15422         }
15423         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15424                 dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15425
15426         return false;
15427 }
15428
15429 /**
15430  * i40e_pf_loop_reset - perform reset in a loop.
15431  * @pf: board private structure
15432  *
15433  * This function is useful when a NIC is about to enter recovery mode.
15434  * When a NIC's internal data structures are corrupted the NIC's
15435  * firmware is going to enter recovery mode.
15436  * Right after a POR it takes about 7 minutes for firmware to enter
15437  * recovery mode. Until that time a NIC is in some kind of intermediate
15438  * state. After that time period the NIC almost surely enters
15439  * recovery mode. The only way for a driver to detect intermediate
15440  * state is to issue a series of pf-resets and check a return value.
15441  * If a PF reset returns success then the firmware could be in recovery
15442  * mode so the caller of this code needs to check for recovery mode
15443  * if this function returns success. There is a little chance that
15444  * firmware will hang in intermediate state forever.
15445  * Since waiting 7 minutes is quite a lot of time this function waits
15446  * 10 seconds and then gives up by returning an error.
15447  *
15448  * Return 0 on success, negative on failure.
15449  **/
15450 static int i40e_pf_loop_reset(struct i40e_pf *pf)
15451 {
15452         /* wait max 10 seconds for PF reset to succeed */
15453         const unsigned long time_end = jiffies + 10 * HZ;
15454         struct i40e_hw *hw = &pf->hw;
15455         int ret;
15456
15457         ret = i40e_pf_reset(hw);
15458         while (ret != 0 && time_before(jiffies, time_end)) {
15459                 usleep_range(10000, 20000);
15460                 ret = i40e_pf_reset(hw);
15461         }
15462
15463         if (ret == 0)
15464                 pf->pfr_count++;
15465         else
15466                 dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15467
15468         return ret;
15469 }
15470
15471 /**
15472  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15473  * @pf: board private structure
15474  *
15475  * Check FW registers to determine if FW issued unexpected EMP Reset.
15476  * Every time when unexpected EMP Reset occurs the FW increments
15477  * a counter of unexpected EMP Resets. When the counter reaches 10
15478  * the FW should enter the Recovery mode
15479  *
15480  * Returns true if FW issued unexpected EMP Reset
15481  **/
15482 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15483 {
15484         const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15485                            I40E_GL_FWSTS_FWS1B_MASK;
15486         return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15487                (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15488 }
15489
15490 /**
15491  * i40e_handle_resets - handle EMP resets and PF resets
15492  * @pf: board private structure
15493  *
15494  * Handle both EMP resets and PF resets and conclude whether there are
15495  * any issues regarding these resets. If there are any issues then
15496  * generate log entry.
15497  *
15498  * Return 0 if NIC is healthy or negative value when there are issues
15499  * with resets
15500  **/
15501 static int i40e_handle_resets(struct i40e_pf *pf)
15502 {
15503         const int pfr = i40e_pf_loop_reset(pf);
15504         const bool is_empr = i40e_check_fw_empr(pf);
15505
15506         if (is_empr || pfr != 0)
15507                 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");
15508
15509         return is_empr ? -EIO : pfr;
15510 }
15511
15512 /**
15513  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15514  * @pf: board private structure
15515  * @hw: ptr to the hardware info
15516  *
15517  * This function does a minimal setup of all subsystems needed for running
15518  * recovery mode.
15519  *
15520  * Returns 0 on success, negative on failure
15521  **/
15522 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15523 {
15524         struct i40e_vsi *vsi;
15525         int err;
15526         int v_idx;
15527
15528         pci_set_drvdata(pf->pdev, pf);
15529         pci_save_state(pf->pdev);
15530
15531         /* set up periodic task facility */
15532         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15533         pf->service_timer_period = HZ;
15534
15535         INIT_WORK(&pf->service_task, i40e_service_task);
15536         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15537
15538         err = i40e_init_interrupt_scheme(pf);
15539         if (err)
15540                 goto err_switch_setup;
15541
15542         /* The number of VSIs reported by the FW is the minimum guaranteed
15543          * to us; HW supports far more and we share the remaining pool with
15544          * the other PFs. We allocate space for more than the guarantee with
15545          * the understanding that we might not get them all later.
15546          */
15547         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15548                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15549         else
15550                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15551
15552         /* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15553         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15554                           GFP_KERNEL);
15555         if (!pf->vsi) {
15556                 err = -ENOMEM;
15557                 goto err_switch_setup;
15558         }
15559
15560         /* We allocate one VSI which is needed as absolute minimum
15561          * in order to register the netdev
15562          */
15563         v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15564         if (v_idx < 0) {
15565                 err = v_idx;
15566                 goto err_switch_setup;
15567         }
15568         pf->lan_vsi = v_idx;
15569         vsi = pf->vsi[v_idx];
15570         if (!vsi) {
15571                 err = -EFAULT;
15572                 goto err_switch_setup;
15573         }
15574         vsi->alloc_queue_pairs = 1;
15575         err = i40e_config_netdev(vsi);
15576         if (err)
15577                 goto err_switch_setup;
15578         err = register_netdev(vsi->netdev);
15579         if (err)
15580                 goto err_switch_setup;
15581         vsi->netdev_registered = true;
15582         i40e_dbg_pf_init(pf);
15583
15584         err = i40e_setup_misc_vector_for_recovery_mode(pf);
15585         if (err)
15586                 goto err_switch_setup;
15587
15588         /* tell the firmware that we're starting */
15589         i40e_send_version(pf);
15590
15591         /* since everything's happy, start the service_task timer */
15592         mod_timer(&pf->service_timer,
15593                   round_jiffies(jiffies + pf->service_timer_period));
15594
15595         return 0;
15596
15597 err_switch_setup:
15598         i40e_reset_interrupt_capability(pf);
15599         timer_shutdown_sync(&pf->service_timer);
15600         i40e_shutdown_adminq(hw);
15601         iounmap(hw->hw_addr);
15602         pci_release_mem_regions(pf->pdev);
15603         pci_disable_device(pf->pdev);
15604         i40e_free_pf(pf);
15605
15606         return err;
15607 }
15608
15609 /**
15610  * i40e_set_subsystem_device_id - set subsystem device id
15611  * @hw: pointer to the hardware info
15612  *
15613  * Set PCI subsystem device id either from a pci_dev structure or
15614  * a specific FW register.
15615  **/
15616 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15617 {
15618         struct i40e_pf *pf = i40e_hw_to_pf(hw);
15619
15620         hw->subsystem_device_id = pf->pdev->subsystem_device ?
15621                 pf->pdev->subsystem_device :
15622                 (ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15623 }
15624
15625 /**
15626  * i40e_probe - Device initialization routine
15627  * @pdev: PCI device information struct
15628  * @ent: entry in i40e_pci_tbl
15629  *
15630  * i40e_probe initializes a PF identified by a pci_dev structure.
15631  * The OS initialization, configuring of the PF private structure,
15632  * and a hardware reset occur.
15633  *
15634  * Returns 0 on success, negative on failure
15635  **/
15636 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15637 {
15638         struct i40e_aq_get_phy_abilities_resp abilities;
15639 #ifdef CONFIG_I40E_DCB
15640         enum i40e_get_fw_lldp_status_resp lldp_status;
15641 #endif /* CONFIG_I40E_DCB */
15642         struct i40e_pf *pf;
15643         struct i40e_hw *hw;
15644         u16 wol_nvm_bits;
15645         char nvm_ver[32];
15646         u16 link_status;
15647 #ifdef CONFIG_I40E_DCB
15648         int status;
15649 #endif /* CONFIG_I40E_DCB */
15650         int err;
15651         u32 val;
15652         u32 i;
15653
15654         err = pci_enable_device_mem(pdev);
15655         if (err)
15656                 return err;
15657
15658         /* set up for high or low dma */
15659         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15660         if (err) {
15661                 dev_err(&pdev->dev,
15662                         "DMA configuration failed: 0x%x\n", err);
15663                 goto err_dma;
15664         }
15665
15666         /* set up pci connections */
15667         err = pci_request_mem_regions(pdev, i40e_driver_name);
15668         if (err) {
15669                 dev_info(&pdev->dev,
15670                          "pci_request_selected_regions failed %d\n", err);
15671                 goto err_pci_reg;
15672         }
15673
15674         pci_set_master(pdev);
15675
15676         /* Now that we have a PCI connection, we need to do the
15677          * low level device setup.  This is primarily setting up
15678          * the Admin Queue structures and then querying for the
15679          * device's current profile information.
15680          */
15681         pf = i40e_alloc_pf(&pdev->dev);
15682         if (!pf) {
15683                 err = -ENOMEM;
15684                 goto err_pf_alloc;
15685         }
15686         pf->next_vsi = 0;
15687         pf->pdev = pdev;
15688         set_bit(__I40E_DOWN, pf->state);
15689
15690         hw = &pf->hw;
15691
15692         pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15693                                 I40E_MAX_CSR_SPACE);
15694         /* We believe that the highest register to read is
15695          * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15696          * is not less than that before mapping to prevent a
15697          * kernel panic.
15698          */
15699         if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15700                 dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15701                         pf->ioremap_len);
15702                 err = -ENOMEM;
15703                 goto err_ioremap;
15704         }
15705         hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15706         if (!hw->hw_addr) {
15707                 err = -EIO;
15708                 dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15709                          (unsigned int)pci_resource_start(pdev, 0),
15710                          pf->ioremap_len, err);
15711                 goto err_ioremap;
15712         }
15713         hw->vendor_id = pdev->vendor;
15714         hw->device_id = pdev->device;
15715         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15716         hw->subsystem_vendor_id = pdev->subsystem_vendor;
15717         i40e_set_subsystem_device_id(hw);
15718         hw->bus.device = PCI_SLOT(pdev->devfn);
15719         hw->bus.func = PCI_FUNC(pdev->devfn);
15720         hw->bus.bus_id = pdev->bus->number;
15721
15722         /* Select something other than the 802.1ad ethertype for the
15723          * switch to use internally and drop on ingress.
15724          */
15725         hw->switch_tag = 0xffff;
15726         hw->first_tag = ETH_P_8021AD;
15727         hw->second_tag = ETH_P_8021Q;
15728
15729         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15730         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15731         INIT_LIST_HEAD(&pf->ddp_old_prof);
15732
15733         /* set up the locks for the AQ, do this only once in probe
15734          * and destroy them only once in remove
15735          */
15736         mutex_init(&hw->aq.asq_mutex);
15737         mutex_init(&hw->aq.arq_mutex);
15738
15739         pf->msg_enable = netif_msg_init(debug,
15740                                         NETIF_MSG_DRV |
15741                                         NETIF_MSG_PROBE |
15742                                         NETIF_MSG_LINK);
15743         if (debug < -1)
15744                 pf->hw.debug_mask = debug;
15745
15746         /* do a special CORER for clearing PXE mode once at init */
15747         if (hw->revision_id == 0 &&
15748             (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15749                 wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15750                 i40e_flush(hw);
15751                 msleep(200);
15752                 pf->corer_count++;
15753
15754                 i40e_clear_pxe_mode(hw);
15755         }
15756
15757         /* Reset here to make sure all is clean and to define PF 'n' */
15758         i40e_clear_hw(hw);
15759
15760         err = i40e_set_mac_type(hw);
15761         if (err) {
15762                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15763                          err);
15764                 goto err_pf_reset;
15765         }
15766
15767         err = i40e_handle_resets(pf);
15768         if (err)
15769                 goto err_pf_reset;
15770
15771         i40e_check_recovery_mode(pf);
15772
15773         if (is_kdump_kernel()) {
15774                 hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15775                 hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15776         } else {
15777                 hw->aq.num_arq_entries = I40E_AQ_LEN;
15778                 hw->aq.num_asq_entries = I40E_AQ_LEN;
15779         }
15780         hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15781         hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15782
15783         snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15784                  "%s-%s:misc",
15785                  dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15786
15787         err = i40e_init_shared_code(hw);
15788         if (err) {
15789                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15790                          err);
15791                 goto err_pf_reset;
15792         }
15793
15794         /* set up a default setting for link flow control */
15795         pf->hw.fc.requested_mode = I40E_FC_NONE;
15796
15797         err = i40e_init_adminq(hw);
15798         if (err) {
15799                 if (err == -EIO)
15800                         dev_info(&pdev->dev,
15801                                  "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",
15802                                  hw->aq.api_maj_ver,
15803                                  hw->aq.api_min_ver,
15804                                  I40E_FW_API_VERSION_MAJOR,
15805                                  I40E_FW_MINOR_VERSION(hw));
15806                 else
15807                         dev_info(&pdev->dev,
15808                                  "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15809
15810                 goto err_pf_reset;
15811         }
15812         i40e_get_oem_version(hw);
15813         i40e_get_pba_string(hw);
15814
15815         /* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15816         i40e_nvm_version_str(hw, nvm_ver, sizeof(nvm_ver));
15817         dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15818                  hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15819                  hw->aq.api_maj_ver, hw->aq.api_min_ver, nvm_ver,
15820                  hw->vendor_id, hw->device_id, hw->subsystem_vendor_id,
15821                  hw->subsystem_device_id);
15822
15823         if (i40e_is_aq_api_ver_ge(hw, I40E_FW_API_VERSION_MAJOR,
15824                                   I40E_FW_MINOR_VERSION(hw) + 1))
15825                 dev_dbg(&pdev->dev,
15826                         "The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15827                          hw->aq.api_maj_ver,
15828                          hw->aq.api_min_ver,
15829                          I40E_FW_API_VERSION_MAJOR,
15830                          I40E_FW_MINOR_VERSION(hw));
15831         else if (i40e_is_aq_api_ver_lt(hw, 1, 4))
15832                 dev_info(&pdev->dev,
15833                          "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",
15834                          hw->aq.api_maj_ver,
15835                          hw->aq.api_min_ver,
15836                          I40E_FW_API_VERSION_MAJOR,
15837                          I40E_FW_MINOR_VERSION(hw));
15838
15839         i40e_verify_eeprom(pf);
15840
15841         /* Rev 0 hardware was never productized */
15842         if (hw->revision_id < 1)
15843                 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");
15844
15845         i40e_clear_pxe_mode(hw);
15846
15847         err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15848         if (err)
15849                 goto err_adminq_setup;
15850
15851         err = i40e_sw_init(pf);
15852         if (err) {
15853                 dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15854                 goto err_sw_init;
15855         }
15856
15857         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15858                 return i40e_init_recovery_mode(pf, hw);
15859
15860         err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15861                                 hw->func_caps.num_rx_qp, 0, 0);
15862         if (err) {
15863                 dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15864                 goto err_init_lan_hmc;
15865         }
15866
15867         err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15868         if (err) {
15869                 dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15870                 err = -ENOENT;
15871                 goto err_configure_lan_hmc;
15872         }
15873
15874         /* Disable LLDP for NICs that have firmware versions lower than v4.3.
15875          * Ignore error return codes because if it was already disabled via
15876          * hardware settings this will fail
15877          */
15878         if (test_bit(I40E_HW_CAP_STOP_FW_LLDP, pf->hw.caps)) {
15879                 dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15880                 i40e_aq_stop_lldp(hw, true, false, NULL);
15881         }
15882
15883         /* allow a platform config to override the HW addr */
15884         i40e_get_platform_mac_addr(pdev, pf);
15885
15886         if (!is_valid_ether_addr(hw->mac.addr)) {
15887                 dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15888                 err = -EIO;
15889                 goto err_mac_addr;
15890         }
15891         dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15892         ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15893         i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15894         if (is_valid_ether_addr(hw->mac.port_addr))
15895                 set_bit(I40E_HW_CAP_PORT_ID_VALID, pf->hw.caps);
15896
15897         i40e_ptp_alloc_pins(pf);
15898         pci_set_drvdata(pdev, pf);
15899         pci_save_state(pdev);
15900
15901 #ifdef CONFIG_I40E_DCB
15902         status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15903         (!status &&
15904          lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15905                 (clear_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags)) :
15906                 (set_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags));
15907         dev_info(&pdev->dev,
15908                  test_bit(I40E_FLAG_FW_LLDP_DIS, pf->flags) ?
15909                         "FW LLDP is disabled\n" :
15910                         "FW LLDP is enabled\n");
15911
15912         /* Enable FW to write default DCB config on link-up */
15913         i40e_aq_set_dcb_parameters(hw, true, NULL);
15914
15915         err = i40e_init_pf_dcb(pf);
15916         if (err) {
15917                 dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15918                 clear_bit(I40E_FLAG_DCB_CAPABLE, pf->flags);
15919                 clear_bit(I40E_FLAG_DCB_ENA, pf->flags);
15920                 /* Continue without DCB enabled */
15921         }
15922 #endif /* CONFIG_I40E_DCB */
15923
15924         /* set up periodic task facility */
15925         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15926         pf->service_timer_period = HZ;
15927
15928         INIT_WORK(&pf->service_task, i40e_service_task);
15929         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15930
15931         /* NVM bit on means WoL disabled for the port */
15932         i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15933         if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15934                 pf->wol_en = false;
15935         else
15936                 pf->wol_en = true;
15937         device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15938
15939         /* set up the main switch operations */
15940         i40e_determine_queue_usage(pf);
15941         err = i40e_init_interrupt_scheme(pf);
15942         if (err)
15943                 goto err_switch_setup;
15944
15945         /* Reduce Tx and Rx pairs for kdump
15946          * When MSI-X is enabled, it's not allowed to use more TC queue
15947          * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15948          * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15949          */
15950         if (is_kdump_kernel())
15951                 pf->num_lan_msix = 1;
15952
15953         pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15954         pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15955         pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15956         pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15957         pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15958         pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15959                                                     UDP_TUNNEL_TYPE_GENEVE;
15960
15961         /* The number of VSIs reported by the FW is the minimum guaranteed
15962          * to us; HW supports far more and we share the remaining pool with
15963          * the other PFs. We allocate space for more than the guarantee with
15964          * the understanding that we might not get them all later.
15965          */
15966         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15967                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15968         else
15969                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15970         if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15971                 dev_warn(&pf->pdev->dev,
15972                          "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15973                          pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15974                 pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15975         }
15976
15977         /* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15978         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15979                           GFP_KERNEL);
15980         if (!pf->vsi) {
15981                 err = -ENOMEM;
15982                 goto err_switch_setup;
15983         }
15984
15985 #ifdef CONFIG_PCI_IOV
15986         /* prep for VF support */
15987         if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
15988             test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
15989             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15990                 if (pci_num_vf(pdev))
15991                         set_bit(I40E_FLAG_VEB_MODE_ENA, pf->flags);
15992         }
15993 #endif
15994         err = i40e_setup_pf_switch(pf, false, false);
15995         if (err) {
15996                 dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15997                 goto err_vsis;
15998         }
15999         INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
16000
16001         /* if FDIR VSI was set up, start it now */
16002         for (i = 0; i < pf->num_alloc_vsi; i++) {
16003                 if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
16004                         i40e_vsi_open(pf->vsi[i]);
16005                         break;
16006                 }
16007         }
16008
16009         /* The driver only wants link up/down and module qualification
16010          * reports from firmware.  Note the negative logic.
16011          */
16012         err = i40e_aq_set_phy_int_mask(&pf->hw,
16013                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
16014                                          I40E_AQ_EVENT_MEDIA_NA |
16015                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
16016         if (err)
16017                 dev_info(&pf->pdev->dev, "set phy mask fail, err %pe aq_err %s\n",
16018                          ERR_PTR(err),
16019                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16020
16021         /* Reconfigure hardware for allowing smaller MSS in the case
16022          * of TSO, so that we avoid the MDD being fired and causing
16023          * a reset in the case of small MSS+TSO.
16024          */
16025         val = rd32(hw, I40E_REG_MSS);
16026         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
16027                 val &= ~I40E_REG_MSS_MIN_MASK;
16028                 val |= I40E_64BYTE_MSS;
16029                 wr32(hw, I40E_REG_MSS, val);
16030         }
16031
16032         if (test_bit(I40E_HW_CAP_RESTART_AUTONEG, pf->hw.caps)) {
16033                 msleep(75);
16034                 err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
16035                 if (err)
16036                         dev_info(&pf->pdev->dev, "link restart failed, err %pe aq_err %s\n",
16037                                  ERR_PTR(err),
16038                                  i40e_aq_str(&pf->hw,
16039                                              pf->hw.aq.asq_last_status));
16040         }
16041         /* The main driver is (mostly) up and happy. We need to set this state
16042          * before setting up the misc vector or we get a race and the vector
16043          * ends up disabled forever.
16044          */
16045         clear_bit(__I40E_DOWN, pf->state);
16046
16047         /* In case of MSIX we are going to setup the misc vector right here
16048          * to handle admin queue events etc. In case of legacy and MSI
16049          * the misc functionality and queue processing is combined in
16050          * the same vector and that gets setup at open.
16051          */
16052         if (test_bit(I40E_FLAG_MSIX_ENA, pf->flags)) {
16053                 err = i40e_setup_misc_vector(pf);
16054                 if (err) {
16055                         dev_info(&pdev->dev,
16056                                  "setup of misc vector failed: %d\n", err);
16057                         i40e_cloud_filter_exit(pf);
16058                         i40e_fdir_teardown(pf);
16059                         goto err_vsis;
16060                 }
16061         }
16062
16063 #ifdef CONFIG_PCI_IOV
16064         /* prep for VF support */
16065         if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags) &&
16066             test_bit(I40E_FLAG_MSIX_ENA, pf->flags) &&
16067             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
16068                 /* disable link interrupts for VFs */
16069                 val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
16070                 val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
16071                 wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
16072                 i40e_flush(hw);
16073
16074                 if (pci_num_vf(pdev)) {
16075                         dev_info(&pdev->dev,
16076                                  "Active VFs found, allocating resources.\n");
16077                         err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
16078                         if (err)
16079                                 dev_info(&pdev->dev,
16080                                          "Error %d allocating resources for existing VFs\n",
16081                                          err);
16082                 }
16083         }
16084 #endif /* CONFIG_PCI_IOV */
16085
16086         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16087                 pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
16088                                                       pf->num_iwarp_msix,
16089                                                       I40E_IWARP_IRQ_PILE_ID);
16090                 if (pf->iwarp_base_vector < 0) {
16091                         dev_info(&pdev->dev,
16092                                  "failed to get tracking for %d vectors for IWARP err=%d\n",
16093                                  pf->num_iwarp_msix, pf->iwarp_base_vector);
16094                         clear_bit(I40E_FLAG_IWARP_ENA, pf->flags);
16095                 }
16096         }
16097
16098         i40e_dbg_pf_init(pf);
16099
16100         /* tell the firmware that we're starting */
16101         i40e_send_version(pf);
16102
16103         /* since everything's happy, start the service_task timer */
16104         mod_timer(&pf->service_timer,
16105                   round_jiffies(jiffies + pf->service_timer_period));
16106
16107         /* add this PF to client device list and launch a client service task */
16108         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16109                 err = i40e_lan_add_device(pf);
16110                 if (err)
16111                         dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
16112                                  err);
16113         }
16114
16115 #define PCI_SPEED_SIZE 8
16116 #define PCI_WIDTH_SIZE 8
16117         /* Devices on the IOSF bus do not have this information
16118          * and will report PCI Gen 1 x 1 by default so don't bother
16119          * checking them.
16120          */
16121         if (!test_bit(I40E_HW_CAP_NO_PCI_LINK_CHECK, pf->hw.caps)) {
16122                 char speed[PCI_SPEED_SIZE] = "Unknown";
16123                 char width[PCI_WIDTH_SIZE] = "Unknown";
16124
16125                 /* Get the negotiated link width and speed from PCI config
16126                  * space
16127                  */
16128                 pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
16129                                           &link_status);
16130
16131                 i40e_set_pci_config_data(hw, link_status);
16132
16133                 switch (hw->bus.speed) {
16134                 case i40e_bus_speed_8000:
16135                         strscpy(speed, "8.0", PCI_SPEED_SIZE); break;
16136                 case i40e_bus_speed_5000:
16137                         strscpy(speed, "5.0", PCI_SPEED_SIZE); break;
16138                 case i40e_bus_speed_2500:
16139                         strscpy(speed, "2.5", PCI_SPEED_SIZE); break;
16140                 default:
16141                         break;
16142                 }
16143                 switch (hw->bus.width) {
16144                 case i40e_bus_width_pcie_x8:
16145                         strscpy(width, "8", PCI_WIDTH_SIZE); break;
16146                 case i40e_bus_width_pcie_x4:
16147                         strscpy(width, "4", PCI_WIDTH_SIZE); break;
16148                 case i40e_bus_width_pcie_x2:
16149                         strscpy(width, "2", PCI_WIDTH_SIZE); break;
16150                 case i40e_bus_width_pcie_x1:
16151                         strscpy(width, "1", PCI_WIDTH_SIZE); break;
16152                 default:
16153                         break;
16154                 }
16155
16156                 dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
16157                          speed, width);
16158
16159                 if (hw->bus.width < i40e_bus_width_pcie_x8 ||
16160                     hw->bus.speed < i40e_bus_speed_8000) {
16161                         dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
16162                         dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
16163                 }
16164         }
16165
16166         /* get the requested speeds from the fw */
16167         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
16168         if (err)
16169                 dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %pe last_status =  %s\n",
16170                         ERR_PTR(err),
16171                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16172         pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
16173
16174         /* set the FEC config due to the board capabilities */
16175         i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, pf->flags);
16176
16177         /* get the supported phy types from the fw */
16178         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
16179         if (err)
16180                 dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %pe last_status =  %s\n",
16181                         ERR_PTR(err),
16182                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
16183
16184         /* make sure the MFS hasn't been set lower than the default */
16185 #define MAX_FRAME_SIZE_DEFAULT 0x2600
16186         val = FIELD_GET(I40E_PRTGL_SAH_MFS_MASK,
16187                         rd32(&pf->hw, I40E_PRTGL_SAH));
16188         if (val < MAX_FRAME_SIZE_DEFAULT)
16189                 dev_warn(&pdev->dev, "MFS for port %x (%d) has been set below the default (%d)\n",
16190                          pf->hw.port, val, MAX_FRAME_SIZE_DEFAULT);
16191
16192         /* Add a filter to drop all Flow control frames from any VSI from being
16193          * transmitted. By doing so we stop a malicious VF from sending out
16194          * PAUSE or PFC frames and potentially controlling traffic for other
16195          * PF/VF VSIs.
16196          * The FW can still send Flow control frames if enabled.
16197          */
16198         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
16199                                                        pf->main_vsi_seid);
16200
16201         if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
16202             (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16203                 set_bit(I40E_HW_CAP_PHY_CONTROLS_LEDS, pf->hw.caps);
16204         if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16205                 set_bit(I40E_HW_CAP_CRT_RETIMER, pf->hw.caps);
16206         /* print a string summarizing features */
16207         i40e_print_features(pf);
16208
16209         i40e_devlink_register(pf);
16210
16211         return 0;
16212
16213         /* Unwind what we've done if something failed in the setup */
16214 err_vsis:
16215         set_bit(__I40E_DOWN, pf->state);
16216         i40e_clear_interrupt_scheme(pf);
16217         kfree(pf->vsi);
16218 err_switch_setup:
16219         i40e_reset_interrupt_capability(pf);
16220         timer_shutdown_sync(&pf->service_timer);
16221 err_mac_addr:
16222 err_configure_lan_hmc:
16223         (void)i40e_shutdown_lan_hmc(hw);
16224 err_init_lan_hmc:
16225         kfree(pf->qp_pile);
16226 err_sw_init:
16227 err_adminq_setup:
16228 err_pf_reset:
16229         iounmap(hw->hw_addr);
16230 err_ioremap:
16231         i40e_free_pf(pf);
16232 err_pf_alloc:
16233         pci_release_mem_regions(pdev);
16234 err_pci_reg:
16235 err_dma:
16236         pci_disable_device(pdev);
16237         return err;
16238 }
16239
16240 /**
16241  * i40e_remove - Device removal routine
16242  * @pdev: PCI device information struct
16243  *
16244  * i40e_remove is called by the PCI subsystem to alert the driver
16245  * that is should release a PCI device.  This could be caused by a
16246  * Hot-Plug event, or because the driver is going to be removed from
16247  * memory.
16248  **/
16249 static void i40e_remove(struct pci_dev *pdev)
16250 {
16251         struct i40e_pf *pf = pci_get_drvdata(pdev);
16252         struct i40e_hw *hw = &pf->hw;
16253         int ret_code;
16254         int i;
16255
16256         i40e_devlink_unregister(pf);
16257
16258         i40e_dbg_pf_exit(pf);
16259
16260         i40e_ptp_stop(pf);
16261
16262         /* Disable RSS in hw */
16263         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16264         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16265
16266         /* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16267          * flags, once they are set, i40e_rebuild should not be called as
16268          * i40e_prep_for_reset always returns early.
16269          */
16270         while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16271                 usleep_range(1000, 2000);
16272         set_bit(__I40E_IN_REMOVE, pf->state);
16273
16274         if (test_bit(I40E_FLAG_SRIOV_ENA, pf->flags)) {
16275                 set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16276                 i40e_free_vfs(pf);
16277                 clear_bit(I40E_FLAG_SRIOV_ENA, pf->flags);
16278         }
16279         /* no more scheduling of any task */
16280         set_bit(__I40E_SUSPENDED, pf->state);
16281         set_bit(__I40E_DOWN, pf->state);
16282         if (pf->service_timer.function)
16283                 timer_shutdown_sync(&pf->service_timer);
16284         if (pf->service_task.func)
16285                 cancel_work_sync(&pf->service_task);
16286
16287         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16288                 struct i40e_vsi *vsi = pf->vsi[0];
16289
16290                 /* We know that we have allocated only one vsi for this PF,
16291                  * it was just for registering netdevice, so the interface
16292                  * could be visible in the 'ifconfig' output
16293                  */
16294                 unregister_netdev(vsi->netdev);
16295                 free_netdev(vsi->netdev);
16296
16297                 goto unmap;
16298         }
16299
16300         /* Client close must be called explicitly here because the timer
16301          * has been stopped.
16302          */
16303         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16304
16305         i40e_fdir_teardown(pf);
16306
16307         /* If there is a switch structure or any orphans, remove them.
16308          * This will leave only the PF's VSI remaining.
16309          */
16310         for (i = 0; i < I40E_MAX_VEB; i++) {
16311                 if (!pf->veb[i])
16312                         continue;
16313
16314                 if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16315                     pf->veb[i]->uplink_seid == 0)
16316                         i40e_switch_branch_release(pf->veb[i]);
16317         }
16318
16319         /* Now we can shutdown the PF's VSIs, just before we kill
16320          * adminq and hmc.
16321          */
16322         for (i = pf->num_alloc_vsi; i--;)
16323                 if (pf->vsi[i]) {
16324                         i40e_vsi_close(pf->vsi[i]);
16325                         i40e_vsi_release(pf->vsi[i]);
16326                         pf->vsi[i] = NULL;
16327                 }
16328
16329         i40e_cloud_filter_exit(pf);
16330
16331         /* remove attached clients */
16332         if (test_bit(I40E_FLAG_IWARP_ENA, pf->flags)) {
16333                 ret_code = i40e_lan_del_device(pf);
16334                 if (ret_code)
16335                         dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16336                                  ret_code);
16337         }
16338
16339         /* shutdown and destroy the HMC */
16340         if (hw->hmc.hmc_obj) {
16341                 ret_code = i40e_shutdown_lan_hmc(hw);
16342                 if (ret_code)
16343                         dev_warn(&pdev->dev,
16344                                  "Failed to destroy the HMC resources: %d\n",
16345                                  ret_code);
16346         }
16347
16348 unmap:
16349         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16350         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16351             !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16352                 free_irq(pf->pdev->irq, pf);
16353
16354         /* shutdown the adminq */
16355         i40e_shutdown_adminq(hw);
16356
16357         /* destroy the locks only once, here */
16358         mutex_destroy(&hw->aq.arq_mutex);
16359         mutex_destroy(&hw->aq.asq_mutex);
16360
16361         /* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16362         rtnl_lock();
16363         i40e_clear_interrupt_scheme(pf);
16364         for (i = 0; i < pf->num_alloc_vsi; i++) {
16365                 if (pf->vsi[i]) {
16366                         if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16367                                 i40e_vsi_clear_rings(pf->vsi[i]);
16368                         i40e_vsi_clear(pf->vsi[i]);
16369                         pf->vsi[i] = NULL;
16370                 }
16371         }
16372         rtnl_unlock();
16373
16374         for (i = 0; i < I40E_MAX_VEB; i++) {
16375                 kfree(pf->veb[i]);
16376                 pf->veb[i] = NULL;
16377         }
16378
16379         kfree(pf->qp_pile);
16380         kfree(pf->vsi);
16381
16382         iounmap(hw->hw_addr);
16383         i40e_free_pf(pf);
16384         pci_release_mem_regions(pdev);
16385
16386         pci_disable_device(pdev);
16387 }
16388
16389 /**
16390  * i40e_pci_error_detected - warning that something funky happened in PCI land
16391  * @pdev: PCI device information struct
16392  * @error: the type of PCI error
16393  *
16394  * Called to warn that something happened and the error handling steps
16395  * are in progress.  Allows the driver to quiesce things, be ready for
16396  * remediation.
16397  **/
16398 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16399                                                 pci_channel_state_t error)
16400 {
16401         struct i40e_pf *pf = pci_get_drvdata(pdev);
16402
16403         dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16404
16405         if (!pf) {
16406                 dev_info(&pdev->dev,
16407                          "Cannot recover - error happened during device probe\n");
16408                 return PCI_ERS_RESULT_DISCONNECT;
16409         }
16410
16411         /* shutdown all operations */
16412         if (!test_bit(__I40E_SUSPENDED, pf->state))
16413                 i40e_prep_for_reset(pf);
16414
16415         /* Request a slot reset */
16416         return PCI_ERS_RESULT_NEED_RESET;
16417 }
16418
16419 /**
16420  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16421  * @pdev: PCI device information struct
16422  *
16423  * Called to find if the driver can work with the device now that
16424  * the pci slot has been reset.  If a basic connection seems good
16425  * (registers are readable and have sane content) then return a
16426  * happy little PCI_ERS_RESULT_xxx.
16427  **/
16428 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16429 {
16430         struct i40e_pf *pf = pci_get_drvdata(pdev);
16431         pci_ers_result_t result;
16432         u32 reg;
16433
16434         dev_dbg(&pdev->dev, "%s\n", __func__);
16435         if (pci_enable_device_mem(pdev)) {
16436                 dev_info(&pdev->dev,
16437                          "Cannot re-enable PCI device after reset.\n");
16438                 result = PCI_ERS_RESULT_DISCONNECT;
16439         } else {
16440                 pci_set_master(pdev);
16441                 pci_restore_state(pdev);
16442                 pci_save_state(pdev);
16443                 pci_wake_from_d3(pdev, false);
16444
16445                 reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16446                 if (reg == 0)
16447                         result = PCI_ERS_RESULT_RECOVERED;
16448                 else
16449                         result = PCI_ERS_RESULT_DISCONNECT;
16450         }
16451
16452         return result;
16453 }
16454
16455 /**
16456  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16457  * @pdev: PCI device information struct
16458  */
16459 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16460 {
16461         struct i40e_pf *pf = pci_get_drvdata(pdev);
16462
16463         i40e_prep_for_reset(pf);
16464 }
16465
16466 /**
16467  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16468  * @pdev: PCI device information struct
16469  */
16470 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16471 {
16472         struct i40e_pf *pf = pci_get_drvdata(pdev);
16473
16474         if (test_bit(__I40E_IN_REMOVE, pf->state))
16475                 return;
16476
16477         i40e_reset_and_rebuild(pf, false, false);
16478 #ifdef CONFIG_PCI_IOV
16479         i40e_restore_all_vfs_msi_state(pdev);
16480 #endif /* CONFIG_PCI_IOV */
16481 }
16482
16483 /**
16484  * i40e_pci_error_resume - restart operations after PCI error recovery
16485  * @pdev: PCI device information struct
16486  *
16487  * Called to allow the driver to bring things back up after PCI error
16488  * and/or reset recovery has finished.
16489  **/
16490 static void i40e_pci_error_resume(struct pci_dev *pdev)
16491 {
16492         struct i40e_pf *pf = pci_get_drvdata(pdev);
16493
16494         dev_dbg(&pdev->dev, "%s\n", __func__);
16495         if (test_bit(__I40E_SUSPENDED, pf->state))
16496                 return;
16497
16498         i40e_handle_reset_warning(pf, false);
16499 }
16500
16501 /**
16502  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16503  * using the mac_address_write admin q function
16504  * @pf: pointer to i40e_pf struct
16505  **/
16506 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16507 {
16508         struct i40e_hw *hw = &pf->hw;
16509         u8 mac_addr[6];
16510         u16 flags = 0;
16511         int ret;
16512
16513         /* Get current MAC address in case it's an LAA */
16514         if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16515                 ether_addr_copy(mac_addr,
16516                                 pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16517         } else {
16518                 dev_err(&pf->pdev->dev,
16519                         "Failed to retrieve MAC address; using default\n");
16520                 ether_addr_copy(mac_addr, hw->mac.addr);
16521         }
16522
16523         /* The FW expects the mac address write cmd to first be called with
16524          * one of these flags before calling it again with the multicast
16525          * enable flags.
16526          */
16527         flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16528
16529         if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16530                 flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16531
16532         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16533         if (ret) {
16534                 dev_err(&pf->pdev->dev,
16535                         "Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16536                 return;
16537         }
16538
16539         flags = I40E_AQC_MC_MAG_EN
16540                         | I40E_AQC_WOL_PRESERVE_ON_PFR
16541                         | I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16542         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16543         if (ret)
16544                 dev_err(&pf->pdev->dev,
16545                         "Failed to enable Multicast Magic Packet wake up\n");
16546 }
16547
16548 /**
16549  * i40e_shutdown - PCI callback for shutting down
16550  * @pdev: PCI device information struct
16551  **/
16552 static void i40e_shutdown(struct pci_dev *pdev)
16553 {
16554         struct i40e_pf *pf = pci_get_drvdata(pdev);
16555         struct i40e_hw *hw = &pf->hw;
16556
16557         set_bit(__I40E_SUSPENDED, pf->state);
16558         set_bit(__I40E_DOWN, pf->state);
16559
16560         del_timer_sync(&pf->service_timer);
16561         cancel_work_sync(&pf->service_task);
16562         i40e_cloud_filter_exit(pf);
16563         i40e_fdir_teardown(pf);
16564
16565         /* Client close must be called explicitly here because the timer
16566          * has been stopped.
16567          */
16568         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16569
16570         if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16571             pf->wol_en)
16572                 i40e_enable_mc_magic_wake(pf);
16573
16574         i40e_prep_for_reset(pf);
16575
16576         wr32(hw, I40E_PFPM_APM,
16577              (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16578         wr32(hw, I40E_PFPM_WUFC,
16579              (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16580
16581         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16582         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16583             !test_bit(I40E_FLAG_MSIX_ENA, pf->flags))
16584                 free_irq(pf->pdev->irq, pf);
16585
16586         /* Since we're going to destroy queues during the
16587          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16588          * whole section
16589          */
16590         rtnl_lock();
16591         i40e_clear_interrupt_scheme(pf);
16592         rtnl_unlock();
16593
16594         if (system_state == SYSTEM_POWER_OFF) {
16595                 pci_wake_from_d3(pdev, pf->wol_en);
16596                 pci_set_power_state(pdev, PCI_D3hot);
16597         }
16598 }
16599
16600 /**
16601  * i40e_suspend - PM callback for moving to D3
16602  * @dev: generic device information structure
16603  **/
16604 static int __maybe_unused i40e_suspend(struct device *dev)
16605 {
16606         struct i40e_pf *pf = dev_get_drvdata(dev);
16607         struct i40e_hw *hw = &pf->hw;
16608
16609         /* If we're already suspended, then there is nothing to do */
16610         if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16611                 return 0;
16612
16613         set_bit(__I40E_DOWN, pf->state);
16614
16615         /* Ensure service task will not be running */
16616         del_timer_sync(&pf->service_timer);
16617         cancel_work_sync(&pf->service_task);
16618
16619         /* Client close must be called explicitly here because the timer
16620          * has been stopped.
16621          */
16622         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16623
16624         if (test_bit(I40E_HW_CAP_WOL_MC_MAGIC_PKT_WAKE, pf->hw.caps) &&
16625             pf->wol_en)
16626                 i40e_enable_mc_magic_wake(pf);
16627
16628         /* Since we're going to destroy queues during the
16629          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16630          * whole section
16631          */
16632         rtnl_lock();
16633
16634         i40e_prep_for_reset(pf);
16635
16636         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16637         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16638
16639         /* Clear the interrupt scheme and release our IRQs so that the system
16640          * can safely hibernate even when there are a large number of CPUs.
16641          * Otherwise hibernation might fail when mapping all the vectors back
16642          * to CPU0.
16643          */
16644         i40e_clear_interrupt_scheme(pf);
16645
16646         rtnl_unlock();
16647
16648         return 0;
16649 }
16650
16651 /**
16652  * i40e_resume - PM callback for waking up from D3
16653  * @dev: generic device information structure
16654  **/
16655 static int __maybe_unused i40e_resume(struct device *dev)
16656 {
16657         struct i40e_pf *pf = dev_get_drvdata(dev);
16658         int err;
16659
16660         /* If we're not suspended, then there is nothing to do */
16661         if (!test_bit(__I40E_SUSPENDED, pf->state))
16662                 return 0;
16663
16664         /* We need to hold the RTNL lock prior to restoring interrupt schemes,
16665          * since we're going to be restoring queues
16666          */
16667         rtnl_lock();
16668
16669         /* We cleared the interrupt scheme when we suspended, so we need to
16670          * restore it now to resume device functionality.
16671          */
16672         err = i40e_restore_interrupt_scheme(pf);
16673         if (err) {
16674                 dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16675                         err);
16676         }
16677
16678         clear_bit(__I40E_DOWN, pf->state);
16679         i40e_reset_and_rebuild(pf, false, true);
16680
16681         rtnl_unlock();
16682
16683         /* Clear suspended state last after everything is recovered */
16684         clear_bit(__I40E_SUSPENDED, pf->state);
16685
16686         /* Restart the service task */
16687         mod_timer(&pf->service_timer,
16688                   round_jiffies(jiffies + pf->service_timer_period));
16689
16690         return 0;
16691 }
16692
16693 static const struct pci_error_handlers i40e_err_handler = {
16694         .error_detected = i40e_pci_error_detected,
16695         .slot_reset = i40e_pci_error_slot_reset,
16696         .reset_prepare = i40e_pci_error_reset_prepare,
16697         .reset_done = i40e_pci_error_reset_done,
16698         .resume = i40e_pci_error_resume,
16699 };
16700
16701 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16702
16703 static struct pci_driver i40e_driver = {
16704         .name     = i40e_driver_name,
16705         .id_table = i40e_pci_tbl,
16706         .probe    = i40e_probe,
16707         .remove   = i40e_remove,
16708         .driver   = {
16709                 .pm = &i40e_pm_ops,
16710         },
16711         .shutdown = i40e_shutdown,
16712         .err_handler = &i40e_err_handler,
16713         .sriov_configure = i40e_pci_sriov_configure,
16714 };
16715
16716 /**
16717  * i40e_init_module - Driver registration routine
16718  *
16719  * i40e_init_module is the first routine called when the driver is
16720  * loaded. All it does is register with the PCI subsystem.
16721  **/
16722 static int __init i40e_init_module(void)
16723 {
16724         int err;
16725
16726         pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16727         pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16728
16729         /* There is no need to throttle the number of active tasks because
16730          * each device limits its own task using a state bit for scheduling
16731          * the service task, and the device tasks do not interfere with each
16732          * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16733          * since we need to be able to guarantee forward progress even under
16734          * memory pressure.
16735          */
16736         i40e_wq = alloc_workqueue("%s", 0, 0, i40e_driver_name);
16737         if (!i40e_wq) {
16738                 pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16739                 return -ENOMEM;
16740         }
16741
16742         i40e_dbg_init();
16743         err = pci_register_driver(&i40e_driver);
16744         if (err) {
16745                 destroy_workqueue(i40e_wq);
16746                 i40e_dbg_exit();
16747                 return err;
16748         }
16749
16750         return 0;
16751 }
16752 module_init(i40e_init_module);
16753
16754 /**
16755  * i40e_exit_module - Driver exit cleanup routine
16756  *
16757  * i40e_exit_module is called just before the driver is removed
16758  * from memory.
16759  **/
16760 static void __exit i40e_exit_module(void)
16761 {
16762         pci_unregister_driver(&i40e_driver);
16763         destroy_workqueue(i40e_wq);
16764         ida_destroy(&i40e_client_ida);
16765         i40e_dbg_exit();
16766 }
16767 module_exit(i40e_exit_module);