]> git.itanic.dy.fi Git - linux-stable/blob - drivers/net/ethernet/intel/i40e/i40e_main.c
1aaf0c5ddf6cfd77b9c2b8615053079804d48f73
[linux-stable] / drivers / net / ethernet / intel / i40e / i40e_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2021 Intel Corporation. */
3
4 #include <linux/etherdevice.h>
5 #include <linux/of_net.h>
6 #include <linux/pci.h>
7 #include <linux/bpf.h>
8 #include <generated/utsrelease.h>
9 #include <linux/crash_dump.h>
10
11 /* Local includes */
12 #include "i40e.h"
13 #include "i40e_diag.h"
14 #include "i40e_xsk.h"
15 #include <net/udp_tunnel.h>
16 #include <net/xdp_sock_drv.h>
17 /* All i40e tracepoints are defined by the include below, which
18  * must be included exactly once across the whole kernel with
19  * CREATE_TRACE_POINTS defined
20  */
21 #define CREATE_TRACE_POINTS
22 #include "i40e_trace.h"
23
24 const char i40e_driver_name[] = "i40e";
25 static const char i40e_driver_string[] =
26                         "Intel(R) Ethernet Connection XL710 Network Driver";
27
28 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
29
30 /* a bit of forward declarations */
31 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
32 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
33 static int i40e_add_vsi(struct i40e_vsi *vsi);
34 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
35 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired);
36 static int i40e_setup_misc_vector(struct i40e_pf *pf);
37 static void i40e_determine_queue_usage(struct i40e_pf *pf);
38 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
39 static void i40e_prep_for_reset(struct i40e_pf *pf);
40 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
41                                    bool lock_acquired);
42 static int i40e_reset(struct i40e_pf *pf);
43 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
44 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
45 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
46 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
47 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
48 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
49 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
50 static int i40e_get_capabilities(struct i40e_pf *pf,
51                                  enum i40e_admin_queue_opc list_type);
52 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf);
53
54 /* i40e_pci_tbl - PCI Device ID Table
55  *
56  * Last entry must be all 0s
57  *
58  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
59  *   Class, Class Mask, private data (not used) }
60  */
61 static const struct pci_device_id i40e_pci_tbl[] = {
62         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
63         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
64         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
65         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
66         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
67         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
68         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
69         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
70         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
71         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_BC), 0},
72         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
73         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
74         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
75         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
76         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
77         {PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
78         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
79         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
80         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722_A), 0},
81         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
82         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
83         {PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
84         {PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
85         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
86         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
87         /* required last entry */
88         {0, }
89 };
90 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
91
92 #define I40E_MAX_VF_COUNT 128
93 static int debug = -1;
94 module_param(debug, uint, 0);
95 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
96
97 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
98 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
99 MODULE_LICENSE("GPL v2");
100
101 static struct workqueue_struct *i40e_wq;
102
103 static void netdev_hw_addr_refcnt(struct i40e_mac_filter *f,
104                                   struct net_device *netdev, int delta)
105 {
106         struct netdev_hw_addr *ha;
107
108         if (!f || !netdev)
109                 return;
110
111         netdev_for_each_mc_addr(ha, netdev) {
112                 if (ether_addr_equal(ha->addr, f->macaddr)) {
113                         ha->refcount += delta;
114                         if (ha->refcount <= 0)
115                                 ha->refcount = 1;
116                         break;
117                 }
118         }
119 }
120
121 /**
122  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
123  * @hw:   pointer to the HW structure
124  * @mem:  ptr to mem struct to fill out
125  * @size: size of memory requested
126  * @alignment: what to align the allocation to
127  **/
128 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
129                             u64 size, u32 alignment)
130 {
131         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
132
133         mem->size = ALIGN(size, alignment);
134         mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
135                                      GFP_KERNEL);
136         if (!mem->va)
137                 return -ENOMEM;
138
139         return 0;
140 }
141
142 /**
143  * i40e_free_dma_mem_d - OS specific memory free for shared code
144  * @hw:   pointer to the HW structure
145  * @mem:  ptr to mem struct to free
146  **/
147 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
148 {
149         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
150
151         dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
152         mem->va = NULL;
153         mem->pa = 0;
154         mem->size = 0;
155
156         return 0;
157 }
158
159 /**
160  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
161  * @hw:   pointer to the HW structure
162  * @mem:  ptr to mem struct to fill out
163  * @size: size of memory requested
164  **/
165 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
166                              u32 size)
167 {
168         mem->size = size;
169         mem->va = kzalloc(size, GFP_KERNEL);
170
171         if (!mem->va)
172                 return -ENOMEM;
173
174         return 0;
175 }
176
177 /**
178  * i40e_free_virt_mem_d - OS specific memory free for shared code
179  * @hw:   pointer to the HW structure
180  * @mem:  ptr to mem struct to free
181  **/
182 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
183 {
184         /* it's ok to kfree a NULL pointer */
185         kfree(mem->va);
186         mem->va = NULL;
187         mem->size = 0;
188
189         return 0;
190 }
191
192 /**
193  * i40e_get_lump - find a lump of free generic resource
194  * @pf: board private structure
195  * @pile: the pile of resource to search
196  * @needed: the number of items needed
197  * @id: an owner id to stick on the items assigned
198  *
199  * Returns the base item index of the lump, or negative for error
200  **/
201 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
202                          u16 needed, u16 id)
203 {
204         int ret = -ENOMEM;
205         int i, j;
206
207         if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
208                 dev_info(&pf->pdev->dev,
209                          "param err: pile=%s needed=%d id=0x%04x\n",
210                          pile ? "<valid>" : "<null>", needed, id);
211                 return -EINVAL;
212         }
213
214         /* Allocate last queue in the pile for FDIR VSI queue
215          * so it doesn't fragment the qp_pile
216          */
217         if (pile == pf->qp_pile && pf->vsi[id]->type == I40E_VSI_FDIR) {
218                 if (pile->list[pile->num_entries - 1] & I40E_PILE_VALID_BIT) {
219                         dev_err(&pf->pdev->dev,
220                                 "Cannot allocate queue %d for I40E_VSI_FDIR\n",
221                                 pile->num_entries - 1);
222                         return -ENOMEM;
223                 }
224                 pile->list[pile->num_entries - 1] = id | I40E_PILE_VALID_BIT;
225                 return pile->num_entries - 1;
226         }
227
228         i = 0;
229         while (i < pile->num_entries) {
230                 /* skip already allocated entries */
231                 if (pile->list[i] & I40E_PILE_VALID_BIT) {
232                         i++;
233                         continue;
234                 }
235
236                 /* do we have enough in this lump? */
237                 for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
238                         if (pile->list[i+j] & I40E_PILE_VALID_BIT)
239                                 break;
240                 }
241
242                 if (j == needed) {
243                         /* there was enough, so assign it to the requestor */
244                         for (j = 0; j < needed; j++)
245                                 pile->list[i+j] = id | I40E_PILE_VALID_BIT;
246                         ret = i;
247                         break;
248                 }
249
250                 /* not enough, so skip over it and continue looking */
251                 i += j;
252         }
253
254         return ret;
255 }
256
257 /**
258  * i40e_put_lump - return a lump of generic resource
259  * @pile: the pile of resource to search
260  * @index: the base item index
261  * @id: the owner id of the items assigned
262  *
263  * Returns the count of items in the lump
264  **/
265 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
266 {
267         int valid_id = (id | I40E_PILE_VALID_BIT);
268         int count = 0;
269         u16 i;
270
271         if (!pile || index >= pile->num_entries)
272                 return -EINVAL;
273
274         for (i = index;
275              i < pile->num_entries && pile->list[i] == valid_id;
276              i++) {
277                 pile->list[i] = 0;
278                 count++;
279         }
280
281
282         return count;
283 }
284
285 /**
286  * i40e_find_vsi_from_id - searches for the vsi with the given id
287  * @pf: the pf structure to search for the vsi
288  * @id: id of the vsi it is searching for
289  **/
290 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
291 {
292         int i;
293
294         for (i = 0; i < pf->num_alloc_vsi; i++)
295                 if (pf->vsi[i] && (pf->vsi[i]->id == id))
296                         return pf->vsi[i];
297
298         return NULL;
299 }
300
301 /**
302  * i40e_service_event_schedule - Schedule the service task to wake up
303  * @pf: board private structure
304  *
305  * If not already scheduled, this puts the task into the work queue
306  **/
307 void i40e_service_event_schedule(struct i40e_pf *pf)
308 {
309         if ((!test_bit(__I40E_DOWN, pf->state) &&
310              !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
311               test_bit(__I40E_RECOVERY_MODE, pf->state))
312                 queue_work(i40e_wq, &pf->service_task);
313 }
314
315 /**
316  * i40e_tx_timeout - Respond to a Tx Hang
317  * @netdev: network interface device structure
318  * @txqueue: queue number timing out
319  *
320  * If any port has noticed a Tx timeout, it is likely that the whole
321  * device is munged, not just the one netdev port, so go for the full
322  * reset.
323  **/
324 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
325 {
326         struct i40e_netdev_priv *np = netdev_priv(netdev);
327         struct i40e_vsi *vsi = np->vsi;
328         struct i40e_pf *pf = vsi->back;
329         struct i40e_ring *tx_ring = NULL;
330         unsigned int i;
331         u32 head, val;
332
333         pf->tx_timeout_count++;
334
335         /* with txqueue index, find the tx_ring struct */
336         for (i = 0; i < vsi->num_queue_pairs; i++) {
337                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
338                         if (txqueue ==
339                             vsi->tx_rings[i]->queue_index) {
340                                 tx_ring = vsi->tx_rings[i];
341                                 break;
342                         }
343                 }
344         }
345
346         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
347                 pf->tx_timeout_recovery_level = 1;  /* reset after some time */
348         else if (time_before(jiffies,
349                       (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
350                 return;   /* don't do any new action before the next timeout */
351
352         /* don't kick off another recovery if one is already pending */
353         if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
354                 return;
355
356         if (tx_ring) {
357                 head = i40e_get_head(tx_ring);
358                 /* Read interrupt register */
359                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
360                         val = rd32(&pf->hw,
361                              I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
362                                                 tx_ring->vsi->base_vector - 1));
363                 else
364                         val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
365
366                 netdev_info(netdev, "tx_timeout: VSI_seid: %d, Q %d, NTC: 0x%x, HWB: 0x%x, NTU: 0x%x, TAIL: 0x%x, INT: 0x%x\n",
367                             vsi->seid, txqueue, tx_ring->next_to_clean,
368                             head, tx_ring->next_to_use,
369                             readl(tx_ring->tail), val);
370         }
371
372         pf->tx_timeout_last_recovery = jiffies;
373         netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
374                     pf->tx_timeout_recovery_level, txqueue);
375
376         switch (pf->tx_timeout_recovery_level) {
377         case 1:
378                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
379                 break;
380         case 2:
381                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
382                 break;
383         case 3:
384                 set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
385                 break;
386         default:
387                 netdev_err(netdev, "tx_timeout recovery unsuccessful, device is in non-recoverable state.\n");
388                 set_bit(__I40E_DOWN_REQUESTED, pf->state);
389                 set_bit(__I40E_VSI_DOWN_REQUESTED, vsi->state);
390                 break;
391         }
392
393         i40e_service_event_schedule(pf);
394         pf->tx_timeout_recovery_level++;
395 }
396
397 /**
398  * i40e_get_vsi_stats_struct - Get System Network Statistics
399  * @vsi: the VSI we care about
400  *
401  * Returns the address of the device statistics structure.
402  * The statistics are actually updated from the service task.
403  **/
404 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
405 {
406         return &vsi->net_stats;
407 }
408
409 /**
410  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
411  * @ring: Tx ring to get statistics from
412  * @stats: statistics entry to be updated
413  **/
414 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
415                                             struct rtnl_link_stats64 *stats)
416 {
417         u64 bytes, packets;
418         unsigned int start;
419
420         do {
421                 start = u64_stats_fetch_begin_irq(&ring->syncp);
422                 packets = ring->stats.packets;
423                 bytes   = ring->stats.bytes;
424         } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
425
426         stats->tx_packets += packets;
427         stats->tx_bytes   += bytes;
428 }
429
430 /**
431  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
432  * @netdev: network interface device structure
433  * @stats: data structure to store statistics
434  *
435  * Returns the address of the device statistics structure.
436  * The statistics are actually updated from the service task.
437  **/
438 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
439                                   struct rtnl_link_stats64 *stats)
440 {
441         struct i40e_netdev_priv *np = netdev_priv(netdev);
442         struct i40e_vsi *vsi = np->vsi;
443         struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
444         struct i40e_ring *ring;
445         int i;
446
447         if (test_bit(__I40E_VSI_DOWN, vsi->state))
448                 return;
449
450         if (!vsi->tx_rings)
451                 return;
452
453         rcu_read_lock();
454         for (i = 0; i < vsi->num_queue_pairs; i++) {
455                 u64 bytes, packets;
456                 unsigned int start;
457
458                 ring = READ_ONCE(vsi->tx_rings[i]);
459                 if (!ring)
460                         continue;
461                 i40e_get_netdev_stats_struct_tx(ring, stats);
462
463                 if (i40e_enabled_xdp_vsi(vsi)) {
464                         ring = READ_ONCE(vsi->xdp_rings[i]);
465                         if (!ring)
466                                 continue;
467                         i40e_get_netdev_stats_struct_tx(ring, stats);
468                 }
469
470                 ring = READ_ONCE(vsi->rx_rings[i]);
471                 if (!ring)
472                         continue;
473                 do {
474                         start   = u64_stats_fetch_begin_irq(&ring->syncp);
475                         packets = ring->stats.packets;
476                         bytes   = ring->stats.bytes;
477                 } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
478
479                 stats->rx_packets += packets;
480                 stats->rx_bytes   += bytes;
481
482         }
483         rcu_read_unlock();
484
485         /* following stats updated by i40e_watchdog_subtask() */
486         stats->multicast        = vsi_stats->multicast;
487         stats->tx_errors        = vsi_stats->tx_errors;
488         stats->tx_dropped       = vsi_stats->tx_dropped;
489         stats->rx_errors        = vsi_stats->rx_errors;
490         stats->rx_dropped       = vsi_stats->rx_dropped;
491         stats->rx_crc_errors    = vsi_stats->rx_crc_errors;
492         stats->rx_length_errors = vsi_stats->rx_length_errors;
493 }
494
495 /**
496  * i40e_vsi_reset_stats - Resets all stats of the given vsi
497  * @vsi: the VSI to have its stats reset
498  **/
499 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
500 {
501         struct rtnl_link_stats64 *ns;
502         int i;
503
504         if (!vsi)
505                 return;
506
507         ns = i40e_get_vsi_stats_struct(vsi);
508         memset(ns, 0, sizeof(*ns));
509         memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
510         memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
511         memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
512         if (vsi->rx_rings && vsi->rx_rings[0]) {
513                 for (i = 0; i < vsi->num_queue_pairs; i++) {
514                         memset(&vsi->rx_rings[i]->stats, 0,
515                                sizeof(vsi->rx_rings[i]->stats));
516                         memset(&vsi->rx_rings[i]->rx_stats, 0,
517                                sizeof(vsi->rx_rings[i]->rx_stats));
518                         memset(&vsi->tx_rings[i]->stats, 0,
519                                sizeof(vsi->tx_rings[i]->stats));
520                         memset(&vsi->tx_rings[i]->tx_stats, 0,
521                                sizeof(vsi->tx_rings[i]->tx_stats));
522                 }
523         }
524         vsi->stat_offsets_loaded = false;
525 }
526
527 /**
528  * i40e_pf_reset_stats - Reset all of the stats for the given PF
529  * @pf: the PF to be reset
530  **/
531 void i40e_pf_reset_stats(struct i40e_pf *pf)
532 {
533         int i;
534
535         memset(&pf->stats, 0, sizeof(pf->stats));
536         memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
537         pf->stat_offsets_loaded = false;
538
539         for (i = 0; i < I40E_MAX_VEB; i++) {
540                 if (pf->veb[i]) {
541                         memset(&pf->veb[i]->stats, 0,
542                                sizeof(pf->veb[i]->stats));
543                         memset(&pf->veb[i]->stats_offsets, 0,
544                                sizeof(pf->veb[i]->stats_offsets));
545                         memset(&pf->veb[i]->tc_stats, 0,
546                                sizeof(pf->veb[i]->tc_stats));
547                         memset(&pf->veb[i]->tc_stats_offsets, 0,
548                                sizeof(pf->veb[i]->tc_stats_offsets));
549                         pf->veb[i]->stat_offsets_loaded = false;
550                 }
551         }
552         pf->hw_csum_rx_error = 0;
553 }
554
555 /**
556  * i40e_compute_pci_to_hw_id - compute index form PCI function.
557  * @vsi: ptr to the VSI to read from.
558  * @hw: ptr to the hardware info.
559  **/
560 static u32 i40e_compute_pci_to_hw_id(struct i40e_vsi *vsi, struct i40e_hw *hw)
561 {
562         int pf_count = i40e_get_pf_count(hw);
563
564         if (vsi->type == I40E_VSI_SRIOV)
565                 return (hw->port * BIT(7)) / pf_count + vsi->vf_id;
566
567         return hw->port + BIT(7);
568 }
569
570 /**
571  * i40e_stat_update64 - read and update a 64 bit stat from the chip.
572  * @hw: ptr to the hardware info.
573  * @hireg: the high 32 bit reg to read.
574  * @loreg: the low 32 bit reg to read.
575  * @offset_loaded: has the initial offset been loaded yet.
576  * @offset: ptr to current offset value.
577  * @stat: ptr to the stat.
578  *
579  * Since the device stats are not reset at PFReset, they will not
580  * be zeroed when the driver starts.  We'll save the first values read
581  * and use them as offsets to be subtracted from the raw values in order
582  * to report stats that count from zero.
583  **/
584 static void i40e_stat_update64(struct i40e_hw *hw, u32 hireg, u32 loreg,
585                                bool offset_loaded, u64 *offset, u64 *stat)
586 {
587         u64 new_data;
588
589         new_data = rd64(hw, loreg);
590
591         if (!offset_loaded || new_data < *offset)
592                 *offset = new_data;
593         *stat = new_data - *offset;
594 }
595
596 /**
597  * i40e_stat_update48 - read and update a 48 bit stat from the chip
598  * @hw: ptr to the hardware info
599  * @hireg: the high 32 bit reg to read
600  * @loreg: the low 32 bit reg to read
601  * @offset_loaded: has the initial offset been loaded yet
602  * @offset: ptr to current offset value
603  * @stat: ptr to the stat
604  *
605  * Since the device stats are not reset at PFReset, they likely will not
606  * be zeroed when the driver starts.  We'll save the first values read
607  * and use them as offsets to be subtracted from the raw values in order
608  * to report stats that count from zero.  In the process, we also manage
609  * the potential roll-over.
610  **/
611 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
612                                bool offset_loaded, u64 *offset, u64 *stat)
613 {
614         u64 new_data;
615
616         if (hw->device_id == I40E_DEV_ID_QEMU) {
617                 new_data = rd32(hw, loreg);
618                 new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
619         } else {
620                 new_data = rd64(hw, loreg);
621         }
622         if (!offset_loaded)
623                 *offset = new_data;
624         if (likely(new_data >= *offset))
625                 *stat = new_data - *offset;
626         else
627                 *stat = (new_data + BIT_ULL(48)) - *offset;
628         *stat &= 0xFFFFFFFFFFFFULL;
629 }
630
631 /**
632  * i40e_stat_update32 - read and update a 32 bit stat from the chip
633  * @hw: ptr to the hardware info
634  * @reg: the hw reg to read
635  * @offset_loaded: has the initial offset been loaded yet
636  * @offset: ptr to current offset value
637  * @stat: ptr to the stat
638  **/
639 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
640                                bool offset_loaded, u64 *offset, u64 *stat)
641 {
642         u32 new_data;
643
644         new_data = rd32(hw, reg);
645         if (!offset_loaded)
646                 *offset = new_data;
647         if (likely(new_data >= *offset))
648                 *stat = (u32)(new_data - *offset);
649         else
650                 *stat = (u32)((new_data + BIT_ULL(32)) - *offset);
651 }
652
653 /**
654  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
655  * @hw: ptr to the hardware info
656  * @reg: the hw reg to read and clear
657  * @stat: ptr to the stat
658  **/
659 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
660 {
661         u32 new_data = rd32(hw, reg);
662
663         wr32(hw, reg, 1); /* must write a nonzero value to clear register */
664         *stat += new_data;
665 }
666
667 /**
668  * i40e_stats_update_rx_discards - update rx_discards.
669  * @vsi: ptr to the VSI to be updated.
670  * @hw: ptr to the hardware info.
671  * @stat_idx: VSI's stat_counter_idx.
672  * @offset_loaded: ptr to the VSI's stat_offsets_loaded.
673  * @stat_offset: ptr to stat_offset to store first read of specific register.
674  * @stat: ptr to VSI's stat to be updated.
675  **/
676 static void
677 i40e_stats_update_rx_discards(struct i40e_vsi *vsi, struct i40e_hw *hw,
678                               int stat_idx, bool offset_loaded,
679                               struct i40e_eth_stats *stat_offset,
680                               struct i40e_eth_stats *stat)
681 {
682         u64 rx_rdpc, rx_rxerr;
683
684         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx), offset_loaded,
685                            &stat_offset->rx_discards, &rx_rdpc);
686         i40e_stat_update64(hw,
687                            I40E_GL_RXERR1H(i40e_compute_pci_to_hw_id(vsi, hw)),
688                            I40E_GL_RXERR1L(i40e_compute_pci_to_hw_id(vsi, hw)),
689                            offset_loaded, &stat_offset->rx_discards_other,
690                            &rx_rxerr);
691
692         stat->rx_discards = rx_rdpc + rx_rxerr;
693 }
694
695 /**
696  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
697  * @vsi: the VSI to be updated
698  **/
699 void i40e_update_eth_stats(struct i40e_vsi *vsi)
700 {
701         int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
702         struct i40e_pf *pf = vsi->back;
703         struct i40e_hw *hw = &pf->hw;
704         struct i40e_eth_stats *oes;
705         struct i40e_eth_stats *es;     /* device's eth stats */
706
707         es = &vsi->eth_stats;
708         oes = &vsi->eth_stats_offsets;
709
710         /* Gather up the stats that the hw collects */
711         i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
712                            vsi->stat_offsets_loaded,
713                            &oes->tx_errors, &es->tx_errors);
714         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
715                            vsi->stat_offsets_loaded,
716                            &oes->rx_discards, &es->rx_discards);
717         i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
718                            vsi->stat_offsets_loaded,
719                            &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
720
721         i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
722                            I40E_GLV_GORCL(stat_idx),
723                            vsi->stat_offsets_loaded,
724                            &oes->rx_bytes, &es->rx_bytes);
725         i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
726                            I40E_GLV_UPRCL(stat_idx),
727                            vsi->stat_offsets_loaded,
728                            &oes->rx_unicast, &es->rx_unicast);
729         i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
730                            I40E_GLV_MPRCL(stat_idx),
731                            vsi->stat_offsets_loaded,
732                            &oes->rx_multicast, &es->rx_multicast);
733         i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
734                            I40E_GLV_BPRCL(stat_idx),
735                            vsi->stat_offsets_loaded,
736                            &oes->rx_broadcast, &es->rx_broadcast);
737
738         i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
739                            I40E_GLV_GOTCL(stat_idx),
740                            vsi->stat_offsets_loaded,
741                            &oes->tx_bytes, &es->tx_bytes);
742         i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
743                            I40E_GLV_UPTCL(stat_idx),
744                            vsi->stat_offsets_loaded,
745                            &oes->tx_unicast, &es->tx_unicast);
746         i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
747                            I40E_GLV_MPTCL(stat_idx),
748                            vsi->stat_offsets_loaded,
749                            &oes->tx_multicast, &es->tx_multicast);
750         i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
751                            I40E_GLV_BPTCL(stat_idx),
752                            vsi->stat_offsets_loaded,
753                            &oes->tx_broadcast, &es->tx_broadcast);
754
755         i40e_stats_update_rx_discards(vsi, hw, stat_idx,
756                                       vsi->stat_offsets_loaded, oes, es);
757
758         vsi->stat_offsets_loaded = true;
759 }
760
761 /**
762  * i40e_update_veb_stats - Update Switch component statistics
763  * @veb: the VEB being updated
764  **/
765 void i40e_update_veb_stats(struct i40e_veb *veb)
766 {
767         struct i40e_pf *pf = veb->pf;
768         struct i40e_hw *hw = &pf->hw;
769         struct i40e_eth_stats *oes;
770         struct i40e_eth_stats *es;     /* device's eth stats */
771         struct i40e_veb_tc_stats *veb_oes;
772         struct i40e_veb_tc_stats *veb_es;
773         int i, idx = 0;
774
775         idx = veb->stats_idx;
776         es = &veb->stats;
777         oes = &veb->stats_offsets;
778         veb_es = &veb->tc_stats;
779         veb_oes = &veb->tc_stats_offsets;
780
781         /* Gather up the stats that the hw collects */
782         i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
783                            veb->stat_offsets_loaded,
784                            &oes->tx_discards, &es->tx_discards);
785         if (hw->revision_id > 0)
786                 i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
787                                    veb->stat_offsets_loaded,
788                                    &oes->rx_unknown_protocol,
789                                    &es->rx_unknown_protocol);
790         i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
791                            veb->stat_offsets_loaded,
792                            &oes->rx_bytes, &es->rx_bytes);
793         i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
794                            veb->stat_offsets_loaded,
795                            &oes->rx_unicast, &es->rx_unicast);
796         i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
797                            veb->stat_offsets_loaded,
798                            &oes->rx_multicast, &es->rx_multicast);
799         i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
800                            veb->stat_offsets_loaded,
801                            &oes->rx_broadcast, &es->rx_broadcast);
802
803         i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
804                            veb->stat_offsets_loaded,
805                            &oes->tx_bytes, &es->tx_bytes);
806         i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
807                            veb->stat_offsets_loaded,
808                            &oes->tx_unicast, &es->tx_unicast);
809         i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
810                            veb->stat_offsets_loaded,
811                            &oes->tx_multicast, &es->tx_multicast);
812         i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
813                            veb->stat_offsets_loaded,
814                            &oes->tx_broadcast, &es->tx_broadcast);
815         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
816                 i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
817                                    I40E_GLVEBTC_RPCL(i, idx),
818                                    veb->stat_offsets_loaded,
819                                    &veb_oes->tc_rx_packets[i],
820                                    &veb_es->tc_rx_packets[i]);
821                 i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
822                                    I40E_GLVEBTC_RBCL(i, idx),
823                                    veb->stat_offsets_loaded,
824                                    &veb_oes->tc_rx_bytes[i],
825                                    &veb_es->tc_rx_bytes[i]);
826                 i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
827                                    I40E_GLVEBTC_TPCL(i, idx),
828                                    veb->stat_offsets_loaded,
829                                    &veb_oes->tc_tx_packets[i],
830                                    &veb_es->tc_tx_packets[i]);
831                 i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
832                                    I40E_GLVEBTC_TBCL(i, idx),
833                                    veb->stat_offsets_loaded,
834                                    &veb_oes->tc_tx_bytes[i],
835                                    &veb_es->tc_tx_bytes[i]);
836         }
837         veb->stat_offsets_loaded = true;
838 }
839
840 /**
841  * i40e_update_vsi_stats - Update the vsi statistics counters.
842  * @vsi: the VSI to be updated
843  *
844  * There are a few instances where we store the same stat in a
845  * couple of different structs.  This is partly because we have
846  * the netdev stats that need to be filled out, which is slightly
847  * different from the "eth_stats" defined by the chip and used in
848  * VF communications.  We sort it out here.
849  **/
850 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
851 {
852         u64 rx_page, rx_buf, rx_reuse, rx_alloc, rx_waive, rx_busy;
853         struct i40e_pf *pf = vsi->back;
854         struct rtnl_link_stats64 *ons;
855         struct rtnl_link_stats64 *ns;   /* netdev stats */
856         struct i40e_eth_stats *oes;
857         struct i40e_eth_stats *es;     /* device's eth stats */
858         u64 tx_restart, tx_busy;
859         struct i40e_ring *p;
860         u64 bytes, packets;
861         unsigned int start;
862         u64 tx_linearize;
863         u64 tx_force_wb;
864         u64 tx_stopped;
865         u64 rx_p, rx_b;
866         u64 tx_p, tx_b;
867         u16 q;
868
869         if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
870             test_bit(__I40E_CONFIG_BUSY, pf->state))
871                 return;
872
873         ns = i40e_get_vsi_stats_struct(vsi);
874         ons = &vsi->net_stats_offsets;
875         es = &vsi->eth_stats;
876         oes = &vsi->eth_stats_offsets;
877
878         /* Gather up the netdev and vsi stats that the driver collects
879          * on the fly during packet processing
880          */
881         rx_b = rx_p = 0;
882         tx_b = tx_p = 0;
883         tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
884         tx_stopped = 0;
885         rx_page = 0;
886         rx_buf = 0;
887         rx_reuse = 0;
888         rx_alloc = 0;
889         rx_waive = 0;
890         rx_busy = 0;
891         rcu_read_lock();
892         for (q = 0; q < vsi->num_queue_pairs; q++) {
893                 /* locate Tx ring */
894                 p = READ_ONCE(vsi->tx_rings[q]);
895                 if (!p)
896                         continue;
897
898                 do {
899                         start = u64_stats_fetch_begin_irq(&p->syncp);
900                         packets = p->stats.packets;
901                         bytes = p->stats.bytes;
902                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
903                 tx_b += bytes;
904                 tx_p += packets;
905                 tx_restart += p->tx_stats.restart_queue;
906                 tx_busy += p->tx_stats.tx_busy;
907                 tx_linearize += p->tx_stats.tx_linearize;
908                 tx_force_wb += p->tx_stats.tx_force_wb;
909                 tx_stopped += p->tx_stats.tx_stopped;
910
911                 /* locate Rx ring */
912                 p = READ_ONCE(vsi->rx_rings[q]);
913                 if (!p)
914                         continue;
915
916                 do {
917                         start = u64_stats_fetch_begin_irq(&p->syncp);
918                         packets = p->stats.packets;
919                         bytes = p->stats.bytes;
920                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
921                 rx_b += bytes;
922                 rx_p += packets;
923                 rx_buf += p->rx_stats.alloc_buff_failed;
924                 rx_page += p->rx_stats.alloc_page_failed;
925                 rx_reuse += p->rx_stats.page_reuse_count;
926                 rx_alloc += p->rx_stats.page_alloc_count;
927                 rx_waive += p->rx_stats.page_waive_count;
928                 rx_busy += p->rx_stats.page_busy_count;
929
930                 if (i40e_enabled_xdp_vsi(vsi)) {
931                         /* locate XDP ring */
932                         p = READ_ONCE(vsi->xdp_rings[q]);
933                         if (!p)
934                                 continue;
935
936                         do {
937                                 start = u64_stats_fetch_begin_irq(&p->syncp);
938                                 packets = p->stats.packets;
939                                 bytes = p->stats.bytes;
940                         } while (u64_stats_fetch_retry_irq(&p->syncp, start));
941                         tx_b += bytes;
942                         tx_p += packets;
943                         tx_restart += p->tx_stats.restart_queue;
944                         tx_busy += p->tx_stats.tx_busy;
945                         tx_linearize += p->tx_stats.tx_linearize;
946                         tx_force_wb += p->tx_stats.tx_force_wb;
947                 }
948         }
949         rcu_read_unlock();
950         vsi->tx_restart = tx_restart;
951         vsi->tx_busy = tx_busy;
952         vsi->tx_linearize = tx_linearize;
953         vsi->tx_force_wb = tx_force_wb;
954         vsi->tx_stopped = tx_stopped;
955         vsi->rx_page_failed = rx_page;
956         vsi->rx_buf_failed = rx_buf;
957         vsi->rx_page_reuse = rx_reuse;
958         vsi->rx_page_alloc = rx_alloc;
959         vsi->rx_page_waive = rx_waive;
960         vsi->rx_page_busy = rx_busy;
961
962         ns->rx_packets = rx_p;
963         ns->rx_bytes = rx_b;
964         ns->tx_packets = tx_p;
965         ns->tx_bytes = tx_b;
966
967         /* update netdev stats from eth stats */
968         i40e_update_eth_stats(vsi);
969         ons->tx_errors = oes->tx_errors;
970         ns->tx_errors = es->tx_errors;
971         ons->multicast = oes->rx_multicast;
972         ns->multicast = es->rx_multicast;
973         ons->rx_dropped = oes->rx_discards;
974         ns->rx_dropped = es->rx_discards;
975         ons->tx_dropped = oes->tx_discards;
976         ns->tx_dropped = es->tx_discards;
977
978         /* pull in a couple PF stats if this is the main vsi */
979         if (vsi == pf->vsi[pf->lan_vsi]) {
980                 ns->rx_crc_errors = pf->stats.crc_errors;
981                 ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
982                 ns->rx_length_errors = pf->stats.rx_length_errors;
983         }
984 }
985
986 /**
987  * i40e_update_pf_stats - Update the PF statistics counters.
988  * @pf: the PF to be updated
989  **/
990 static void i40e_update_pf_stats(struct i40e_pf *pf)
991 {
992         struct i40e_hw_port_stats *osd = &pf->stats_offsets;
993         struct i40e_hw_port_stats *nsd = &pf->stats;
994         struct i40e_hw *hw = &pf->hw;
995         u32 val;
996         int i;
997
998         i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
999                            I40E_GLPRT_GORCL(hw->port),
1000                            pf->stat_offsets_loaded,
1001                            &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
1002         i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
1003                            I40E_GLPRT_GOTCL(hw->port),
1004                            pf->stat_offsets_loaded,
1005                            &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
1006         i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
1007                            pf->stat_offsets_loaded,
1008                            &osd->eth.rx_discards,
1009                            &nsd->eth.rx_discards);
1010         i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
1011                            I40E_GLPRT_UPRCL(hw->port),
1012                            pf->stat_offsets_loaded,
1013                            &osd->eth.rx_unicast,
1014                            &nsd->eth.rx_unicast);
1015         i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
1016                            I40E_GLPRT_MPRCL(hw->port),
1017                            pf->stat_offsets_loaded,
1018                            &osd->eth.rx_multicast,
1019                            &nsd->eth.rx_multicast);
1020         i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
1021                            I40E_GLPRT_BPRCL(hw->port),
1022                            pf->stat_offsets_loaded,
1023                            &osd->eth.rx_broadcast,
1024                            &nsd->eth.rx_broadcast);
1025         i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
1026                            I40E_GLPRT_UPTCL(hw->port),
1027                            pf->stat_offsets_loaded,
1028                            &osd->eth.tx_unicast,
1029                            &nsd->eth.tx_unicast);
1030         i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
1031                            I40E_GLPRT_MPTCL(hw->port),
1032                            pf->stat_offsets_loaded,
1033                            &osd->eth.tx_multicast,
1034                            &nsd->eth.tx_multicast);
1035         i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
1036                            I40E_GLPRT_BPTCL(hw->port),
1037                            pf->stat_offsets_loaded,
1038                            &osd->eth.tx_broadcast,
1039                            &nsd->eth.tx_broadcast);
1040
1041         i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
1042                            pf->stat_offsets_loaded,
1043                            &osd->tx_dropped_link_down,
1044                            &nsd->tx_dropped_link_down);
1045
1046         i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
1047                            pf->stat_offsets_loaded,
1048                            &osd->crc_errors, &nsd->crc_errors);
1049
1050         i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
1051                            pf->stat_offsets_loaded,
1052                            &osd->illegal_bytes, &nsd->illegal_bytes);
1053
1054         i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
1055                            pf->stat_offsets_loaded,
1056                            &osd->mac_local_faults,
1057                            &nsd->mac_local_faults);
1058         i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
1059                            pf->stat_offsets_loaded,
1060                            &osd->mac_remote_faults,
1061                            &nsd->mac_remote_faults);
1062
1063         i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
1064                            pf->stat_offsets_loaded,
1065                            &osd->rx_length_errors,
1066                            &nsd->rx_length_errors);
1067
1068         i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
1069                            pf->stat_offsets_loaded,
1070                            &osd->link_xon_rx, &nsd->link_xon_rx);
1071         i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
1072                            pf->stat_offsets_loaded,
1073                            &osd->link_xon_tx, &nsd->link_xon_tx);
1074         i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
1075                            pf->stat_offsets_loaded,
1076                            &osd->link_xoff_rx, &nsd->link_xoff_rx);
1077         i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
1078                            pf->stat_offsets_loaded,
1079                            &osd->link_xoff_tx, &nsd->link_xoff_tx);
1080
1081         for (i = 0; i < 8; i++) {
1082                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
1083                                    pf->stat_offsets_loaded,
1084                                    &osd->priority_xoff_rx[i],
1085                                    &nsd->priority_xoff_rx[i]);
1086                 i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
1087                                    pf->stat_offsets_loaded,
1088                                    &osd->priority_xon_rx[i],
1089                                    &nsd->priority_xon_rx[i]);
1090                 i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
1091                                    pf->stat_offsets_loaded,
1092                                    &osd->priority_xon_tx[i],
1093                                    &nsd->priority_xon_tx[i]);
1094                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
1095                                    pf->stat_offsets_loaded,
1096                                    &osd->priority_xoff_tx[i],
1097                                    &nsd->priority_xoff_tx[i]);
1098                 i40e_stat_update32(hw,
1099                                    I40E_GLPRT_RXON2OFFCNT(hw->port, i),
1100                                    pf->stat_offsets_loaded,
1101                                    &osd->priority_xon_2_xoff[i],
1102                                    &nsd->priority_xon_2_xoff[i]);
1103         }
1104
1105         i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
1106                            I40E_GLPRT_PRC64L(hw->port),
1107                            pf->stat_offsets_loaded,
1108                            &osd->rx_size_64, &nsd->rx_size_64);
1109         i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
1110                            I40E_GLPRT_PRC127L(hw->port),
1111                            pf->stat_offsets_loaded,
1112                            &osd->rx_size_127, &nsd->rx_size_127);
1113         i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
1114                            I40E_GLPRT_PRC255L(hw->port),
1115                            pf->stat_offsets_loaded,
1116                            &osd->rx_size_255, &nsd->rx_size_255);
1117         i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1118                            I40E_GLPRT_PRC511L(hw->port),
1119                            pf->stat_offsets_loaded,
1120                            &osd->rx_size_511, &nsd->rx_size_511);
1121         i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1122                            I40E_GLPRT_PRC1023L(hw->port),
1123                            pf->stat_offsets_loaded,
1124                            &osd->rx_size_1023, &nsd->rx_size_1023);
1125         i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1126                            I40E_GLPRT_PRC1522L(hw->port),
1127                            pf->stat_offsets_loaded,
1128                            &osd->rx_size_1522, &nsd->rx_size_1522);
1129         i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1130                            I40E_GLPRT_PRC9522L(hw->port),
1131                            pf->stat_offsets_loaded,
1132                            &osd->rx_size_big, &nsd->rx_size_big);
1133
1134         i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1135                            I40E_GLPRT_PTC64L(hw->port),
1136                            pf->stat_offsets_loaded,
1137                            &osd->tx_size_64, &nsd->tx_size_64);
1138         i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1139                            I40E_GLPRT_PTC127L(hw->port),
1140                            pf->stat_offsets_loaded,
1141                            &osd->tx_size_127, &nsd->tx_size_127);
1142         i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1143                            I40E_GLPRT_PTC255L(hw->port),
1144                            pf->stat_offsets_loaded,
1145                            &osd->tx_size_255, &nsd->tx_size_255);
1146         i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1147                            I40E_GLPRT_PTC511L(hw->port),
1148                            pf->stat_offsets_loaded,
1149                            &osd->tx_size_511, &nsd->tx_size_511);
1150         i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1151                            I40E_GLPRT_PTC1023L(hw->port),
1152                            pf->stat_offsets_loaded,
1153                            &osd->tx_size_1023, &nsd->tx_size_1023);
1154         i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1155                            I40E_GLPRT_PTC1522L(hw->port),
1156                            pf->stat_offsets_loaded,
1157                            &osd->tx_size_1522, &nsd->tx_size_1522);
1158         i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1159                            I40E_GLPRT_PTC9522L(hw->port),
1160                            pf->stat_offsets_loaded,
1161                            &osd->tx_size_big, &nsd->tx_size_big);
1162
1163         i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1164                            pf->stat_offsets_loaded,
1165                            &osd->rx_undersize, &nsd->rx_undersize);
1166         i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1167                            pf->stat_offsets_loaded,
1168                            &osd->rx_fragments, &nsd->rx_fragments);
1169         i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1170                            pf->stat_offsets_loaded,
1171                            &osd->rx_oversize, &nsd->rx_oversize);
1172         i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1173                            pf->stat_offsets_loaded,
1174                            &osd->rx_jabber, &nsd->rx_jabber);
1175
1176         /* FDIR stats */
1177         i40e_stat_update_and_clear32(hw,
1178                         I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1179                         &nsd->fd_atr_match);
1180         i40e_stat_update_and_clear32(hw,
1181                         I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1182                         &nsd->fd_sb_match);
1183         i40e_stat_update_and_clear32(hw,
1184                         I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1185                         &nsd->fd_atr_tunnel_match);
1186
1187         val = rd32(hw, I40E_PRTPM_EEE_STAT);
1188         nsd->tx_lpi_status =
1189                        (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1190                         I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1191         nsd->rx_lpi_status =
1192                        (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1193                         I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1194         i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1195                            pf->stat_offsets_loaded,
1196                            &osd->tx_lpi_count, &nsd->tx_lpi_count);
1197         i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1198                            pf->stat_offsets_loaded,
1199                            &osd->rx_lpi_count, &nsd->rx_lpi_count);
1200
1201         if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1202             !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1203                 nsd->fd_sb_status = true;
1204         else
1205                 nsd->fd_sb_status = false;
1206
1207         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1208             !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1209                 nsd->fd_atr_status = true;
1210         else
1211                 nsd->fd_atr_status = false;
1212
1213         pf->stat_offsets_loaded = true;
1214 }
1215
1216 /**
1217  * i40e_update_stats - Update the various statistics counters.
1218  * @vsi: the VSI to be updated
1219  *
1220  * Update the various stats for this VSI and its related entities.
1221  **/
1222 void i40e_update_stats(struct i40e_vsi *vsi)
1223 {
1224         struct i40e_pf *pf = vsi->back;
1225
1226         if (vsi == pf->vsi[pf->lan_vsi])
1227                 i40e_update_pf_stats(pf);
1228
1229         i40e_update_vsi_stats(vsi);
1230 }
1231
1232 /**
1233  * i40e_count_filters - counts VSI mac filters
1234  * @vsi: the VSI to be searched
1235  *
1236  * Returns count of mac filters
1237  **/
1238 int i40e_count_filters(struct i40e_vsi *vsi)
1239 {
1240         struct i40e_mac_filter *f;
1241         struct hlist_node *h;
1242         int bkt;
1243         int cnt = 0;
1244
1245         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1246                 ++cnt;
1247
1248         return cnt;
1249 }
1250
1251 /**
1252  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1253  * @vsi: the VSI to be searched
1254  * @macaddr: the MAC address
1255  * @vlan: the vlan
1256  *
1257  * Returns ptr to the filter object or NULL
1258  **/
1259 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1260                                                 const u8 *macaddr, s16 vlan)
1261 {
1262         struct i40e_mac_filter *f;
1263         u64 key;
1264
1265         if (!vsi || !macaddr)
1266                 return NULL;
1267
1268         key = i40e_addr_to_hkey(macaddr);
1269         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1270                 if ((ether_addr_equal(macaddr, f->macaddr)) &&
1271                     (vlan == f->vlan))
1272                         return f;
1273         }
1274         return NULL;
1275 }
1276
1277 /**
1278  * i40e_find_mac - Find a mac addr in the macvlan filters list
1279  * @vsi: the VSI to be searched
1280  * @macaddr: the MAC address we are searching for
1281  *
1282  * Returns the first filter with the provided MAC address or NULL if
1283  * MAC address was not found
1284  **/
1285 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1286 {
1287         struct i40e_mac_filter *f;
1288         u64 key;
1289
1290         if (!vsi || !macaddr)
1291                 return NULL;
1292
1293         key = i40e_addr_to_hkey(macaddr);
1294         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1295                 if ((ether_addr_equal(macaddr, f->macaddr)))
1296                         return f;
1297         }
1298         return NULL;
1299 }
1300
1301 /**
1302  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1303  * @vsi: the VSI to be searched
1304  *
1305  * Returns true if VSI is in vlan mode or false otherwise
1306  **/
1307 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1308 {
1309         /* If we have a PVID, always operate in VLAN mode */
1310         if (vsi->info.pvid)
1311                 return true;
1312
1313         /* We need to operate in VLAN mode whenever we have any filters with
1314          * a VLAN other than I40E_VLAN_ALL. We could check the table each
1315          * time, incurring search cost repeatedly. However, we can notice two
1316          * things:
1317          *
1318          * 1) the only place where we can gain a VLAN filter is in
1319          *    i40e_add_filter.
1320          *
1321          * 2) the only place where filters are actually removed is in
1322          *    i40e_sync_filters_subtask.
1323          *
1324          * Thus, we can simply use a boolean value, has_vlan_filters which we
1325          * will set to true when we add a VLAN filter in i40e_add_filter. Then
1326          * we have to perform the full search after deleting filters in
1327          * i40e_sync_filters_subtask, but we already have to search
1328          * filters here and can perform the check at the same time. This
1329          * results in avoiding embedding a loop for VLAN mode inside another
1330          * loop over all the filters, and should maintain correctness as noted
1331          * above.
1332          */
1333         return vsi->has_vlan_filter;
1334 }
1335
1336 /**
1337  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1338  * @vsi: the VSI to configure
1339  * @tmp_add_list: list of filters ready to be added
1340  * @tmp_del_list: list of filters ready to be deleted
1341  * @vlan_filters: the number of active VLAN filters
1342  *
1343  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1344  * behave as expected. If we have any active VLAN filters remaining or about
1345  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1346  * so that they only match against untagged traffic. If we no longer have any
1347  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1348  * so that they match against both tagged and untagged traffic. In this way,
1349  * we ensure that we correctly receive the desired traffic. This ensures that
1350  * when we have an active VLAN we will receive only untagged traffic and
1351  * traffic matching active VLANs. If we have no active VLANs then we will
1352  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1353  *
1354  * Finally, in a similar fashion, this function also corrects filters when
1355  * there is an active PVID assigned to this VSI.
1356  *
1357  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1358  *
1359  * This function is only expected to be called from within
1360  * i40e_sync_vsi_filters.
1361  *
1362  * NOTE: This function expects to be called while under the
1363  * mac_filter_hash_lock
1364  */
1365 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1366                                          struct hlist_head *tmp_add_list,
1367                                          struct hlist_head *tmp_del_list,
1368                                          int vlan_filters)
1369 {
1370         s16 pvid = le16_to_cpu(vsi->info.pvid);
1371         struct i40e_mac_filter *f, *add_head;
1372         struct i40e_new_mac_filter *new;
1373         struct hlist_node *h;
1374         int bkt, new_vlan;
1375
1376         /* To determine if a particular filter needs to be replaced we
1377          * have the three following conditions:
1378          *
1379          * a) if we have a PVID assigned, then all filters which are
1380          *    not marked as VLAN=PVID must be replaced with filters that
1381          *    are.
1382          * b) otherwise, if we have any active VLANS, all filters
1383          *    which are marked as VLAN=-1 must be replaced with
1384          *    filters marked as VLAN=0
1385          * c) finally, if we do not have any active VLANS, all filters
1386          *    which are marked as VLAN=0 must be replaced with filters
1387          *    marked as VLAN=-1
1388          */
1389
1390         /* Update the filters about to be added in place */
1391         hlist_for_each_entry(new, tmp_add_list, hlist) {
1392                 if (pvid && new->f->vlan != pvid)
1393                         new->f->vlan = pvid;
1394                 else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1395                         new->f->vlan = 0;
1396                 else if (!vlan_filters && new->f->vlan == 0)
1397                         new->f->vlan = I40E_VLAN_ANY;
1398         }
1399
1400         /* Update the remaining active filters */
1401         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1402                 /* Combine the checks for whether a filter needs to be changed
1403                  * and then determine the new VLAN inside the if block, in
1404                  * order to avoid duplicating code for adding the new filter
1405                  * then deleting the old filter.
1406                  */
1407                 if ((pvid && f->vlan != pvid) ||
1408                     (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1409                     (!vlan_filters && f->vlan == 0)) {
1410                         /* Determine the new vlan we will be adding */
1411                         if (pvid)
1412                                 new_vlan = pvid;
1413                         else if (vlan_filters)
1414                                 new_vlan = 0;
1415                         else
1416                                 new_vlan = I40E_VLAN_ANY;
1417
1418                         /* Create the new filter */
1419                         add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1420                         if (!add_head)
1421                                 return -ENOMEM;
1422
1423                         /* Create a temporary i40e_new_mac_filter */
1424                         new = kzalloc(sizeof(*new), GFP_ATOMIC);
1425                         if (!new)
1426                                 return -ENOMEM;
1427
1428                         new->f = add_head;
1429                         new->state = add_head->state;
1430
1431                         /* Add the new filter to the tmp list */
1432                         hlist_add_head(&new->hlist, tmp_add_list);
1433
1434                         /* Put the original filter into the delete list */
1435                         f->state = I40E_FILTER_REMOVE;
1436                         hash_del(&f->hlist);
1437                         hlist_add_head(&f->hlist, tmp_del_list);
1438                 }
1439         }
1440
1441         vsi->has_vlan_filter = !!vlan_filters;
1442
1443         return 0;
1444 }
1445
1446 /**
1447  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1448  * @vsi: the PF Main VSI - inappropriate for any other VSI
1449  * @macaddr: the MAC address
1450  *
1451  * Remove whatever filter the firmware set up so the driver can manage
1452  * its own filtering intelligently.
1453  **/
1454 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1455 {
1456         struct i40e_aqc_remove_macvlan_element_data element;
1457         struct i40e_pf *pf = vsi->back;
1458
1459         /* Only appropriate for the PF main VSI */
1460         if (vsi->type != I40E_VSI_MAIN)
1461                 return;
1462
1463         memset(&element, 0, sizeof(element));
1464         ether_addr_copy(element.mac_addr, macaddr);
1465         element.vlan_tag = 0;
1466         /* Ignore error returns, some firmware does it this way... */
1467         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1468         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1469
1470         memset(&element, 0, sizeof(element));
1471         ether_addr_copy(element.mac_addr, macaddr);
1472         element.vlan_tag = 0;
1473         /* ...and some firmware does it this way. */
1474         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1475                         I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1476         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1477 }
1478
1479 /**
1480  * i40e_add_filter - Add a mac/vlan filter to the VSI
1481  * @vsi: the VSI to be searched
1482  * @macaddr: the MAC address
1483  * @vlan: the vlan
1484  *
1485  * Returns ptr to the filter object or NULL when no memory available.
1486  *
1487  * NOTE: This function is expected to be called with mac_filter_hash_lock
1488  * being held.
1489  **/
1490 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1491                                         const u8 *macaddr, s16 vlan)
1492 {
1493         struct i40e_mac_filter *f;
1494         u64 key;
1495
1496         if (!vsi || !macaddr)
1497                 return NULL;
1498
1499         f = i40e_find_filter(vsi, macaddr, vlan);
1500         if (!f) {
1501                 f = kzalloc(sizeof(*f), GFP_ATOMIC);
1502                 if (!f)
1503                         return NULL;
1504
1505                 /* Update the boolean indicating if we need to function in
1506                  * VLAN mode.
1507                  */
1508                 if (vlan >= 0)
1509                         vsi->has_vlan_filter = true;
1510
1511                 ether_addr_copy(f->macaddr, macaddr);
1512                 f->vlan = vlan;
1513                 f->state = I40E_FILTER_NEW;
1514                 INIT_HLIST_NODE(&f->hlist);
1515
1516                 key = i40e_addr_to_hkey(macaddr);
1517                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
1518
1519                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1520                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1521         }
1522
1523         /* If we're asked to add a filter that has been marked for removal, it
1524          * is safe to simply restore it to active state. __i40e_del_filter
1525          * will have simply deleted any filters which were previously marked
1526          * NEW or FAILED, so if it is currently marked REMOVE it must have
1527          * previously been ACTIVE. Since we haven't yet run the sync filters
1528          * task, just restore this filter to the ACTIVE state so that the
1529          * sync task leaves it in place
1530          */
1531         if (f->state == I40E_FILTER_REMOVE)
1532                 f->state = I40E_FILTER_ACTIVE;
1533
1534         return f;
1535 }
1536
1537 /**
1538  * __i40e_del_filter - Remove a specific filter from the VSI
1539  * @vsi: VSI to remove from
1540  * @f: the filter to remove from the list
1541  *
1542  * This function should be called instead of i40e_del_filter only if you know
1543  * the exact filter you will remove already, such as via i40e_find_filter or
1544  * i40e_find_mac.
1545  *
1546  * NOTE: This function is expected to be called with mac_filter_hash_lock
1547  * being held.
1548  * ANOTHER NOTE: This function MUST be called from within the context of
1549  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1550  * instead of list_for_each_entry().
1551  **/
1552 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1553 {
1554         if (!f)
1555                 return;
1556
1557         /* If the filter was never added to firmware then we can just delete it
1558          * directly and we don't want to set the status to remove or else an
1559          * admin queue command will unnecessarily fire.
1560          */
1561         if ((f->state == I40E_FILTER_FAILED) ||
1562             (f->state == I40E_FILTER_NEW)) {
1563                 hash_del(&f->hlist);
1564                 kfree(f);
1565         } else {
1566                 f->state = I40E_FILTER_REMOVE;
1567         }
1568
1569         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1570         set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1571 }
1572
1573 /**
1574  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1575  * @vsi: the VSI to be searched
1576  * @macaddr: the MAC address
1577  * @vlan: the VLAN
1578  *
1579  * NOTE: This function is expected to be called with mac_filter_hash_lock
1580  * being held.
1581  * ANOTHER NOTE: This function MUST be called from within the context of
1582  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1583  * instead of list_for_each_entry().
1584  **/
1585 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1586 {
1587         struct i40e_mac_filter *f;
1588
1589         if (!vsi || !macaddr)
1590                 return;
1591
1592         f = i40e_find_filter(vsi, macaddr, vlan);
1593         __i40e_del_filter(vsi, f);
1594 }
1595
1596 /**
1597  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1598  * @vsi: the VSI to be searched
1599  * @macaddr: the mac address to be filtered
1600  *
1601  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1602  * go through all the macvlan filters and add a macvlan filter for each
1603  * unique vlan that already exists. If a PVID has been assigned, instead only
1604  * add the macaddr to that VLAN.
1605  *
1606  * Returns last filter added on success, else NULL
1607  **/
1608 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1609                                             const u8 *macaddr)
1610 {
1611         struct i40e_mac_filter *f, *add = NULL;
1612         struct hlist_node *h;
1613         int bkt;
1614
1615         if (vsi->info.pvid)
1616                 return i40e_add_filter(vsi, macaddr,
1617                                        le16_to_cpu(vsi->info.pvid));
1618
1619         if (!i40e_is_vsi_in_vlan(vsi))
1620                 return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1621
1622         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1623                 if (f->state == I40E_FILTER_REMOVE)
1624                         continue;
1625                 add = i40e_add_filter(vsi, macaddr, f->vlan);
1626                 if (!add)
1627                         return NULL;
1628         }
1629
1630         return add;
1631 }
1632
1633 /**
1634  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1635  * @vsi: the VSI to be searched
1636  * @macaddr: the mac address to be removed
1637  *
1638  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1639  * associated with.
1640  *
1641  * Returns 0 for success, or error
1642  **/
1643 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1644 {
1645         struct i40e_mac_filter *f;
1646         struct hlist_node *h;
1647         bool found = false;
1648         int bkt;
1649
1650         lockdep_assert_held(&vsi->mac_filter_hash_lock);
1651         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1652                 if (ether_addr_equal(macaddr, f->macaddr)) {
1653                         __i40e_del_filter(vsi, f);
1654                         found = true;
1655                 }
1656         }
1657
1658         if (found)
1659                 return 0;
1660         else
1661                 return -ENOENT;
1662 }
1663
1664 /**
1665  * i40e_set_mac - NDO callback to set mac address
1666  * @netdev: network interface device structure
1667  * @p: pointer to an address structure
1668  *
1669  * Returns 0 on success, negative on failure
1670  **/
1671 static int i40e_set_mac(struct net_device *netdev, void *p)
1672 {
1673         struct i40e_netdev_priv *np = netdev_priv(netdev);
1674         struct i40e_vsi *vsi = np->vsi;
1675         struct i40e_pf *pf = vsi->back;
1676         struct i40e_hw *hw = &pf->hw;
1677         struct sockaddr *addr = p;
1678
1679         if (!is_valid_ether_addr(addr->sa_data))
1680                 return -EADDRNOTAVAIL;
1681
1682         if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1683                 netdev_info(netdev, "already using mac address %pM\n",
1684                             addr->sa_data);
1685                 return 0;
1686         }
1687
1688         if (test_bit(__I40E_DOWN, pf->state) ||
1689             test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1690                 return -EADDRNOTAVAIL;
1691
1692         if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1693                 netdev_info(netdev, "returning to hw mac address %pM\n",
1694                             hw->mac.addr);
1695         else
1696                 netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1697
1698         /* Copy the address first, so that we avoid a possible race with
1699          * .set_rx_mode().
1700          * - Remove old address from MAC filter
1701          * - Copy new address
1702          * - Add new address to MAC filter
1703          */
1704         spin_lock_bh(&vsi->mac_filter_hash_lock);
1705         i40e_del_mac_filter(vsi, netdev->dev_addr);
1706         eth_hw_addr_set(netdev, addr->sa_data);
1707         i40e_add_mac_filter(vsi, netdev->dev_addr);
1708         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1709
1710         if (vsi->type == I40E_VSI_MAIN) {
1711                 i40e_status ret;
1712
1713                 ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1714                                                 addr->sa_data, NULL);
1715                 if (ret)
1716                         netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1717                                     i40e_stat_str(hw, ret),
1718                                     i40e_aq_str(hw, hw->aq.asq_last_status));
1719         }
1720
1721         /* schedule our worker thread which will take care of
1722          * applying the new filter changes
1723          */
1724         i40e_service_event_schedule(pf);
1725         return 0;
1726 }
1727
1728 /**
1729  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1730  * @vsi: vsi structure
1731  * @seed: RSS hash seed
1732  * @lut: pointer to lookup table of lut_size
1733  * @lut_size: size of the lookup table
1734  **/
1735 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1736                               u8 *lut, u16 lut_size)
1737 {
1738         struct i40e_pf *pf = vsi->back;
1739         struct i40e_hw *hw = &pf->hw;
1740         int ret = 0;
1741
1742         if (seed) {
1743                 struct i40e_aqc_get_set_rss_key_data *seed_dw =
1744                         (struct i40e_aqc_get_set_rss_key_data *)seed;
1745                 ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1746                 if (ret) {
1747                         dev_info(&pf->pdev->dev,
1748                                  "Cannot set RSS key, err %s aq_err %s\n",
1749                                  i40e_stat_str(hw, ret),
1750                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1751                         return ret;
1752                 }
1753         }
1754         if (lut) {
1755                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
1756
1757                 ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1758                 if (ret) {
1759                         dev_info(&pf->pdev->dev,
1760                                  "Cannot set RSS lut, err %s aq_err %s\n",
1761                                  i40e_stat_str(hw, ret),
1762                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1763                         return ret;
1764                 }
1765         }
1766         return ret;
1767 }
1768
1769 /**
1770  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1771  * @vsi: VSI structure
1772  **/
1773 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1774 {
1775         struct i40e_pf *pf = vsi->back;
1776         u8 seed[I40E_HKEY_ARRAY_SIZE];
1777         u8 *lut;
1778         int ret;
1779
1780         if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1781                 return 0;
1782         if (!vsi->rss_size)
1783                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
1784                                       vsi->num_queue_pairs);
1785         if (!vsi->rss_size)
1786                 return -EINVAL;
1787         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1788         if (!lut)
1789                 return -ENOMEM;
1790
1791         /* Use the user configured hash keys and lookup table if there is one,
1792          * otherwise use default
1793          */
1794         if (vsi->rss_lut_user)
1795                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1796         else
1797                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1798         if (vsi->rss_hkey_user)
1799                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1800         else
1801                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1802         ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1803         kfree(lut);
1804         return ret;
1805 }
1806
1807 /**
1808  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1809  * @vsi: the VSI being configured,
1810  * @ctxt: VSI context structure
1811  * @enabled_tc: number of traffic classes to enable
1812  *
1813  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1814  **/
1815 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1816                                            struct i40e_vsi_context *ctxt,
1817                                            u8 enabled_tc)
1818 {
1819         u16 qcount = 0, max_qcount, qmap, sections = 0;
1820         int i, override_q, pow, num_qps, ret;
1821         u8 netdev_tc = 0, offset = 0;
1822
1823         if (vsi->type != I40E_VSI_MAIN)
1824                 return -EINVAL;
1825         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1826         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1827         vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1828         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1829         num_qps = vsi->mqprio_qopt.qopt.count[0];
1830
1831         /* find the next higher power-of-2 of num queue pairs */
1832         pow = ilog2(num_qps);
1833         if (!is_power_of_2(num_qps))
1834                 pow++;
1835         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1836                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1837
1838         /* Setup queue offset/count for all TCs for given VSI */
1839         max_qcount = vsi->mqprio_qopt.qopt.count[0];
1840         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1841                 /* See if the given TC is enabled for the given VSI */
1842                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1843                         offset = vsi->mqprio_qopt.qopt.offset[i];
1844                         qcount = vsi->mqprio_qopt.qopt.count[i];
1845                         if (qcount > max_qcount)
1846                                 max_qcount = qcount;
1847                         vsi->tc_config.tc_info[i].qoffset = offset;
1848                         vsi->tc_config.tc_info[i].qcount = qcount;
1849                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1850                 } else {
1851                         /* TC is not enabled so set the offset to
1852                          * default queue and allocate one queue
1853                          * for the given TC.
1854                          */
1855                         vsi->tc_config.tc_info[i].qoffset = 0;
1856                         vsi->tc_config.tc_info[i].qcount = 1;
1857                         vsi->tc_config.tc_info[i].netdev_tc = 0;
1858                 }
1859         }
1860
1861         /* Set actual Tx/Rx queue pairs */
1862         vsi->num_queue_pairs = offset + qcount;
1863
1864         /* Setup queue TC[0].qmap for given VSI context */
1865         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1866         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1867         ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1868         ctxt->info.valid_sections |= cpu_to_le16(sections);
1869
1870         /* Reconfigure RSS for main VSI with max queue count */
1871         vsi->rss_size = max_qcount;
1872         ret = i40e_vsi_config_rss(vsi);
1873         if (ret) {
1874                 dev_info(&vsi->back->pdev->dev,
1875                          "Failed to reconfig rss for num_queues (%u)\n",
1876                          max_qcount);
1877                 return ret;
1878         }
1879         vsi->reconfig_rss = true;
1880         dev_dbg(&vsi->back->pdev->dev,
1881                 "Reconfigured rss with num_queues (%u)\n", max_qcount);
1882
1883         /* Find queue count available for channel VSIs and starting offset
1884          * for channel VSIs
1885          */
1886         override_q = vsi->mqprio_qopt.qopt.count[0];
1887         if (override_q && override_q < vsi->num_queue_pairs) {
1888                 vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1889                 vsi->next_base_queue = override_q;
1890         }
1891         return 0;
1892 }
1893
1894 /**
1895  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1896  * @vsi: the VSI being setup
1897  * @ctxt: VSI context structure
1898  * @enabled_tc: Enabled TCs bitmap
1899  * @is_add: True if called before Add VSI
1900  *
1901  * Setup VSI queue mapping for enabled traffic classes.
1902  **/
1903 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
1904                                      struct i40e_vsi_context *ctxt,
1905                                      u8 enabled_tc,
1906                                      bool is_add)
1907 {
1908         struct i40e_pf *pf = vsi->back;
1909         u16 num_tc_qps = 0;
1910         u16 sections = 0;
1911         u8 netdev_tc = 0;
1912         u16 numtc = 1;
1913         u16 qcount;
1914         u8 offset;
1915         u16 qmap;
1916         int i;
1917
1918         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1919         offset = 0;
1920         /* zero out queue mapping, it will get updated on the end of the function */
1921         memset(ctxt->info.queue_mapping, 0, sizeof(ctxt->info.queue_mapping));
1922
1923         if (vsi->type == I40E_VSI_MAIN) {
1924                 /* This code helps add more queue to the VSI if we have
1925                  * more cores than RSS can support, the higher cores will
1926                  * be served by ATR or other filters. Furthermore, the
1927                  * non-zero req_queue_pairs says that user requested a new
1928                  * queue count via ethtool's set_channels, so use this
1929                  * value for queues distribution across traffic classes
1930                  * We need at least one queue pair for the interface
1931                  * to be usable as we see in else statement.
1932                  */
1933                 if (vsi->req_queue_pairs > 0)
1934                         vsi->num_queue_pairs = vsi->req_queue_pairs;
1935                 else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1936                         vsi->num_queue_pairs = pf->num_lan_msix;
1937                 else
1938                         vsi->num_queue_pairs = 1;
1939         }
1940
1941         /* Number of queues per enabled TC */
1942         if (vsi->type == I40E_VSI_MAIN ||
1943             (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs != 0))
1944                 num_tc_qps = vsi->num_queue_pairs;
1945         else
1946                 num_tc_qps = vsi->alloc_queue_pairs;
1947
1948         if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
1949                 /* Find numtc from enabled TC bitmap */
1950                 for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1951                         if (enabled_tc & BIT(i)) /* TC is enabled */
1952                                 numtc++;
1953                 }
1954                 if (!numtc) {
1955                         dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
1956                         numtc = 1;
1957                 }
1958                 num_tc_qps = num_tc_qps / numtc;
1959                 num_tc_qps = min_t(int, num_tc_qps,
1960                                    i40e_pf_get_max_q_per_tc(pf));
1961         }
1962
1963         vsi->tc_config.numtc = numtc;
1964         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1965
1966         /* Do not allow use more TC queue pairs than MSI-X vectors exist */
1967         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1968                 num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
1969
1970         /* Setup queue offset/count for all TCs for given VSI */
1971         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1972                 /* See if the given TC is enabled for the given VSI */
1973                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1974                         /* TC is enabled */
1975                         int pow, num_qps;
1976
1977                         switch (vsi->type) {
1978                         case I40E_VSI_MAIN:
1979                                 if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
1980                                     I40E_FLAG_FD_ATR_ENABLED)) ||
1981                                     vsi->tc_config.enabled_tc != 1) {
1982                                         qcount = min_t(int, pf->alloc_rss_size,
1983                                                        num_tc_qps);
1984                                         break;
1985                                 }
1986                                 fallthrough;
1987                         case I40E_VSI_FDIR:
1988                         case I40E_VSI_SRIOV:
1989                         case I40E_VSI_VMDQ2:
1990                         default:
1991                                 qcount = num_tc_qps;
1992                                 WARN_ON(i != 0);
1993                                 break;
1994                         }
1995                         vsi->tc_config.tc_info[i].qoffset = offset;
1996                         vsi->tc_config.tc_info[i].qcount = qcount;
1997
1998                         /* find the next higher power-of-2 of num queue pairs */
1999                         num_qps = qcount;
2000                         pow = 0;
2001                         while (num_qps && (BIT_ULL(pow) < qcount)) {
2002                                 pow++;
2003                                 num_qps >>= 1;
2004                         }
2005
2006                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
2007                         qmap =
2008                             (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
2009                             (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
2010
2011                         offset += qcount;
2012                 } else {
2013                         /* TC is not enabled so set the offset to
2014                          * default queue and allocate one queue
2015                          * for the given TC.
2016                          */
2017                         vsi->tc_config.tc_info[i].qoffset = 0;
2018                         vsi->tc_config.tc_info[i].qcount = 1;
2019                         vsi->tc_config.tc_info[i].netdev_tc = 0;
2020
2021                         qmap = 0;
2022                 }
2023                 ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
2024         }
2025         /* Do not change previously set num_queue_pairs for PFs and VFs*/
2026         if ((vsi->type == I40E_VSI_MAIN && numtc != 1) ||
2027             (vsi->type == I40E_VSI_SRIOV && vsi->num_queue_pairs == 0) ||
2028             (vsi->type != I40E_VSI_MAIN && vsi->type != I40E_VSI_SRIOV))
2029                 vsi->num_queue_pairs = offset;
2030
2031         /* Scheduler section valid can only be set for ADD VSI */
2032         if (is_add) {
2033                 sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
2034
2035                 ctxt->info.up_enable_bits = enabled_tc;
2036         }
2037         if (vsi->type == I40E_VSI_SRIOV) {
2038                 ctxt->info.mapping_flags |=
2039                                      cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
2040                 for (i = 0; i < vsi->num_queue_pairs; i++)
2041                         ctxt->info.queue_mapping[i] =
2042                                                cpu_to_le16(vsi->base_queue + i);
2043         } else {
2044                 ctxt->info.mapping_flags |=
2045                                         cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
2046                 ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
2047         }
2048         ctxt->info.valid_sections |= cpu_to_le16(sections);
2049 }
2050
2051 /**
2052  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
2053  * @netdev: the netdevice
2054  * @addr: address to add
2055  *
2056  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
2057  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2058  */
2059 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
2060 {
2061         struct i40e_netdev_priv *np = netdev_priv(netdev);
2062         struct i40e_vsi *vsi = np->vsi;
2063
2064         if (i40e_add_mac_filter(vsi, addr))
2065                 return 0;
2066         else
2067                 return -ENOMEM;
2068 }
2069
2070 /**
2071  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
2072  * @netdev: the netdevice
2073  * @addr: address to add
2074  *
2075  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
2076  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
2077  */
2078 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
2079 {
2080         struct i40e_netdev_priv *np = netdev_priv(netdev);
2081         struct i40e_vsi *vsi = np->vsi;
2082
2083         /* Under some circumstances, we might receive a request to delete
2084          * our own device address from our uc list. Because we store the
2085          * device address in the VSI's MAC/VLAN filter list, we need to ignore
2086          * such requests and not delete our device address from this list.
2087          */
2088         if (ether_addr_equal(addr, netdev->dev_addr))
2089                 return 0;
2090
2091         i40e_del_mac_filter(vsi, addr);
2092
2093         return 0;
2094 }
2095
2096 /**
2097  * i40e_set_rx_mode - NDO callback to set the netdev filters
2098  * @netdev: network interface device structure
2099  **/
2100 static void i40e_set_rx_mode(struct net_device *netdev)
2101 {
2102         struct i40e_netdev_priv *np = netdev_priv(netdev);
2103         struct i40e_vsi *vsi = np->vsi;
2104
2105         spin_lock_bh(&vsi->mac_filter_hash_lock);
2106
2107         __dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2108         __dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
2109
2110         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2111
2112         /* check for other flag changes */
2113         if (vsi->current_netdev_flags != vsi->netdev->flags) {
2114                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2115                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
2116         }
2117 }
2118
2119 /**
2120  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
2121  * @vsi: Pointer to VSI struct
2122  * @from: Pointer to list which contains MAC filter entries - changes to
2123  *        those entries needs to be undone.
2124  *
2125  * MAC filter entries from this list were slated for deletion.
2126  **/
2127 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
2128                                          struct hlist_head *from)
2129 {
2130         struct i40e_mac_filter *f;
2131         struct hlist_node *h;
2132
2133         hlist_for_each_entry_safe(f, h, from, hlist) {
2134                 u64 key = i40e_addr_to_hkey(f->macaddr);
2135
2136                 /* Move the element back into MAC filter list*/
2137                 hlist_del(&f->hlist);
2138                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
2139         }
2140 }
2141
2142 /**
2143  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2144  * @vsi: Pointer to vsi struct
2145  * @from: Pointer to list which contains MAC filter entries - changes to
2146  *        those entries needs to be undone.
2147  *
2148  * MAC filter entries from this list were slated for addition.
2149  **/
2150 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2151                                          struct hlist_head *from)
2152 {
2153         struct i40e_new_mac_filter *new;
2154         struct hlist_node *h;
2155
2156         hlist_for_each_entry_safe(new, h, from, hlist) {
2157                 /* We can simply free the wrapper structure */
2158                 hlist_del(&new->hlist);
2159                 netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2160                 kfree(new);
2161         }
2162 }
2163
2164 /**
2165  * i40e_next_filter - Get the next non-broadcast filter from a list
2166  * @next: pointer to filter in list
2167  *
2168  * Returns the next non-broadcast filter in the list. Required so that we
2169  * ignore broadcast filters within the list, since these are not handled via
2170  * the normal firmware update path.
2171  */
2172 static
2173 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2174 {
2175         hlist_for_each_entry_continue(next, hlist) {
2176                 if (!is_broadcast_ether_addr(next->f->macaddr))
2177                         return next;
2178         }
2179
2180         return NULL;
2181 }
2182
2183 /**
2184  * i40e_update_filter_state - Update filter state based on return data
2185  * from firmware
2186  * @count: Number of filters added
2187  * @add_list: return data from fw
2188  * @add_head: pointer to first filter in current batch
2189  *
2190  * MAC filter entries from list were slated to be added to device. Returns
2191  * number of successful filters. Note that 0 does NOT mean success!
2192  **/
2193 static int
2194 i40e_update_filter_state(int count,
2195                          struct i40e_aqc_add_macvlan_element_data *add_list,
2196                          struct i40e_new_mac_filter *add_head)
2197 {
2198         int retval = 0;
2199         int i;
2200
2201         for (i = 0; i < count; i++) {
2202                 /* Always check status of each filter. We don't need to check
2203                  * the firmware return status because we pre-set the filter
2204                  * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2205                  * request to the adminq. Thus, if it no longer matches then
2206                  * we know the filter is active.
2207                  */
2208                 if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2209                         add_head->state = I40E_FILTER_FAILED;
2210                 } else {
2211                         add_head->state = I40E_FILTER_ACTIVE;
2212                         retval++;
2213                 }
2214
2215                 add_head = i40e_next_filter(add_head);
2216                 if (!add_head)
2217                         break;
2218         }
2219
2220         return retval;
2221 }
2222
2223 /**
2224  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2225  * @vsi: ptr to the VSI
2226  * @vsi_name: name to display in messages
2227  * @list: the list of filters to send to firmware
2228  * @num_del: the number of filters to delete
2229  * @retval: Set to -EIO on failure to delete
2230  *
2231  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2232  * *retval instead of a return value so that success does not force ret_val to
2233  * be set to 0. This ensures that a sequence of calls to this function
2234  * preserve the previous value of *retval on successful delete.
2235  */
2236 static
2237 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2238                           struct i40e_aqc_remove_macvlan_element_data *list,
2239                           int num_del, int *retval)
2240 {
2241         struct i40e_hw *hw = &vsi->back->hw;
2242         enum i40e_admin_queue_err aq_status;
2243         i40e_status aq_ret;
2244
2245         aq_ret = i40e_aq_remove_macvlan_v2(hw, vsi->seid, list, num_del, NULL,
2246                                            &aq_status);
2247
2248         /* Explicitly ignore and do not report when firmware returns ENOENT */
2249         if (aq_ret && !(aq_status == I40E_AQ_RC_ENOENT)) {
2250                 *retval = -EIO;
2251                 dev_info(&vsi->back->pdev->dev,
2252                          "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
2253                          vsi_name, i40e_stat_str(hw, aq_ret),
2254                          i40e_aq_str(hw, aq_status));
2255         }
2256 }
2257
2258 /**
2259  * i40e_aqc_add_filters - Request firmware to add a set of filters
2260  * @vsi: ptr to the VSI
2261  * @vsi_name: name to display in messages
2262  * @list: the list of filters to send to firmware
2263  * @add_head: Position in the add hlist
2264  * @num_add: the number of filters to add
2265  *
2266  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2267  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2268  * space for more filters.
2269  */
2270 static
2271 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2272                           struct i40e_aqc_add_macvlan_element_data *list,
2273                           struct i40e_new_mac_filter *add_head,
2274                           int num_add)
2275 {
2276         struct i40e_hw *hw = &vsi->back->hw;
2277         enum i40e_admin_queue_err aq_status;
2278         int fcnt;
2279
2280         i40e_aq_add_macvlan_v2(hw, vsi->seid, list, num_add, NULL, &aq_status);
2281         fcnt = i40e_update_filter_state(num_add, list, add_head);
2282
2283         if (fcnt != num_add) {
2284                 if (vsi->type == I40E_VSI_MAIN) {
2285                         set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2286                         dev_warn(&vsi->back->pdev->dev,
2287                                  "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2288                                  i40e_aq_str(hw, aq_status), vsi_name);
2289                 } else if (vsi->type == I40E_VSI_SRIOV ||
2290                            vsi->type == I40E_VSI_VMDQ1 ||
2291                            vsi->type == I40E_VSI_VMDQ2) {
2292                         dev_warn(&vsi->back->pdev->dev,
2293                                  "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2294                                  i40e_aq_str(hw, aq_status), vsi_name,
2295                                              vsi_name);
2296                 } else {
2297                         dev_warn(&vsi->back->pdev->dev,
2298                                  "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2299                                  i40e_aq_str(hw, aq_status), vsi_name,
2300                                              vsi->type);
2301                 }
2302         }
2303 }
2304
2305 /**
2306  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2307  * @vsi: pointer to the VSI
2308  * @vsi_name: the VSI name
2309  * @f: filter data
2310  *
2311  * This function sets or clears the promiscuous broadcast flags for VLAN
2312  * filters in order to properly receive broadcast frames. Assumes that only
2313  * broadcast filters are passed.
2314  *
2315  * Returns status indicating success or failure;
2316  **/
2317 static i40e_status
2318 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2319                           struct i40e_mac_filter *f)
2320 {
2321         bool enable = f->state == I40E_FILTER_NEW;
2322         struct i40e_hw *hw = &vsi->back->hw;
2323         i40e_status aq_ret;
2324
2325         if (f->vlan == I40E_VLAN_ANY) {
2326                 aq_ret = i40e_aq_set_vsi_broadcast(hw,
2327                                                    vsi->seid,
2328                                                    enable,
2329                                                    NULL);
2330         } else {
2331                 aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2332                                                             vsi->seid,
2333                                                             enable,
2334                                                             f->vlan,
2335                                                             NULL);
2336         }
2337
2338         if (aq_ret) {
2339                 set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2340                 dev_warn(&vsi->back->pdev->dev,
2341                          "Error %s, forcing overflow promiscuous on %s\n",
2342                          i40e_aq_str(hw, hw->aq.asq_last_status),
2343                          vsi_name);
2344         }
2345
2346         return aq_ret;
2347 }
2348
2349 /**
2350  * i40e_set_promiscuous - set promiscuous mode
2351  * @pf: board private structure
2352  * @promisc: promisc on or off
2353  *
2354  * There are different ways of setting promiscuous mode on a PF depending on
2355  * what state/environment we're in.  This identifies and sets it appropriately.
2356  * Returns 0 on success.
2357  **/
2358 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2359 {
2360         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2361         struct i40e_hw *hw = &pf->hw;
2362         i40e_status aq_ret;
2363
2364         if (vsi->type == I40E_VSI_MAIN &&
2365             pf->lan_veb != I40E_NO_VEB &&
2366             !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2367                 /* set defport ON for Main VSI instead of true promisc
2368                  * this way we will get all unicast/multicast and VLAN
2369                  * promisc behavior but will not get VF or VMDq traffic
2370                  * replicated on the Main VSI.
2371                  */
2372                 if (promisc)
2373                         aq_ret = i40e_aq_set_default_vsi(hw,
2374                                                          vsi->seid,
2375                                                          NULL);
2376                 else
2377                         aq_ret = i40e_aq_clear_default_vsi(hw,
2378                                                            vsi->seid,
2379                                                            NULL);
2380                 if (aq_ret) {
2381                         dev_info(&pf->pdev->dev,
2382                                  "Set default VSI failed, err %s, aq_err %s\n",
2383                                  i40e_stat_str(hw, aq_ret),
2384                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2385                 }
2386         } else {
2387                 aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2388                                                   hw,
2389                                                   vsi->seid,
2390                                                   promisc, NULL,
2391                                                   true);
2392                 if (aq_ret) {
2393                         dev_info(&pf->pdev->dev,
2394                                  "set unicast promisc failed, err %s, aq_err %s\n",
2395                                  i40e_stat_str(hw, aq_ret),
2396                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2397                 }
2398                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2399                                                   hw,
2400                                                   vsi->seid,
2401                                                   promisc, NULL);
2402                 if (aq_ret) {
2403                         dev_info(&pf->pdev->dev,
2404                                  "set multicast promisc failed, err %s, aq_err %s\n",
2405                                  i40e_stat_str(hw, aq_ret),
2406                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2407                 }
2408         }
2409
2410         if (!aq_ret)
2411                 pf->cur_promisc = promisc;
2412
2413         return aq_ret;
2414 }
2415
2416 /**
2417  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2418  * @vsi: ptr to the VSI
2419  *
2420  * Push any outstanding VSI filter changes through the AdminQ.
2421  *
2422  * Returns 0 or error value
2423  **/
2424 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2425 {
2426         struct hlist_head tmp_add_list, tmp_del_list;
2427         struct i40e_mac_filter *f;
2428         struct i40e_new_mac_filter *new, *add_head = NULL;
2429         struct i40e_hw *hw = &vsi->back->hw;
2430         bool old_overflow, new_overflow;
2431         unsigned int failed_filters = 0;
2432         unsigned int vlan_filters = 0;
2433         char vsi_name[16] = "PF";
2434         int filter_list_len = 0;
2435         i40e_status aq_ret = 0;
2436         u32 changed_flags = 0;
2437         struct hlist_node *h;
2438         struct i40e_pf *pf;
2439         int num_add = 0;
2440         int num_del = 0;
2441         int retval = 0;
2442         u16 cmd_flags;
2443         int list_size;
2444         int bkt;
2445
2446         /* empty array typed pointers, kcalloc later */
2447         struct i40e_aqc_add_macvlan_element_data *add_list;
2448         struct i40e_aqc_remove_macvlan_element_data *del_list;
2449
2450         while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2451                 usleep_range(1000, 2000);
2452         pf = vsi->back;
2453
2454         old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2455
2456         if (vsi->netdev) {
2457                 changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2458                 vsi->current_netdev_flags = vsi->netdev->flags;
2459         }
2460
2461         INIT_HLIST_HEAD(&tmp_add_list);
2462         INIT_HLIST_HEAD(&tmp_del_list);
2463
2464         if (vsi->type == I40E_VSI_SRIOV)
2465                 snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2466         else if (vsi->type != I40E_VSI_MAIN)
2467                 snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2468
2469         if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2470                 vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2471
2472                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2473                 /* Create a list of filters to delete. */
2474                 hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2475                         if (f->state == I40E_FILTER_REMOVE) {
2476                                 /* Move the element into temporary del_list */
2477                                 hash_del(&f->hlist);
2478                                 hlist_add_head(&f->hlist, &tmp_del_list);
2479
2480                                 /* Avoid counting removed filters */
2481                                 continue;
2482                         }
2483                         if (f->state == I40E_FILTER_NEW) {
2484                                 /* Create a temporary i40e_new_mac_filter */
2485                                 new = kzalloc(sizeof(*new), GFP_ATOMIC);
2486                                 if (!new)
2487                                         goto err_no_memory_locked;
2488
2489                                 /* Store pointer to the real filter */
2490                                 new->f = f;
2491                                 new->state = f->state;
2492
2493                                 /* Add it to the hash list */
2494                                 hlist_add_head(&new->hlist, &tmp_add_list);
2495                         }
2496
2497                         /* Count the number of active (current and new) VLAN
2498                          * filters we have now. Does not count filters which
2499                          * are marked for deletion.
2500                          */
2501                         if (f->vlan > 0)
2502                                 vlan_filters++;
2503                 }
2504
2505                 retval = i40e_correct_mac_vlan_filters(vsi,
2506                                                        &tmp_add_list,
2507                                                        &tmp_del_list,
2508                                                        vlan_filters);
2509
2510                 hlist_for_each_entry(new, &tmp_add_list, hlist)
2511                         netdev_hw_addr_refcnt(new->f, vsi->netdev, 1);
2512
2513                 if (retval)
2514                         goto err_no_memory_locked;
2515
2516                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2517         }
2518
2519         /* Now process 'del_list' outside the lock */
2520         if (!hlist_empty(&tmp_del_list)) {
2521                 filter_list_len = hw->aq.asq_buf_size /
2522                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2523                 list_size = filter_list_len *
2524                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2525                 del_list = kzalloc(list_size, GFP_ATOMIC);
2526                 if (!del_list)
2527                         goto err_no_memory;
2528
2529                 hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2530                         cmd_flags = 0;
2531
2532                         /* handle broadcast filters by updating the broadcast
2533                          * promiscuous flag and release filter list.
2534                          */
2535                         if (is_broadcast_ether_addr(f->macaddr)) {
2536                                 i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2537
2538                                 hlist_del(&f->hlist);
2539                                 kfree(f);
2540                                 continue;
2541                         }
2542
2543                         /* add to delete list */
2544                         ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2545                         if (f->vlan == I40E_VLAN_ANY) {
2546                                 del_list[num_del].vlan_tag = 0;
2547                                 cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2548                         } else {
2549                                 del_list[num_del].vlan_tag =
2550                                         cpu_to_le16((u16)(f->vlan));
2551                         }
2552
2553                         cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2554                         del_list[num_del].flags = cmd_flags;
2555                         num_del++;
2556
2557                         /* flush a full buffer */
2558                         if (num_del == filter_list_len) {
2559                                 i40e_aqc_del_filters(vsi, vsi_name, del_list,
2560                                                      num_del, &retval);
2561                                 memset(del_list, 0, list_size);
2562                                 num_del = 0;
2563                         }
2564                         /* Release memory for MAC filter entries which were
2565                          * synced up with HW.
2566                          */
2567                         hlist_del(&f->hlist);
2568                         kfree(f);
2569                 }
2570
2571                 if (num_del) {
2572                         i40e_aqc_del_filters(vsi, vsi_name, del_list,
2573                                              num_del, &retval);
2574                 }
2575
2576                 kfree(del_list);
2577                 del_list = NULL;
2578         }
2579
2580         if (!hlist_empty(&tmp_add_list)) {
2581                 /* Do all the adds now. */
2582                 filter_list_len = hw->aq.asq_buf_size /
2583                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2584                 list_size = filter_list_len *
2585                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2586                 add_list = kzalloc(list_size, GFP_ATOMIC);
2587                 if (!add_list)
2588                         goto err_no_memory;
2589
2590                 num_add = 0;
2591                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2592                         /* handle broadcast filters by updating the broadcast
2593                          * promiscuous flag instead of adding a MAC filter.
2594                          */
2595                         if (is_broadcast_ether_addr(new->f->macaddr)) {
2596                                 if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2597                                                               new->f))
2598                                         new->state = I40E_FILTER_FAILED;
2599                                 else
2600                                         new->state = I40E_FILTER_ACTIVE;
2601                                 continue;
2602                         }
2603
2604                         /* add to add array */
2605                         if (num_add == 0)
2606                                 add_head = new;
2607                         cmd_flags = 0;
2608                         ether_addr_copy(add_list[num_add].mac_addr,
2609                                         new->f->macaddr);
2610                         if (new->f->vlan == I40E_VLAN_ANY) {
2611                                 add_list[num_add].vlan_tag = 0;
2612                                 cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2613                         } else {
2614                                 add_list[num_add].vlan_tag =
2615                                         cpu_to_le16((u16)(new->f->vlan));
2616                         }
2617                         add_list[num_add].queue_number = 0;
2618                         /* set invalid match method for later detection */
2619                         add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2620                         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2621                         add_list[num_add].flags = cpu_to_le16(cmd_flags);
2622                         num_add++;
2623
2624                         /* flush a full buffer */
2625                         if (num_add == filter_list_len) {
2626                                 i40e_aqc_add_filters(vsi, vsi_name, add_list,
2627                                                      add_head, num_add);
2628                                 memset(add_list, 0, list_size);
2629                                 num_add = 0;
2630                         }
2631                 }
2632                 if (num_add) {
2633                         i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2634                                              num_add);
2635                 }
2636                 /* Now move all of the filters from the temp add list back to
2637                  * the VSI's list.
2638                  */
2639                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2640                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2641                         /* Only update the state if we're still NEW */
2642                         if (new->f->state == I40E_FILTER_NEW)
2643                                 new->f->state = new->state;
2644                         hlist_del(&new->hlist);
2645                         netdev_hw_addr_refcnt(new->f, vsi->netdev, -1);
2646                         kfree(new);
2647                 }
2648                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2649                 kfree(add_list);
2650                 add_list = NULL;
2651         }
2652
2653         /* Determine the number of active and failed filters. */
2654         spin_lock_bh(&vsi->mac_filter_hash_lock);
2655         vsi->active_filters = 0;
2656         hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2657                 if (f->state == I40E_FILTER_ACTIVE)
2658                         vsi->active_filters++;
2659                 else if (f->state == I40E_FILTER_FAILED)
2660                         failed_filters++;
2661         }
2662         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2663
2664         /* Check if we are able to exit overflow promiscuous mode. We can
2665          * safely exit if we didn't just enter, we no longer have any failed
2666          * filters, and we have reduced filters below the threshold value.
2667          */
2668         if (old_overflow && !failed_filters &&
2669             vsi->active_filters < vsi->promisc_threshold) {
2670                 dev_info(&pf->pdev->dev,
2671                          "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2672                          vsi_name);
2673                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2674                 vsi->promisc_threshold = 0;
2675         }
2676
2677         /* if the VF is not trusted do not do promisc */
2678         if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2679                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2680                 goto out;
2681         }
2682
2683         new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2684
2685         /* If we are entering overflow promiscuous, we need to calculate a new
2686          * threshold for when we are safe to exit
2687          */
2688         if (!old_overflow && new_overflow)
2689                 vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2690
2691         /* check for changes in promiscuous modes */
2692         if (changed_flags & IFF_ALLMULTI) {
2693                 bool cur_multipromisc;
2694
2695                 cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2696                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2697                                                                vsi->seid,
2698                                                                cur_multipromisc,
2699                                                                NULL);
2700                 if (aq_ret) {
2701                         retval = i40e_aq_rc_to_posix(aq_ret,
2702                                                      hw->aq.asq_last_status);
2703                         dev_info(&pf->pdev->dev,
2704                                  "set multi promisc failed on %s, err %s aq_err %s\n",
2705                                  vsi_name,
2706                                  i40e_stat_str(hw, aq_ret),
2707                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2708                 } else {
2709                         dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2710                                  cur_multipromisc ? "entering" : "leaving");
2711                 }
2712         }
2713
2714         if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2715                 bool cur_promisc;
2716
2717                 cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2718                                new_overflow);
2719                 aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2720                 if (aq_ret) {
2721                         retval = i40e_aq_rc_to_posix(aq_ret,
2722                                                      hw->aq.asq_last_status);
2723                         dev_info(&pf->pdev->dev,
2724                                  "Setting promiscuous %s failed on %s, err %s aq_err %s\n",
2725                                  cur_promisc ? "on" : "off",
2726                                  vsi_name,
2727                                  i40e_stat_str(hw, aq_ret),
2728                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2729                 }
2730         }
2731 out:
2732         /* if something went wrong then set the changed flag so we try again */
2733         if (retval)
2734                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2735
2736         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2737         return retval;
2738
2739 err_no_memory:
2740         /* Restore elements on the temporary add and delete lists */
2741         spin_lock_bh(&vsi->mac_filter_hash_lock);
2742 err_no_memory_locked:
2743         i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2744         i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2745         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2746
2747         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2748         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2749         return -ENOMEM;
2750 }
2751
2752 /**
2753  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2754  * @pf: board private structure
2755  **/
2756 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2757 {
2758         int v;
2759
2760         if (!pf)
2761                 return;
2762         if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2763                 return;
2764         if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2765                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2766                 return;
2767         }
2768
2769         for (v = 0; v < pf->num_alloc_vsi; v++) {
2770                 if (pf->vsi[v] &&
2771                     (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED) &&
2772                     !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2773                         int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2774
2775                         if (ret) {
2776                                 /* come back and try again later */
2777                                 set_bit(__I40E_MACVLAN_SYNC_PENDING,
2778                                         pf->state);
2779                                 break;
2780                         }
2781                 }
2782         }
2783 }
2784
2785 /**
2786  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2787  * @vsi: the vsi
2788  **/
2789 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2790 {
2791         if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2792                 return I40E_RXBUFFER_2048;
2793         else
2794                 return I40E_RXBUFFER_3072;
2795 }
2796
2797 /**
2798  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2799  * @netdev: network interface device structure
2800  * @new_mtu: new value for maximum frame size
2801  *
2802  * Returns 0 on success, negative on failure
2803  **/
2804 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2805 {
2806         struct i40e_netdev_priv *np = netdev_priv(netdev);
2807         struct i40e_vsi *vsi = np->vsi;
2808         struct i40e_pf *pf = vsi->back;
2809
2810         if (i40e_enabled_xdp_vsi(vsi)) {
2811                 int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2812
2813                 if (frame_size > i40e_max_xdp_frame_size(vsi))
2814                         return -EINVAL;
2815         }
2816
2817         netdev_dbg(netdev, "changing MTU from %d to %d\n",
2818                    netdev->mtu, new_mtu);
2819         netdev->mtu = new_mtu;
2820         if (netif_running(netdev))
2821                 i40e_vsi_reinit_locked(vsi);
2822         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2823         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2824         return 0;
2825 }
2826
2827 /**
2828  * i40e_ioctl - Access the hwtstamp interface
2829  * @netdev: network interface device structure
2830  * @ifr: interface request data
2831  * @cmd: ioctl command
2832  **/
2833 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2834 {
2835         struct i40e_netdev_priv *np = netdev_priv(netdev);
2836         struct i40e_pf *pf = np->vsi->back;
2837
2838         switch (cmd) {
2839         case SIOCGHWTSTAMP:
2840                 return i40e_ptp_get_ts_config(pf, ifr);
2841         case SIOCSHWTSTAMP:
2842                 return i40e_ptp_set_ts_config(pf, ifr);
2843         default:
2844                 return -EOPNOTSUPP;
2845         }
2846 }
2847
2848 /**
2849  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2850  * @vsi: the vsi being adjusted
2851  **/
2852 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2853 {
2854         struct i40e_vsi_context ctxt;
2855         i40e_status ret;
2856
2857         /* Don't modify stripping options if a port VLAN is active */
2858         if (vsi->info.pvid)
2859                 return;
2860
2861         if ((vsi->info.valid_sections &
2862              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2863             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2864                 return;  /* already enabled */
2865
2866         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2867         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2868                                     I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2869
2870         ctxt.seid = vsi->seid;
2871         ctxt.info = vsi->info;
2872         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2873         if (ret) {
2874                 dev_info(&vsi->back->pdev->dev,
2875                          "update vlan stripping failed, err %s aq_err %s\n",
2876                          i40e_stat_str(&vsi->back->hw, ret),
2877                          i40e_aq_str(&vsi->back->hw,
2878                                      vsi->back->hw.aq.asq_last_status));
2879         }
2880 }
2881
2882 /**
2883  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2884  * @vsi: the vsi being adjusted
2885  **/
2886 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2887 {
2888         struct i40e_vsi_context ctxt;
2889         i40e_status ret;
2890
2891         /* Don't modify stripping options if a port VLAN is active */
2892         if (vsi->info.pvid)
2893                 return;
2894
2895         if ((vsi->info.valid_sections &
2896              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2897             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
2898              I40E_AQ_VSI_PVLAN_EMOD_MASK))
2899                 return;  /* already disabled */
2900
2901         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2902         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2903                                     I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2904
2905         ctxt.seid = vsi->seid;
2906         ctxt.info = vsi->info;
2907         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2908         if (ret) {
2909                 dev_info(&vsi->back->pdev->dev,
2910                          "update vlan stripping failed, err %s aq_err %s\n",
2911                          i40e_stat_str(&vsi->back->hw, ret),
2912                          i40e_aq_str(&vsi->back->hw,
2913                                      vsi->back->hw.aq.asq_last_status));
2914         }
2915 }
2916
2917 /**
2918  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
2919  * @vsi: the vsi being configured
2920  * @vid: vlan id to be added (0 = untagged only , -1 = any)
2921  *
2922  * This is a helper function for adding a new MAC/VLAN filter with the
2923  * specified VLAN for each existing MAC address already in the hash table.
2924  * This function does *not* perform any accounting to update filters based on
2925  * VLAN mode.
2926  *
2927  * NOTE: this function expects to be called while under the
2928  * mac_filter_hash_lock
2929  **/
2930 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2931 {
2932         struct i40e_mac_filter *f, *add_f;
2933         struct hlist_node *h;
2934         int bkt;
2935
2936         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2937                 if (f->state == I40E_FILTER_REMOVE)
2938                         continue;
2939                 add_f = i40e_add_filter(vsi, f->macaddr, vid);
2940                 if (!add_f) {
2941                         dev_info(&vsi->back->pdev->dev,
2942                                  "Could not add vlan filter %d for %pM\n",
2943                                  vid, f->macaddr);
2944                         return -ENOMEM;
2945                 }
2946         }
2947
2948         return 0;
2949 }
2950
2951 /**
2952  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
2953  * @vsi: the VSI being configured
2954  * @vid: VLAN id to be added
2955  **/
2956 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
2957 {
2958         int err;
2959
2960         if (vsi->info.pvid)
2961                 return -EINVAL;
2962
2963         /* The network stack will attempt to add VID=0, with the intention to
2964          * receive priority tagged packets with a VLAN of 0. Our HW receives
2965          * these packets by default when configured to receive untagged
2966          * packets, so we don't need to add a filter for this case.
2967          * Additionally, HW interprets adding a VID=0 filter as meaning to
2968          * receive *only* tagged traffic and stops receiving untagged traffic.
2969          * Thus, we do not want to actually add a filter for VID=0
2970          */
2971         if (!vid)
2972                 return 0;
2973
2974         /* Locked once because all functions invoked below iterates list*/
2975         spin_lock_bh(&vsi->mac_filter_hash_lock);
2976         err = i40e_add_vlan_all_mac(vsi, vid);
2977         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2978         if (err)
2979                 return err;
2980
2981         /* schedule our worker thread which will take care of
2982          * applying the new filter changes
2983          */
2984         i40e_service_event_schedule(vsi->back);
2985         return 0;
2986 }
2987
2988 /**
2989  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
2990  * @vsi: the vsi being configured
2991  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
2992  *
2993  * This function should be used to remove all VLAN filters which match the
2994  * given VID. It does not schedule the service event and does not take the
2995  * mac_filter_hash_lock so it may be combined with other operations under
2996  * a single invocation of the mac_filter_hash_lock.
2997  *
2998  * NOTE: this function expects to be called while under the
2999  * mac_filter_hash_lock
3000  */
3001 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
3002 {
3003         struct i40e_mac_filter *f;
3004         struct hlist_node *h;
3005         int bkt;
3006
3007         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
3008                 if (f->vlan == vid)
3009                         __i40e_del_filter(vsi, f);
3010         }
3011 }
3012
3013 /**
3014  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
3015  * @vsi: the VSI being configured
3016  * @vid: VLAN id to be removed
3017  **/
3018 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
3019 {
3020         if (!vid || vsi->info.pvid)
3021                 return;
3022
3023         spin_lock_bh(&vsi->mac_filter_hash_lock);
3024         i40e_rm_vlan_all_mac(vsi, vid);
3025         spin_unlock_bh(&vsi->mac_filter_hash_lock);
3026
3027         /* schedule our worker thread which will take care of
3028          * applying the new filter changes
3029          */
3030         i40e_service_event_schedule(vsi->back);
3031 }
3032
3033 /**
3034  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
3035  * @netdev: network interface to be adjusted
3036  * @proto: unused protocol value
3037  * @vid: vlan id to be added
3038  *
3039  * net_device_ops implementation for adding vlan ids
3040  **/
3041 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
3042                                 __always_unused __be16 proto, u16 vid)
3043 {
3044         struct i40e_netdev_priv *np = netdev_priv(netdev);
3045         struct i40e_vsi *vsi = np->vsi;
3046         int ret = 0;
3047
3048         if (vid >= VLAN_N_VID)
3049                 return -EINVAL;
3050
3051         ret = i40e_vsi_add_vlan(vsi, vid);
3052         if (!ret)
3053                 set_bit(vid, vsi->active_vlans);
3054
3055         return ret;
3056 }
3057
3058 /**
3059  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
3060  * @netdev: network interface to be adjusted
3061  * @proto: unused protocol value
3062  * @vid: vlan id to be added
3063  **/
3064 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
3065                                     __always_unused __be16 proto, u16 vid)
3066 {
3067         struct i40e_netdev_priv *np = netdev_priv(netdev);
3068         struct i40e_vsi *vsi = np->vsi;
3069
3070         if (vid >= VLAN_N_VID)
3071                 return;
3072         set_bit(vid, vsi->active_vlans);
3073 }
3074
3075 /**
3076  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
3077  * @netdev: network interface to be adjusted
3078  * @proto: unused protocol value
3079  * @vid: vlan id to be removed
3080  *
3081  * net_device_ops implementation for removing vlan ids
3082  **/
3083 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
3084                                  __always_unused __be16 proto, u16 vid)
3085 {
3086         struct i40e_netdev_priv *np = netdev_priv(netdev);
3087         struct i40e_vsi *vsi = np->vsi;
3088
3089         /* return code is ignored as there is nothing a user
3090          * can do about failure to remove and a log message was
3091          * already printed from the other function
3092          */
3093         i40e_vsi_kill_vlan(vsi, vid);
3094
3095         clear_bit(vid, vsi->active_vlans);
3096
3097         return 0;
3098 }
3099
3100 /**
3101  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
3102  * @vsi: the vsi being brought back up
3103  **/
3104 static void i40e_restore_vlan(struct i40e_vsi *vsi)
3105 {
3106         u16 vid;
3107
3108         if (!vsi->netdev)
3109                 return;
3110
3111         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
3112                 i40e_vlan_stripping_enable(vsi);
3113         else
3114                 i40e_vlan_stripping_disable(vsi);
3115
3116         for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
3117                 i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
3118                                         vid);
3119 }
3120
3121 /**
3122  * i40e_vsi_add_pvid - Add pvid for the VSI
3123  * @vsi: the vsi being adjusted
3124  * @vid: the vlan id to set as a PVID
3125  **/
3126 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
3127 {
3128         struct i40e_vsi_context ctxt;
3129         i40e_status ret;
3130
3131         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
3132         vsi->info.pvid = cpu_to_le16(vid);
3133         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
3134                                     I40E_AQ_VSI_PVLAN_INSERT_PVID |
3135                                     I40E_AQ_VSI_PVLAN_EMOD_STR;
3136
3137         ctxt.seid = vsi->seid;
3138         ctxt.info = vsi->info;
3139         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
3140         if (ret) {
3141                 dev_info(&vsi->back->pdev->dev,
3142                          "add pvid failed, err %s aq_err %s\n",
3143                          i40e_stat_str(&vsi->back->hw, ret),
3144                          i40e_aq_str(&vsi->back->hw,
3145                                      vsi->back->hw.aq.asq_last_status));
3146                 return -ENOENT;
3147         }
3148
3149         return 0;
3150 }
3151
3152 /**
3153  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3154  * @vsi: the vsi being adjusted
3155  *
3156  * Just use the vlan_rx_register() service to put it back to normal
3157  **/
3158 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3159 {
3160         vsi->info.pvid = 0;
3161
3162         i40e_vlan_stripping_disable(vsi);
3163 }
3164
3165 /**
3166  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3167  * @vsi: ptr to the VSI
3168  *
3169  * If this function returns with an error, then it's possible one or
3170  * more of the rings is populated (while the rest are not).  It is the
3171  * callers duty to clean those orphaned rings.
3172  *
3173  * Return 0 on success, negative on failure
3174  **/
3175 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3176 {
3177         int i, err = 0;
3178
3179         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3180                 err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3181
3182         if (!i40e_enabled_xdp_vsi(vsi))
3183                 return err;
3184
3185         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3186                 err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3187
3188         return err;
3189 }
3190
3191 /**
3192  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3193  * @vsi: ptr to the VSI
3194  *
3195  * Free VSI's transmit software resources
3196  **/
3197 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3198 {
3199         int i;
3200
3201         if (vsi->tx_rings) {
3202                 for (i = 0; i < vsi->num_queue_pairs; i++)
3203                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3204                                 i40e_free_tx_resources(vsi->tx_rings[i]);
3205         }
3206
3207         if (vsi->xdp_rings) {
3208                 for (i = 0; i < vsi->num_queue_pairs; i++)
3209                         if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3210                                 i40e_free_tx_resources(vsi->xdp_rings[i]);
3211         }
3212 }
3213
3214 /**
3215  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3216  * @vsi: ptr to the VSI
3217  *
3218  * If this function returns with an error, then it's possible one or
3219  * more of the rings is populated (while the rest are not).  It is the
3220  * callers duty to clean those orphaned rings.
3221  *
3222  * Return 0 on success, negative on failure
3223  **/
3224 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3225 {
3226         int i, err = 0;
3227
3228         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3229                 err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3230         return err;
3231 }
3232
3233 /**
3234  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3235  * @vsi: ptr to the VSI
3236  *
3237  * Free all receive software resources
3238  **/
3239 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3240 {
3241         int i;
3242
3243         if (!vsi->rx_rings)
3244                 return;
3245
3246         for (i = 0; i < vsi->num_queue_pairs; i++)
3247                 if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3248                         i40e_free_rx_resources(vsi->rx_rings[i]);
3249 }
3250
3251 /**
3252  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3253  * @ring: The Tx ring to configure
3254  *
3255  * This enables/disables XPS for a given Tx descriptor ring
3256  * based on the TCs enabled for the VSI that ring belongs to.
3257  **/
3258 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3259 {
3260         int cpu;
3261
3262         if (!ring->q_vector || !ring->netdev || ring->ch)
3263                 return;
3264
3265         /* We only initialize XPS once, so as not to overwrite user settings */
3266         if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3267                 return;
3268
3269         cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3270         netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3271                             ring->queue_index);
3272 }
3273
3274 /**
3275  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3276  * @ring: The Tx or Rx ring
3277  *
3278  * Returns the AF_XDP buffer pool or NULL.
3279  **/
3280 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3281 {
3282         bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3283         int qid = ring->queue_index;
3284
3285         if (ring_is_xdp(ring))
3286                 qid -= ring->vsi->alloc_queue_pairs;
3287
3288         if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3289                 return NULL;
3290
3291         return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3292 }
3293
3294 /**
3295  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3296  * @ring: The Tx ring to configure
3297  *
3298  * Configure the Tx descriptor ring in the HMC context.
3299  **/
3300 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3301 {
3302         struct i40e_vsi *vsi = ring->vsi;
3303         u16 pf_q = vsi->base_queue + ring->queue_index;
3304         struct i40e_hw *hw = &vsi->back->hw;
3305         struct i40e_hmc_obj_txq tx_ctx;
3306         i40e_status err = 0;
3307         u32 qtx_ctl = 0;
3308
3309         if (ring_is_xdp(ring))
3310                 ring->xsk_pool = i40e_xsk_pool(ring);
3311
3312         /* some ATR related tx ring init */
3313         if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3314                 ring->atr_sample_rate = vsi->back->atr_sample_rate;
3315                 ring->atr_count = 0;
3316         } else {
3317                 ring->atr_sample_rate = 0;
3318         }
3319
3320         /* configure XPS */
3321         i40e_config_xps_tx_ring(ring);
3322
3323         /* clear the context structure first */
3324         memset(&tx_ctx, 0, sizeof(tx_ctx));
3325
3326         tx_ctx.new_context = 1;
3327         tx_ctx.base = (ring->dma / 128);
3328         tx_ctx.qlen = ring->count;
3329         tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3330                                                I40E_FLAG_FD_ATR_ENABLED));
3331         tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3332         /* FDIR VSI tx ring can still use RS bit and writebacks */
3333         if (vsi->type != I40E_VSI_FDIR)
3334                 tx_ctx.head_wb_ena = 1;
3335         tx_ctx.head_wb_addr = ring->dma +
3336                               (ring->count * sizeof(struct i40e_tx_desc));
3337
3338         /* As part of VSI creation/update, FW allocates certain
3339          * Tx arbitration queue sets for each TC enabled for
3340          * the VSI. The FW returns the handles to these queue
3341          * sets as part of the response buffer to Add VSI,
3342          * Update VSI, etc. AQ commands. It is expected that
3343          * these queue set handles be associated with the Tx
3344          * queues by the driver as part of the TX queue context
3345          * initialization. This has to be done regardless of
3346          * DCB as by default everything is mapped to TC0.
3347          */
3348
3349         if (ring->ch)
3350                 tx_ctx.rdylist =
3351                         le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3352
3353         else
3354                 tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3355
3356         tx_ctx.rdylist_act = 0;
3357
3358         /* clear the context in the HMC */
3359         err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3360         if (err) {
3361                 dev_info(&vsi->back->pdev->dev,
3362                          "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3363                          ring->queue_index, pf_q, err);
3364                 return -ENOMEM;
3365         }
3366
3367         /* set the context in the HMC */
3368         err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3369         if (err) {
3370                 dev_info(&vsi->back->pdev->dev,
3371                          "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3372                          ring->queue_index, pf_q, err);
3373                 return -ENOMEM;
3374         }
3375
3376         /* Now associate this queue with this PCI function */
3377         if (ring->ch) {
3378                 if (ring->ch->type == I40E_VSI_VMDQ2)
3379                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3380                 else
3381                         return -EINVAL;
3382
3383                 qtx_ctl |= (ring->ch->vsi_number <<
3384                             I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3385                             I40E_QTX_CTL_VFVM_INDX_MASK;
3386         } else {
3387                 if (vsi->type == I40E_VSI_VMDQ2) {
3388                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3389                         qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3390                                     I40E_QTX_CTL_VFVM_INDX_MASK;
3391                 } else {
3392                         qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3393                 }
3394         }
3395
3396         qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3397                     I40E_QTX_CTL_PF_INDX_MASK);
3398         wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3399         i40e_flush(hw);
3400
3401         /* cache tail off for easier writes later */
3402         ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3403
3404         return 0;
3405 }
3406
3407 /**
3408  * i40e_rx_offset - Return expected offset into page to access data
3409  * @rx_ring: Ring we are requesting offset of
3410  *
3411  * Returns the offset value for ring into the data buffer.
3412  */
3413 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3414 {
3415         return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3416 }
3417
3418 /**
3419  * i40e_configure_rx_ring - Configure a receive ring context
3420  * @ring: The Rx ring to configure
3421  *
3422  * Configure the Rx descriptor ring in the HMC context.
3423  **/
3424 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3425 {
3426         struct i40e_vsi *vsi = ring->vsi;
3427         u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3428         u16 pf_q = vsi->base_queue + ring->queue_index;
3429         struct i40e_hw *hw = &vsi->back->hw;
3430         struct i40e_hmc_obj_rxq rx_ctx;
3431         i40e_status err = 0;
3432         bool ok;
3433         int ret;
3434
3435         bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3436
3437         /* clear the context structure first */
3438         memset(&rx_ctx, 0, sizeof(rx_ctx));
3439
3440         if (ring->vsi->type == I40E_VSI_MAIN)
3441                 xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3442
3443         kfree(ring->rx_bi);
3444         ring->xsk_pool = i40e_xsk_pool(ring);
3445         if (ring->xsk_pool) {
3446                 ret = i40e_alloc_rx_bi_zc(ring);
3447                 if (ret)
3448                         return ret;
3449                 ring->rx_buf_len =
3450                   xsk_pool_get_rx_frame_size(ring->xsk_pool);
3451                 /* For AF_XDP ZC, we disallow packets to span on
3452                  * multiple buffers, thus letting us skip that
3453                  * handling in the fast-path.
3454                  */
3455                 chain_len = 1;
3456                 ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3457                                                  MEM_TYPE_XSK_BUFF_POOL,
3458                                                  NULL);
3459                 if (ret)
3460                         return ret;
3461                 dev_info(&vsi->back->pdev->dev,
3462                          "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3463                          ring->queue_index);
3464
3465         } else {
3466                 ret = i40e_alloc_rx_bi(ring);
3467                 if (ret)
3468                         return ret;
3469                 ring->rx_buf_len = vsi->rx_buf_len;
3470                 if (ring->vsi->type == I40E_VSI_MAIN) {
3471                         ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3472                                                          MEM_TYPE_PAGE_SHARED,
3473                                                          NULL);
3474                         if (ret)
3475                                 return ret;
3476                 }
3477         }
3478
3479         rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3480                                     BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3481
3482         rx_ctx.base = (ring->dma / 128);
3483         rx_ctx.qlen = ring->count;
3484
3485         /* use 16 byte descriptors */
3486         rx_ctx.dsize = 0;
3487
3488         /* descriptor type is always zero
3489          * rx_ctx.dtype = 0;
3490          */
3491         rx_ctx.hsplit_0 = 0;
3492
3493         rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3494         if (hw->revision_id == 0)
3495                 rx_ctx.lrxqthresh = 0;
3496         else
3497                 rx_ctx.lrxqthresh = 1;
3498         rx_ctx.crcstrip = 1;
3499         rx_ctx.l2tsel = 1;
3500         /* this controls whether VLAN is stripped from inner headers */
3501         rx_ctx.showiv = 0;
3502         /* set the prefena field to 1 because the manual says to */
3503         rx_ctx.prefena = 1;
3504
3505         /* clear the context in the HMC */
3506         err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3507         if (err) {
3508                 dev_info(&vsi->back->pdev->dev,
3509                          "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3510                          ring->queue_index, pf_q, err);
3511                 return -ENOMEM;
3512         }
3513
3514         /* set the context in the HMC */
3515         err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3516         if (err) {
3517                 dev_info(&vsi->back->pdev->dev,
3518                          "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3519                          ring->queue_index, pf_q, err);
3520                 return -ENOMEM;
3521         }
3522
3523         /* configure Rx buffer alignment */
3524         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3525                 clear_ring_build_skb_enabled(ring);
3526         else
3527                 set_ring_build_skb_enabled(ring);
3528
3529         ring->rx_offset = i40e_rx_offset(ring);
3530
3531         /* cache tail for quicker writes, and clear the reg before use */
3532         ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3533         writel(0, ring->tail);
3534
3535         if (ring->xsk_pool) {
3536                 xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3537                 ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3538         } else {
3539                 ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3540         }
3541         if (!ok) {
3542                 /* Log this in case the user has forgotten to give the kernel
3543                  * any buffers, even later in the application.
3544                  */
3545                 dev_info(&vsi->back->pdev->dev,
3546                          "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3547                          ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3548                          ring->queue_index, pf_q);
3549         }
3550
3551         return 0;
3552 }
3553
3554 /**
3555  * i40e_vsi_configure_tx - Configure the VSI for Tx
3556  * @vsi: VSI structure describing this set of rings and resources
3557  *
3558  * Configure the Tx VSI for operation.
3559  **/
3560 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3561 {
3562         int err = 0;
3563         u16 i;
3564
3565         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3566                 err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3567
3568         if (err || !i40e_enabled_xdp_vsi(vsi))
3569                 return err;
3570
3571         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3572                 err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3573
3574         return err;
3575 }
3576
3577 /**
3578  * i40e_vsi_configure_rx - Configure the VSI for Rx
3579  * @vsi: the VSI being configured
3580  *
3581  * Configure the Rx VSI for operation.
3582  **/
3583 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3584 {
3585         int err = 0;
3586         u16 i;
3587
3588         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3589                 vsi->max_frame = I40E_MAX_RXBUFFER;
3590                 vsi->rx_buf_len = I40E_RXBUFFER_2048;
3591 #if (PAGE_SIZE < 8192)
3592         } else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3593                    (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3594                 vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3595                 vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3596 #endif
3597         } else {
3598                 vsi->max_frame = I40E_MAX_RXBUFFER;
3599                 vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3600                                                        I40E_RXBUFFER_2048;
3601         }
3602
3603         /* set up individual rings */
3604         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3605                 err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3606
3607         return err;
3608 }
3609
3610 /**
3611  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3612  * @vsi: ptr to the VSI
3613  **/
3614 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3615 {
3616         struct i40e_ring *tx_ring, *rx_ring;
3617         u16 qoffset, qcount;
3618         int i, n;
3619
3620         if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3621                 /* Reset the TC information */
3622                 for (i = 0; i < vsi->num_queue_pairs; i++) {
3623                         rx_ring = vsi->rx_rings[i];
3624                         tx_ring = vsi->tx_rings[i];
3625                         rx_ring->dcb_tc = 0;
3626                         tx_ring->dcb_tc = 0;
3627                 }
3628                 return;
3629         }
3630
3631         for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3632                 if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3633                         continue;
3634
3635                 qoffset = vsi->tc_config.tc_info[n].qoffset;
3636                 qcount = vsi->tc_config.tc_info[n].qcount;
3637                 for (i = qoffset; i < (qoffset + qcount); i++) {
3638                         rx_ring = vsi->rx_rings[i];
3639                         tx_ring = vsi->tx_rings[i];
3640                         rx_ring->dcb_tc = n;
3641                         tx_ring->dcb_tc = n;
3642                 }
3643         }
3644 }
3645
3646 /**
3647  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3648  * @vsi: ptr to the VSI
3649  **/
3650 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3651 {
3652         if (vsi->netdev)
3653                 i40e_set_rx_mode(vsi->netdev);
3654 }
3655
3656 /**
3657  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3658  * @pf: Pointer to the targeted PF
3659  *
3660  * Set all flow director counters to 0.
3661  */
3662 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3663 {
3664         pf->fd_tcp4_filter_cnt = 0;
3665         pf->fd_udp4_filter_cnt = 0;
3666         pf->fd_sctp4_filter_cnt = 0;
3667         pf->fd_ip4_filter_cnt = 0;
3668         pf->fd_tcp6_filter_cnt = 0;
3669         pf->fd_udp6_filter_cnt = 0;
3670         pf->fd_sctp6_filter_cnt = 0;
3671         pf->fd_ip6_filter_cnt = 0;
3672 }
3673
3674 /**
3675  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3676  * @vsi: Pointer to the targeted VSI
3677  *
3678  * This function replays the hlist on the hw where all the SB Flow Director
3679  * filters were saved.
3680  **/
3681 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3682 {
3683         struct i40e_fdir_filter *filter;
3684         struct i40e_pf *pf = vsi->back;
3685         struct hlist_node *node;
3686
3687         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3688                 return;
3689
3690         /* Reset FDir counters as we're replaying all existing filters */
3691         i40e_reset_fdir_filter_cnt(pf);
3692
3693         hlist_for_each_entry_safe(filter, node,
3694                                   &pf->fdir_filter_list, fdir_node) {
3695                 i40e_add_del_fdir(vsi, filter, true);
3696         }
3697 }
3698
3699 /**
3700  * i40e_vsi_configure - Set up the VSI for action
3701  * @vsi: the VSI being configured
3702  **/
3703 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3704 {
3705         int err;
3706
3707         i40e_set_vsi_rx_mode(vsi);
3708         i40e_restore_vlan(vsi);
3709         i40e_vsi_config_dcb_rings(vsi);
3710         err = i40e_vsi_configure_tx(vsi);
3711         if (!err)
3712                 err = i40e_vsi_configure_rx(vsi);
3713
3714         return err;
3715 }
3716
3717 /**
3718  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3719  * @vsi: the VSI being configured
3720  **/
3721 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3722 {
3723         bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3724         struct i40e_pf *pf = vsi->back;
3725         struct i40e_hw *hw = &pf->hw;
3726         u16 vector;
3727         int i, q;
3728         u32 qp;
3729
3730         /* The interrupt indexing is offset by 1 in the PFINT_ITRn
3731          * and PFINT_LNKLSTn registers, e.g.:
3732          *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3733          */
3734         qp = vsi->base_queue;
3735         vector = vsi->base_vector;
3736         for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3737                 struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3738
3739                 q_vector->rx.next_update = jiffies + 1;
3740                 q_vector->rx.target_itr =
3741                         ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3742                 wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3743                      q_vector->rx.target_itr >> 1);
3744                 q_vector->rx.current_itr = q_vector->rx.target_itr;
3745
3746                 q_vector->tx.next_update = jiffies + 1;
3747                 q_vector->tx.target_itr =
3748                         ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3749                 wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3750                      q_vector->tx.target_itr >> 1);
3751                 q_vector->tx.current_itr = q_vector->tx.target_itr;
3752
3753                 wr32(hw, I40E_PFINT_RATEN(vector - 1),
3754                      i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3755
3756                 /* Linked list for the queuepairs assigned to this vector */
3757                 wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3758                 for (q = 0; q < q_vector->num_ringpairs; q++) {
3759                         u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3760                         u32 val;
3761
3762                         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3763                               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3764                               (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3765                               (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3766                               (I40E_QUEUE_TYPE_TX <<
3767                                I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3768
3769                         wr32(hw, I40E_QINT_RQCTL(qp), val);
3770
3771                         if (has_xdp) {
3772                                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3773                                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3774                                       (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3775                                       (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3776                                       (I40E_QUEUE_TYPE_TX <<
3777                                        I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3778
3779                                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3780                         }
3781
3782                         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3783                               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3784                               (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3785                               ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3786                               (I40E_QUEUE_TYPE_RX <<
3787                                I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3788
3789                         /* Terminate the linked list */
3790                         if (q == (q_vector->num_ringpairs - 1))
3791                                 val |= (I40E_QUEUE_END_OF_LIST <<
3792                                         I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3793
3794                         wr32(hw, I40E_QINT_TQCTL(qp), val);
3795                         qp++;
3796                 }
3797         }
3798
3799         i40e_flush(hw);
3800 }
3801
3802 /**
3803  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3804  * @pf: pointer to private device data structure
3805  **/
3806 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3807 {
3808         struct i40e_hw *hw = &pf->hw;
3809         u32 val;
3810
3811         /* clear things first */
3812         wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3813         rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3814
3815         val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3816               I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3817               I40E_PFINT_ICR0_ENA_GRST_MASK          |
3818               I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3819               I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3820               I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3821               I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3822               I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3823
3824         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3825                 val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3826
3827         if (pf->flags & I40E_FLAG_PTP)
3828                 val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3829
3830         wr32(hw, I40E_PFINT_ICR0_ENA, val);
3831
3832         /* SW_ITR_IDX = 0, but don't change INTENA */
3833         wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3834                                         I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3835
3836         /* OTHER_ITR_IDX = 0 */
3837         wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3838 }
3839
3840 /**
3841  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3842  * @vsi: the VSI being configured
3843  **/
3844 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3845 {
3846         u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3847         struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3848         struct i40e_pf *pf = vsi->back;
3849         struct i40e_hw *hw = &pf->hw;
3850         u32 val;
3851
3852         /* set the ITR configuration */
3853         q_vector->rx.next_update = jiffies + 1;
3854         q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3855         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
3856         q_vector->rx.current_itr = q_vector->rx.target_itr;
3857         q_vector->tx.next_update = jiffies + 1;
3858         q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3859         wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
3860         q_vector->tx.current_itr = q_vector->tx.target_itr;
3861
3862         i40e_enable_misc_int_causes(pf);
3863
3864         /* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3865         wr32(hw, I40E_PFINT_LNKLST0, 0);
3866
3867         /* Associate the queue pair to the vector and enable the queue int */
3868         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK                   |
3869               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3870               (nextqp      << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3871               (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3872
3873         wr32(hw, I40E_QINT_RQCTL(0), val);
3874
3875         if (i40e_enabled_xdp_vsi(vsi)) {
3876                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                 |
3877                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
3878                       (I40E_QUEUE_TYPE_TX
3879                        << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3880
3881                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3882         }
3883
3884         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                  |
3885               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3886               (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3887
3888         wr32(hw, I40E_QINT_TQCTL(0), val);
3889         i40e_flush(hw);
3890 }
3891
3892 /**
3893  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
3894  * @pf: board private structure
3895  **/
3896 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
3897 {
3898         struct i40e_hw *hw = &pf->hw;
3899
3900         wr32(hw, I40E_PFINT_DYN_CTL0,
3901              I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
3902         i40e_flush(hw);
3903 }
3904
3905 /**
3906  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
3907  * @pf: board private structure
3908  **/
3909 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
3910 {
3911         struct i40e_hw *hw = &pf->hw;
3912         u32 val;
3913
3914         val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
3915               I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
3916               (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
3917
3918         wr32(hw, I40E_PFINT_DYN_CTL0, val);
3919         i40e_flush(hw);
3920 }
3921
3922 /**
3923  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
3924  * @irq: interrupt number
3925  * @data: pointer to a q_vector
3926  **/
3927 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
3928 {
3929         struct i40e_q_vector *q_vector = data;
3930
3931         if (!q_vector->tx.ring && !q_vector->rx.ring)
3932                 return IRQ_HANDLED;
3933
3934         napi_schedule_irqoff(&q_vector->napi);
3935
3936         return IRQ_HANDLED;
3937 }
3938
3939 /**
3940  * i40e_irq_affinity_notify - Callback for affinity changes
3941  * @notify: context as to what irq was changed
3942  * @mask: the new affinity mask
3943  *
3944  * This is a callback function used by the irq_set_affinity_notifier function
3945  * so that we may register to receive changes to the irq affinity masks.
3946  **/
3947 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
3948                                      const cpumask_t *mask)
3949 {
3950         struct i40e_q_vector *q_vector =
3951                 container_of(notify, struct i40e_q_vector, affinity_notify);
3952
3953         cpumask_copy(&q_vector->affinity_mask, mask);
3954 }
3955
3956 /**
3957  * i40e_irq_affinity_release - Callback for affinity notifier release
3958  * @ref: internal core kernel usage
3959  *
3960  * This is a callback function used by the irq_set_affinity_notifier function
3961  * to inform the current notification subscriber that they will no longer
3962  * receive notifications.
3963  **/
3964 static void i40e_irq_affinity_release(struct kref *ref) {}
3965
3966 /**
3967  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
3968  * @vsi: the VSI being configured
3969  * @basename: name for the vector
3970  *
3971  * Allocates MSI-X vectors and requests interrupts from the kernel.
3972  **/
3973 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
3974 {
3975         int q_vectors = vsi->num_q_vectors;
3976         struct i40e_pf *pf = vsi->back;
3977         int base = vsi->base_vector;
3978         int rx_int_idx = 0;
3979         int tx_int_idx = 0;
3980         int vector, err;
3981         int irq_num;
3982         int cpu;
3983
3984         for (vector = 0; vector < q_vectors; vector++) {
3985                 struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
3986
3987                 irq_num = pf->msix_entries[base + vector].vector;
3988
3989                 if (q_vector->tx.ring && q_vector->rx.ring) {
3990                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3991                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
3992                         tx_int_idx++;
3993                 } else if (q_vector->rx.ring) {
3994                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3995                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
3996                 } else if (q_vector->tx.ring) {
3997                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3998                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
3999                 } else {
4000                         /* skip this unused q_vector */
4001                         continue;
4002                 }
4003                 err = request_irq(irq_num,
4004                                   vsi->irq_handler,
4005                                   0,
4006                                   q_vector->name,
4007                                   q_vector);
4008                 if (err) {
4009                         dev_info(&pf->pdev->dev,
4010                                  "MSIX request_irq failed, error: %d\n", err);
4011                         goto free_queue_irqs;
4012                 }
4013
4014                 /* register for affinity change notifications */
4015                 q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
4016                 q_vector->affinity_notify.release = i40e_irq_affinity_release;
4017                 irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
4018                 /* Spread affinity hints out across online CPUs.
4019                  *
4020                  * get_cpu_mask returns a static constant mask with
4021                  * a permanent lifetime so it's ok to pass to
4022                  * irq_update_affinity_hint without making a copy.
4023                  */
4024                 cpu = cpumask_local_spread(q_vector->v_idx, -1);
4025                 irq_update_affinity_hint(irq_num, get_cpu_mask(cpu));
4026         }
4027
4028         vsi->irqs_ready = true;
4029         return 0;
4030
4031 free_queue_irqs:
4032         while (vector) {
4033                 vector--;
4034                 irq_num = pf->msix_entries[base + vector].vector;
4035                 irq_set_affinity_notifier(irq_num, NULL);
4036                 irq_update_affinity_hint(irq_num, NULL);
4037                 free_irq(irq_num, &vsi->q_vectors[vector]);
4038         }
4039         return err;
4040 }
4041
4042 /**
4043  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
4044  * @vsi: the VSI being un-configured
4045  **/
4046 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
4047 {
4048         struct i40e_pf *pf = vsi->back;
4049         struct i40e_hw *hw = &pf->hw;
4050         int base = vsi->base_vector;
4051         int i;
4052
4053         /* disable interrupt causation from each queue */
4054         for (i = 0; i < vsi->num_queue_pairs; i++) {
4055                 u32 val;
4056
4057                 val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
4058                 val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
4059                 wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
4060
4061                 val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
4062                 val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
4063                 wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
4064
4065                 if (!i40e_enabled_xdp_vsi(vsi))
4066                         continue;
4067                 wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
4068         }
4069
4070         /* disable each interrupt */
4071         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4072                 for (i = vsi->base_vector;
4073                      i < (vsi->num_q_vectors + vsi->base_vector); i++)
4074                         wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
4075
4076                 i40e_flush(hw);
4077                 for (i = 0; i < vsi->num_q_vectors; i++)
4078                         synchronize_irq(pf->msix_entries[i + base].vector);
4079         } else {
4080                 /* Legacy and MSI mode - this stops all interrupt handling */
4081                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
4082                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
4083                 i40e_flush(hw);
4084                 synchronize_irq(pf->pdev->irq);
4085         }
4086 }
4087
4088 /**
4089  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
4090  * @vsi: the VSI being configured
4091  **/
4092 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
4093 {
4094         struct i40e_pf *pf = vsi->back;
4095         int i;
4096
4097         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4098                 for (i = 0; i < vsi->num_q_vectors; i++)
4099                         i40e_irq_dynamic_enable(vsi, i);
4100         } else {
4101                 i40e_irq_dynamic_enable_icr0(pf);
4102         }
4103
4104         i40e_flush(&pf->hw);
4105         return 0;
4106 }
4107
4108 /**
4109  * i40e_free_misc_vector - Free the vector that handles non-queue events
4110  * @pf: board private structure
4111  **/
4112 static void i40e_free_misc_vector(struct i40e_pf *pf)
4113 {
4114         /* Disable ICR 0 */
4115         wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
4116         i40e_flush(&pf->hw);
4117
4118         if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4119                 synchronize_irq(pf->msix_entries[0].vector);
4120                 free_irq(pf->msix_entries[0].vector, pf);
4121                 clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
4122         }
4123 }
4124
4125 /**
4126  * i40e_intr - MSI/Legacy and non-queue interrupt handler
4127  * @irq: interrupt number
4128  * @data: pointer to a q_vector
4129  *
4130  * This is the handler used for all MSI/Legacy interrupts, and deals
4131  * with both queue and non-queue interrupts.  This is also used in
4132  * MSIX mode to handle the non-queue interrupts.
4133  **/
4134 static irqreturn_t i40e_intr(int irq, void *data)
4135 {
4136         struct i40e_pf *pf = (struct i40e_pf *)data;
4137         struct i40e_hw *hw = &pf->hw;
4138         irqreturn_t ret = IRQ_NONE;
4139         u32 icr0, icr0_remaining;
4140         u32 val, ena_mask;
4141
4142         icr0 = rd32(hw, I40E_PFINT_ICR0);
4143         ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
4144
4145         /* if sharing a legacy IRQ, we might get called w/o an intr pending */
4146         if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4147                 goto enable_intr;
4148
4149         /* if interrupt but no bits showing, must be SWINT */
4150         if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4151             (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4152                 pf->sw_int_count++;
4153
4154         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4155             (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4156                 ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4157                 dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4158                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4159         }
4160
4161         /* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4162         if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4163                 struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4164                 struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4165
4166                 /* We do not have a way to disarm Queue causes while leaving
4167                  * interrupt enabled for all other causes, ideally
4168                  * interrupt should be disabled while we are in NAPI but
4169                  * this is not a performance path and napi_schedule()
4170                  * can deal with rescheduling.
4171                  */
4172                 if (!test_bit(__I40E_DOWN, pf->state))
4173                         napi_schedule_irqoff(&q_vector->napi);
4174         }
4175
4176         if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4177                 ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4178                 set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4179                 i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4180         }
4181
4182         if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4183                 ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4184                 set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4185         }
4186
4187         if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4188                 /* disable any further VFLR event notifications */
4189                 if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4190                         u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4191
4192                         reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4193                         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4194                 } else {
4195                         ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4196                         set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4197                 }
4198         }
4199
4200         if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4201                 if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4202                         set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4203                 ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4204                 val = rd32(hw, I40E_GLGEN_RSTAT);
4205                 val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4206                        >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4207                 if (val == I40E_RESET_CORER) {
4208                         pf->corer_count++;
4209                 } else if (val == I40E_RESET_GLOBR) {
4210                         pf->globr_count++;
4211                 } else if (val == I40E_RESET_EMPR) {
4212                         pf->empr_count++;
4213                         set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4214                 }
4215         }
4216
4217         if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4218                 icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4219                 dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4220                 dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4221                          rd32(hw, I40E_PFHMC_ERRORINFO),
4222                          rd32(hw, I40E_PFHMC_ERRORDATA));
4223         }
4224
4225         if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4226                 u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4227
4228                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4229                         schedule_work(&pf->ptp_extts0_work);
4230
4231                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4232                         i40e_ptp_tx_hwtstamp(pf);
4233
4234                 icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4235         }
4236
4237         /* If a critical error is pending we have no choice but to reset the
4238          * device.
4239          * Report and mask out any remaining unexpected interrupts.
4240          */
4241         icr0_remaining = icr0 & ena_mask;
4242         if (icr0_remaining) {
4243                 dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4244                          icr0_remaining);
4245                 if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4246                     (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4247                     (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4248                         dev_info(&pf->pdev->dev, "device will be reset\n");
4249                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4250                         i40e_service_event_schedule(pf);
4251                 }
4252                 ena_mask &= ~icr0_remaining;
4253         }
4254         ret = IRQ_HANDLED;
4255
4256 enable_intr:
4257         /* re-enable interrupt causes */
4258         wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4259         if (!test_bit(__I40E_DOWN, pf->state) ||
4260             test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4261                 i40e_service_event_schedule(pf);
4262                 i40e_irq_dynamic_enable_icr0(pf);
4263         }
4264
4265         return ret;
4266 }
4267
4268 /**
4269  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4270  * @tx_ring:  tx ring to clean
4271  * @budget:   how many cleans we're allowed
4272  *
4273  * Returns true if there's any budget left (e.g. the clean is finished)
4274  **/
4275 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4276 {
4277         struct i40e_vsi *vsi = tx_ring->vsi;
4278         u16 i = tx_ring->next_to_clean;
4279         struct i40e_tx_buffer *tx_buf;
4280         struct i40e_tx_desc *tx_desc;
4281
4282         tx_buf = &tx_ring->tx_bi[i];
4283         tx_desc = I40E_TX_DESC(tx_ring, i);
4284         i -= tx_ring->count;
4285
4286         do {
4287                 struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4288
4289                 /* if next_to_watch is not set then there is no work pending */
4290                 if (!eop_desc)
4291                         break;
4292
4293                 /* prevent any other reads prior to eop_desc */
4294                 smp_rmb();
4295
4296                 /* if the descriptor isn't done, no work yet to do */
4297                 if (!(eop_desc->cmd_type_offset_bsz &
4298                       cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4299                         break;
4300
4301                 /* clear next_to_watch to prevent false hangs */
4302                 tx_buf->next_to_watch = NULL;
4303
4304                 tx_desc->buffer_addr = 0;
4305                 tx_desc->cmd_type_offset_bsz = 0;
4306                 /* move past filter desc */
4307                 tx_buf++;
4308                 tx_desc++;
4309                 i++;
4310                 if (unlikely(!i)) {
4311                         i -= tx_ring->count;
4312                         tx_buf = tx_ring->tx_bi;
4313                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4314                 }
4315                 /* unmap skb header data */
4316                 dma_unmap_single(tx_ring->dev,
4317                                  dma_unmap_addr(tx_buf, dma),
4318                                  dma_unmap_len(tx_buf, len),
4319                                  DMA_TO_DEVICE);
4320                 if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4321                         kfree(tx_buf->raw_buf);
4322
4323                 tx_buf->raw_buf = NULL;
4324                 tx_buf->tx_flags = 0;
4325                 tx_buf->next_to_watch = NULL;
4326                 dma_unmap_len_set(tx_buf, len, 0);
4327                 tx_desc->buffer_addr = 0;
4328                 tx_desc->cmd_type_offset_bsz = 0;
4329
4330                 /* move us past the eop_desc for start of next FD desc */
4331                 tx_buf++;
4332                 tx_desc++;
4333                 i++;
4334                 if (unlikely(!i)) {
4335                         i -= tx_ring->count;
4336                         tx_buf = tx_ring->tx_bi;
4337                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4338                 }
4339
4340                 /* update budget accounting */
4341                 budget--;
4342         } while (likely(budget));
4343
4344         i += tx_ring->count;
4345         tx_ring->next_to_clean = i;
4346
4347         if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4348                 i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4349
4350         return budget > 0;
4351 }
4352
4353 /**
4354  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4355  * @irq: interrupt number
4356  * @data: pointer to a q_vector
4357  **/
4358 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4359 {
4360         struct i40e_q_vector *q_vector = data;
4361         struct i40e_vsi *vsi;
4362
4363         if (!q_vector->tx.ring)
4364                 return IRQ_HANDLED;
4365
4366         vsi = q_vector->tx.ring->vsi;
4367         i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4368
4369         return IRQ_HANDLED;
4370 }
4371
4372 /**
4373  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4374  * @vsi: the VSI being configured
4375  * @v_idx: vector index
4376  * @qp_idx: queue pair index
4377  **/
4378 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4379 {
4380         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4381         struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4382         struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4383
4384         tx_ring->q_vector = q_vector;
4385         tx_ring->next = q_vector->tx.ring;
4386         q_vector->tx.ring = tx_ring;
4387         q_vector->tx.count++;
4388
4389         /* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4390         if (i40e_enabled_xdp_vsi(vsi)) {
4391                 struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4392
4393                 xdp_ring->q_vector = q_vector;
4394                 xdp_ring->next = q_vector->tx.ring;
4395                 q_vector->tx.ring = xdp_ring;
4396                 q_vector->tx.count++;
4397         }
4398
4399         rx_ring->q_vector = q_vector;
4400         rx_ring->next = q_vector->rx.ring;
4401         q_vector->rx.ring = rx_ring;
4402         q_vector->rx.count++;
4403 }
4404
4405 /**
4406  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4407  * @vsi: the VSI being configured
4408  *
4409  * This function maps descriptor rings to the queue-specific vectors
4410  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4411  * one vector per queue pair, but on a constrained vector budget, we
4412  * group the queue pairs as "efficiently" as possible.
4413  **/
4414 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4415 {
4416         int qp_remaining = vsi->num_queue_pairs;
4417         int q_vectors = vsi->num_q_vectors;
4418         int num_ringpairs;
4419         int v_start = 0;
4420         int qp_idx = 0;
4421
4422         /* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4423          * group them so there are multiple queues per vector.
4424          * It is also important to go through all the vectors available to be
4425          * sure that if we don't use all the vectors, that the remaining vectors
4426          * are cleared. This is especially important when decreasing the
4427          * number of queues in use.
4428          */
4429         for (; v_start < q_vectors; v_start++) {
4430                 struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4431
4432                 num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4433
4434                 q_vector->num_ringpairs = num_ringpairs;
4435                 q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4436
4437                 q_vector->rx.count = 0;
4438                 q_vector->tx.count = 0;
4439                 q_vector->rx.ring = NULL;
4440                 q_vector->tx.ring = NULL;
4441
4442                 while (num_ringpairs--) {
4443                         i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4444                         qp_idx++;
4445                         qp_remaining--;
4446                 }
4447         }
4448 }
4449
4450 /**
4451  * i40e_vsi_request_irq - Request IRQ from the OS
4452  * @vsi: the VSI being configured
4453  * @basename: name for the vector
4454  **/
4455 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4456 {
4457         struct i40e_pf *pf = vsi->back;
4458         int err;
4459
4460         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4461                 err = i40e_vsi_request_irq_msix(vsi, basename);
4462         else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4463                 err = request_irq(pf->pdev->irq, i40e_intr, 0,
4464                                   pf->int_name, pf);
4465         else
4466                 err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4467                                   pf->int_name, pf);
4468
4469         if (err)
4470                 dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4471
4472         return err;
4473 }
4474
4475 #ifdef CONFIG_NET_POLL_CONTROLLER
4476 /**
4477  * i40e_netpoll - A Polling 'interrupt' handler
4478  * @netdev: network interface device structure
4479  *
4480  * This is used by netconsole to send skbs without having to re-enable
4481  * interrupts.  It's not called while the normal interrupt routine is executing.
4482  **/
4483 static void i40e_netpoll(struct net_device *netdev)
4484 {
4485         struct i40e_netdev_priv *np = netdev_priv(netdev);
4486         struct i40e_vsi *vsi = np->vsi;
4487         struct i40e_pf *pf = vsi->back;
4488         int i;
4489
4490         /* if interface is down do nothing */
4491         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4492                 return;
4493
4494         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4495                 for (i = 0; i < vsi->num_q_vectors; i++)
4496                         i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4497         } else {
4498                 i40e_intr(pf->pdev->irq, netdev);
4499         }
4500 }
4501 #endif
4502
4503 #define I40E_QTX_ENA_WAIT_COUNT 50
4504
4505 /**
4506  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4507  * @pf: the PF being configured
4508  * @pf_q: the PF queue
4509  * @enable: enable or disable state of the queue
4510  *
4511  * This routine will wait for the given Tx queue of the PF to reach the
4512  * enabled or disabled state.
4513  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4514  * multiple retries; else will return 0 in case of success.
4515  **/
4516 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4517 {
4518         int i;
4519         u32 tx_reg;
4520
4521         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4522                 tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4523                 if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4524                         break;
4525
4526                 usleep_range(10, 20);
4527         }
4528         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4529                 return -ETIMEDOUT;
4530
4531         return 0;
4532 }
4533
4534 /**
4535  * i40e_control_tx_q - Start or stop a particular Tx queue
4536  * @pf: the PF structure
4537  * @pf_q: the PF queue to configure
4538  * @enable: start or stop the queue
4539  *
4540  * This function enables or disables a single queue. Note that any delay
4541  * required after the operation is expected to be handled by the caller of
4542  * this function.
4543  **/
4544 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4545 {
4546         struct i40e_hw *hw = &pf->hw;
4547         u32 tx_reg;
4548         int i;
4549
4550         /* warn the TX unit of coming changes */
4551         i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4552         if (!enable)
4553                 usleep_range(10, 20);
4554
4555         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4556                 tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4557                 if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4558                     ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4559                         break;
4560                 usleep_range(1000, 2000);
4561         }
4562
4563         /* Skip if the queue is already in the requested state */
4564         if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4565                 return;
4566
4567         /* turn on/off the queue */
4568         if (enable) {
4569                 wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4570                 tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4571         } else {
4572                 tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4573         }
4574
4575         wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4576 }
4577
4578 /**
4579  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4580  * @seid: VSI SEID
4581  * @pf: the PF structure
4582  * @pf_q: the PF queue to configure
4583  * @is_xdp: true if the queue is used for XDP
4584  * @enable: start or stop the queue
4585  **/
4586 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4587                            bool is_xdp, bool enable)
4588 {
4589         int ret;
4590
4591         i40e_control_tx_q(pf, pf_q, enable);
4592
4593         /* wait for the change to finish */
4594         ret = i40e_pf_txq_wait(pf, pf_q, enable);
4595         if (ret) {
4596                 dev_info(&pf->pdev->dev,
4597                          "VSI seid %d %sTx ring %d %sable timeout\n",
4598                          seid, (is_xdp ? "XDP " : ""), pf_q,
4599                          (enable ? "en" : "dis"));
4600         }
4601
4602         return ret;
4603 }
4604
4605 /**
4606  * i40e_vsi_enable_tx - Start a VSI's rings
4607  * @vsi: the VSI being configured
4608  **/
4609 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4610 {
4611         struct i40e_pf *pf = vsi->back;
4612         int i, pf_q, ret = 0;
4613
4614         pf_q = vsi->base_queue;
4615         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4616                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4617                                              pf_q,
4618                                              false /*is xdp*/, true);
4619                 if (ret)
4620                         break;
4621
4622                 if (!i40e_enabled_xdp_vsi(vsi))
4623                         continue;
4624
4625                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4626                                              pf_q + vsi->alloc_queue_pairs,
4627                                              true /*is xdp*/, true);
4628                 if (ret)
4629                         break;
4630         }
4631         return ret;
4632 }
4633
4634 /**
4635  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4636  * @pf: the PF being configured
4637  * @pf_q: the PF queue
4638  * @enable: enable or disable state of the queue
4639  *
4640  * This routine will wait for the given Rx queue of the PF to reach the
4641  * enabled or disabled state.
4642  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4643  * multiple retries; else will return 0 in case of success.
4644  **/
4645 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4646 {
4647         int i;
4648         u32 rx_reg;
4649
4650         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4651                 rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4652                 if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4653                         break;
4654
4655                 usleep_range(10, 20);
4656         }
4657         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4658                 return -ETIMEDOUT;
4659
4660         return 0;
4661 }
4662
4663 /**
4664  * i40e_control_rx_q - Start or stop a particular Rx queue
4665  * @pf: the PF structure
4666  * @pf_q: the PF queue to configure
4667  * @enable: start or stop the queue
4668  *
4669  * This function enables or disables a single queue. Note that
4670  * any delay required after the operation is expected to be
4671  * handled by the caller of this function.
4672  **/
4673 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4674 {
4675         struct i40e_hw *hw = &pf->hw;
4676         u32 rx_reg;
4677         int i;
4678
4679         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4680                 rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4681                 if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4682                     ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4683                         break;
4684                 usleep_range(1000, 2000);
4685         }
4686
4687         /* Skip if the queue is already in the requested state */
4688         if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4689                 return;
4690
4691         /* turn on/off the queue */
4692         if (enable)
4693                 rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4694         else
4695                 rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4696
4697         wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4698 }
4699
4700 /**
4701  * i40e_control_wait_rx_q
4702  * @pf: the PF structure
4703  * @pf_q: queue being configured
4704  * @enable: start or stop the rings
4705  *
4706  * This function enables or disables a single queue along with waiting
4707  * for the change to finish. The caller of this function should handle
4708  * the delays needed in the case of disabling queues.
4709  **/
4710 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4711 {
4712         int ret = 0;
4713
4714         i40e_control_rx_q(pf, pf_q, enable);
4715
4716         /* wait for the change to finish */
4717         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4718         if (ret)
4719                 return ret;
4720
4721         return ret;
4722 }
4723
4724 /**
4725  * i40e_vsi_enable_rx - Start a VSI's rings
4726  * @vsi: the VSI being configured
4727  **/
4728 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4729 {
4730         struct i40e_pf *pf = vsi->back;
4731         int i, pf_q, ret = 0;
4732
4733         pf_q = vsi->base_queue;
4734         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4735                 ret = i40e_control_wait_rx_q(pf, pf_q, true);
4736                 if (ret) {
4737                         dev_info(&pf->pdev->dev,
4738                                  "VSI seid %d Rx ring %d enable timeout\n",
4739                                  vsi->seid, pf_q);
4740                         break;
4741                 }
4742         }
4743
4744         return ret;
4745 }
4746
4747 /**
4748  * i40e_vsi_start_rings - Start a VSI's rings
4749  * @vsi: the VSI being configured
4750  **/
4751 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4752 {
4753         int ret = 0;
4754
4755         /* do rx first for enable and last for disable */
4756         ret = i40e_vsi_enable_rx(vsi);
4757         if (ret)
4758                 return ret;
4759         ret = i40e_vsi_enable_tx(vsi);
4760
4761         return ret;
4762 }
4763
4764 #define I40E_DISABLE_TX_GAP_MSEC        50
4765
4766 /**
4767  * i40e_vsi_stop_rings - Stop a VSI's rings
4768  * @vsi: the VSI being configured
4769  **/
4770 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4771 {
4772         struct i40e_pf *pf = vsi->back;
4773         int pf_q, err, q_end;
4774
4775         /* When port TX is suspended, don't wait */
4776         if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4777                 return i40e_vsi_stop_rings_no_wait(vsi);
4778
4779         q_end = vsi->base_queue + vsi->num_queue_pairs;
4780         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4781                 i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4782
4783         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4784                 err = i40e_control_wait_rx_q(pf, pf_q, false);
4785                 if (err)
4786                         dev_info(&pf->pdev->dev,
4787                                  "VSI seid %d Rx ring %d disable timeout\n",
4788                                  vsi->seid, pf_q);
4789         }
4790
4791         msleep(I40E_DISABLE_TX_GAP_MSEC);
4792         pf_q = vsi->base_queue;
4793         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4794                 wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4795
4796         i40e_vsi_wait_queues_disabled(vsi);
4797 }
4798
4799 /**
4800  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4801  * @vsi: the VSI being shutdown
4802  *
4803  * This function stops all the rings for a VSI but does not delay to verify
4804  * that rings have been disabled. It is expected that the caller is shutting
4805  * down multiple VSIs at once and will delay together for all the VSIs after
4806  * initiating the shutdown. This is particularly useful for shutting down lots
4807  * of VFs together. Otherwise, a large delay can be incurred while configuring
4808  * each VSI in serial.
4809  **/
4810 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4811 {
4812         struct i40e_pf *pf = vsi->back;
4813         int i, pf_q;
4814
4815         pf_q = vsi->base_queue;
4816         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4817                 i40e_control_tx_q(pf, pf_q, false);
4818                 i40e_control_rx_q(pf, pf_q, false);
4819         }
4820 }
4821
4822 /**
4823  * i40e_vsi_free_irq - Free the irq association with the OS
4824  * @vsi: the VSI being configured
4825  **/
4826 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4827 {
4828         struct i40e_pf *pf = vsi->back;
4829         struct i40e_hw *hw = &pf->hw;
4830         int base = vsi->base_vector;
4831         u32 val, qp;
4832         int i;
4833
4834         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4835                 if (!vsi->q_vectors)
4836                         return;
4837
4838                 if (!vsi->irqs_ready)
4839                         return;
4840
4841                 vsi->irqs_ready = false;
4842                 for (i = 0; i < vsi->num_q_vectors; i++) {
4843                         int irq_num;
4844                         u16 vector;
4845
4846                         vector = i + base;
4847                         irq_num = pf->msix_entries[vector].vector;
4848
4849                         /* free only the irqs that were actually requested */
4850                         if (!vsi->q_vectors[i] ||
4851                             !vsi->q_vectors[i]->num_ringpairs)
4852                                 continue;
4853
4854                         /* clear the affinity notifier in the IRQ descriptor */
4855                         irq_set_affinity_notifier(irq_num, NULL);
4856                         /* remove our suggested affinity mask for this IRQ */
4857                         irq_update_affinity_hint(irq_num, NULL);
4858                         synchronize_irq(irq_num);
4859                         free_irq(irq_num, vsi->q_vectors[i]);
4860
4861                         /* Tear down the interrupt queue link list
4862                          *
4863                          * We know that they come in pairs and always
4864                          * the Rx first, then the Tx.  To clear the
4865                          * link list, stick the EOL value into the
4866                          * next_q field of the registers.
4867                          */
4868                         val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4869                         qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4870                                 >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4871                         val |= I40E_QUEUE_END_OF_LIST
4872                                 << I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4873                         wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4874
4875                         while (qp != I40E_QUEUE_END_OF_LIST) {
4876                                 u32 next;
4877
4878                                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4879
4880                                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4881                                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4882                                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4883                                          I40E_QINT_RQCTL_INTEVENT_MASK);
4884
4885                                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4886                                          I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4887
4888                                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4889
4890                                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4891
4892                                 next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
4893                                         >> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
4894
4895                                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4896                                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4897                                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4898                                          I40E_QINT_TQCTL_INTEVENT_MASK);
4899
4900                                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4901                                          I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4902
4903                                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4904                                 qp = next;
4905                         }
4906                 }
4907         } else {
4908                 free_irq(pf->pdev->irq, pf);
4909
4910                 val = rd32(hw, I40E_PFINT_LNKLST0);
4911                 qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4912                         >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4913                 val |= I40E_QUEUE_END_OF_LIST
4914                         << I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
4915                 wr32(hw, I40E_PFINT_LNKLST0, val);
4916
4917                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4918                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4919                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4920                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4921                          I40E_QINT_RQCTL_INTEVENT_MASK);
4922
4923                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4924                         I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4925
4926                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4927
4928                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4929
4930                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4931                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4932                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4933                          I40E_QINT_TQCTL_INTEVENT_MASK);
4934
4935                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4936                         I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4937
4938                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4939         }
4940 }
4941
4942 /**
4943  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
4944  * @vsi: the VSI being configured
4945  * @v_idx: Index of vector to be freed
4946  *
4947  * This function frees the memory allocated to the q_vector.  In addition if
4948  * NAPI is enabled it will delete any references to the NAPI struct prior
4949  * to freeing the q_vector.
4950  **/
4951 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
4952 {
4953         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4954         struct i40e_ring *ring;
4955
4956         if (!q_vector)
4957                 return;
4958
4959         /* disassociate q_vector from rings */
4960         i40e_for_each_ring(ring, q_vector->tx)
4961                 ring->q_vector = NULL;
4962
4963         i40e_for_each_ring(ring, q_vector->rx)
4964                 ring->q_vector = NULL;
4965
4966         /* only VSI w/ an associated netdev is set up w/ NAPI */
4967         if (vsi->netdev)
4968                 netif_napi_del(&q_vector->napi);
4969
4970         vsi->q_vectors[v_idx] = NULL;
4971
4972         kfree_rcu(q_vector, rcu);
4973 }
4974
4975 /**
4976  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
4977  * @vsi: the VSI being un-configured
4978  *
4979  * This frees the memory allocated to the q_vectors and
4980  * deletes references to the NAPI struct.
4981  **/
4982 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
4983 {
4984         int v_idx;
4985
4986         for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
4987                 i40e_free_q_vector(vsi, v_idx);
4988 }
4989
4990 /**
4991  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
4992  * @pf: board private structure
4993  **/
4994 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
4995 {
4996         /* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
4997         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4998                 pci_disable_msix(pf->pdev);
4999                 kfree(pf->msix_entries);
5000                 pf->msix_entries = NULL;
5001                 kfree(pf->irq_pile);
5002                 pf->irq_pile = NULL;
5003         } else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
5004                 pci_disable_msi(pf->pdev);
5005         }
5006         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
5007 }
5008
5009 /**
5010  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
5011  * @pf: board private structure
5012  *
5013  * We go through and clear interrupt specific resources and reset the structure
5014  * to pre-load conditions
5015  **/
5016 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
5017 {
5018         int i;
5019
5020         if (test_bit(__I40E_MISC_IRQ_REQUESTED, pf->state))
5021                 i40e_free_misc_vector(pf);
5022
5023         i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
5024                       I40E_IWARP_IRQ_PILE_ID);
5025
5026         i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
5027         for (i = 0; i < pf->num_alloc_vsi; i++)
5028                 if (pf->vsi[i])
5029                         i40e_vsi_free_q_vectors(pf->vsi[i]);
5030         i40e_reset_interrupt_capability(pf);
5031 }
5032
5033 /**
5034  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
5035  * @vsi: the VSI being configured
5036  **/
5037 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
5038 {
5039         int q_idx;
5040
5041         if (!vsi->netdev)
5042                 return;
5043
5044         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5045                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5046
5047                 if (q_vector->rx.ring || q_vector->tx.ring)
5048                         napi_enable(&q_vector->napi);
5049         }
5050 }
5051
5052 /**
5053  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
5054  * @vsi: the VSI being configured
5055  **/
5056 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
5057 {
5058         int q_idx;
5059
5060         if (!vsi->netdev)
5061                 return;
5062
5063         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
5064                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
5065
5066                 if (q_vector->rx.ring || q_vector->tx.ring)
5067                         napi_disable(&q_vector->napi);
5068         }
5069 }
5070
5071 /**
5072  * i40e_vsi_close - Shut down a VSI
5073  * @vsi: the vsi to be quelled
5074  **/
5075 static void i40e_vsi_close(struct i40e_vsi *vsi)
5076 {
5077         struct i40e_pf *pf = vsi->back;
5078         if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
5079                 i40e_down(vsi);
5080         i40e_vsi_free_irq(vsi);
5081         i40e_vsi_free_tx_resources(vsi);
5082         i40e_vsi_free_rx_resources(vsi);
5083         vsi->current_netdev_flags = 0;
5084         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
5085         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
5086                 set_bit(__I40E_CLIENT_RESET, pf->state);
5087 }
5088
5089 /**
5090  * i40e_quiesce_vsi - Pause a given VSI
5091  * @vsi: the VSI being paused
5092  **/
5093 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
5094 {
5095         if (test_bit(__I40E_VSI_DOWN, vsi->state))
5096                 return;
5097
5098         set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
5099         if (vsi->netdev && netif_running(vsi->netdev))
5100                 vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
5101         else
5102                 i40e_vsi_close(vsi);
5103 }
5104
5105 /**
5106  * i40e_unquiesce_vsi - Resume a given VSI
5107  * @vsi: the VSI being resumed
5108  **/
5109 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
5110 {
5111         if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
5112                 return;
5113
5114         if (vsi->netdev && netif_running(vsi->netdev))
5115                 vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
5116         else
5117                 i40e_vsi_open(vsi);   /* this clears the DOWN bit */
5118 }
5119
5120 /**
5121  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
5122  * @pf: the PF
5123  **/
5124 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
5125 {
5126         int v;
5127
5128         for (v = 0; v < pf->num_alloc_vsi; v++) {
5129                 if (pf->vsi[v])
5130                         i40e_quiesce_vsi(pf->vsi[v]);
5131         }
5132 }
5133
5134 /**
5135  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
5136  * @pf: the PF
5137  **/
5138 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
5139 {
5140         int v;
5141
5142         for (v = 0; v < pf->num_alloc_vsi; v++) {
5143                 if (pf->vsi[v])
5144                         i40e_unquiesce_vsi(pf->vsi[v]);
5145         }
5146 }
5147
5148 /**
5149  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5150  * @vsi: the VSI being configured
5151  *
5152  * Wait until all queues on a given VSI have been disabled.
5153  **/
5154 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5155 {
5156         struct i40e_pf *pf = vsi->back;
5157         int i, pf_q, ret;
5158
5159         pf_q = vsi->base_queue;
5160         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5161                 /* Check and wait for the Tx queue */
5162                 ret = i40e_pf_txq_wait(pf, pf_q, false);
5163                 if (ret) {
5164                         dev_info(&pf->pdev->dev,
5165                                  "VSI seid %d Tx ring %d disable timeout\n",
5166                                  vsi->seid, pf_q);
5167                         return ret;
5168                 }
5169
5170                 if (!i40e_enabled_xdp_vsi(vsi))
5171                         goto wait_rx;
5172
5173                 /* Check and wait for the XDP Tx queue */
5174                 ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5175                                        false);
5176                 if (ret) {
5177                         dev_info(&pf->pdev->dev,
5178                                  "VSI seid %d XDP Tx ring %d disable timeout\n",
5179                                  vsi->seid, pf_q);
5180                         return ret;
5181                 }
5182 wait_rx:
5183                 /* Check and wait for the Rx queue */
5184                 ret = i40e_pf_rxq_wait(pf, pf_q, false);
5185                 if (ret) {
5186                         dev_info(&pf->pdev->dev,
5187                                  "VSI seid %d Rx ring %d disable timeout\n",
5188                                  vsi->seid, pf_q);
5189                         return ret;
5190                 }
5191         }
5192
5193         return 0;
5194 }
5195
5196 #ifdef CONFIG_I40E_DCB
5197 /**
5198  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5199  * @pf: the PF
5200  *
5201  * This function waits for the queues to be in disabled state for all the
5202  * VSIs that are managed by this PF.
5203  **/
5204 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5205 {
5206         int v, ret = 0;
5207
5208         for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5209                 if (pf->vsi[v]) {
5210                         ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5211                         if (ret)
5212                                 break;
5213                 }
5214         }
5215
5216         return ret;
5217 }
5218
5219 #endif
5220
5221 /**
5222  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5223  * @pf: pointer to PF
5224  *
5225  * Get TC map for ISCSI PF type that will include iSCSI TC
5226  * and LAN TC.
5227  **/
5228 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5229 {
5230         struct i40e_dcb_app_priority_table app;
5231         struct i40e_hw *hw = &pf->hw;
5232         u8 enabled_tc = 1; /* TC0 is always enabled */
5233         u8 tc, i;
5234         /* Get the iSCSI APP TLV */
5235         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5236
5237         for (i = 0; i < dcbcfg->numapps; i++) {
5238                 app = dcbcfg->app[i];
5239                 if (app.selector == I40E_APP_SEL_TCPIP &&
5240                     app.protocolid == I40E_APP_PROTOID_ISCSI) {
5241                         tc = dcbcfg->etscfg.prioritytable[app.priority];
5242                         enabled_tc |= BIT(tc);
5243                         break;
5244                 }
5245         }
5246
5247         return enabled_tc;
5248 }
5249
5250 /**
5251  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5252  * @dcbcfg: the corresponding DCBx configuration structure
5253  *
5254  * Return the number of TCs from given DCBx configuration
5255  **/
5256 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5257 {
5258         int i, tc_unused = 0;
5259         u8 num_tc = 0;
5260         u8 ret = 0;
5261
5262         /* Scan the ETS Config Priority Table to find
5263          * traffic class enabled for a given priority
5264          * and create a bitmask of enabled TCs
5265          */
5266         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5267                 num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5268
5269         /* Now scan the bitmask to check for
5270          * contiguous TCs starting with TC0
5271          */
5272         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5273                 if (num_tc & BIT(i)) {
5274                         if (!tc_unused) {
5275                                 ret++;
5276                         } else {
5277                                 pr_err("Non-contiguous TC - Disabling DCB\n");
5278                                 return 1;
5279                         }
5280                 } else {
5281                         tc_unused = 1;
5282                 }
5283         }
5284
5285         /* There is always at least TC0 */
5286         if (!ret)
5287                 ret = 1;
5288
5289         return ret;
5290 }
5291
5292 /**
5293  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5294  * @dcbcfg: the corresponding DCBx configuration structure
5295  *
5296  * Query the current DCB configuration and return the number of
5297  * traffic classes enabled from the given DCBX config
5298  **/
5299 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5300 {
5301         u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5302         u8 enabled_tc = 1;
5303         u8 i;
5304
5305         for (i = 0; i < num_tc; i++)
5306                 enabled_tc |= BIT(i);
5307
5308         return enabled_tc;
5309 }
5310
5311 /**
5312  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5313  * @pf: PF being queried
5314  *
5315  * Query the current MQPRIO configuration and return the number of
5316  * traffic classes enabled.
5317  **/
5318 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5319 {
5320         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5321         u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5322         u8 enabled_tc = 1, i;
5323
5324         for (i = 1; i < num_tc; i++)
5325                 enabled_tc |= BIT(i);
5326         return enabled_tc;
5327 }
5328
5329 /**
5330  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5331  * @pf: PF being queried
5332  *
5333  * Return number of traffic classes enabled for the given PF
5334  **/
5335 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5336 {
5337         struct i40e_hw *hw = &pf->hw;
5338         u8 i, enabled_tc = 1;
5339         u8 num_tc = 0;
5340         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5341
5342         if (i40e_is_tc_mqprio_enabled(pf))
5343                 return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5344
5345         /* If neither MQPRIO nor DCB is enabled, then always use single TC */
5346         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5347                 return 1;
5348
5349         /* SFP mode will be enabled for all TCs on port */
5350         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5351                 return i40e_dcb_get_num_tc(dcbcfg);
5352
5353         /* MFP mode return count of enabled TCs for this PF */
5354         if (pf->hw.func_caps.iscsi)
5355                 enabled_tc =  i40e_get_iscsi_tc_map(pf);
5356         else
5357                 return 1; /* Only TC0 */
5358
5359         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5360                 if (enabled_tc & BIT(i))
5361                         num_tc++;
5362         }
5363         return num_tc;
5364 }
5365
5366 /**
5367  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5368  * @pf: PF being queried
5369  *
5370  * Return a bitmap for enabled traffic classes for this PF.
5371  **/
5372 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5373 {
5374         if (i40e_is_tc_mqprio_enabled(pf))
5375                 return i40e_mqprio_get_enabled_tc(pf);
5376
5377         /* If neither MQPRIO nor DCB is enabled for this PF then just return
5378          * default TC
5379          */
5380         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5381                 return I40E_DEFAULT_TRAFFIC_CLASS;
5382
5383         /* SFP mode we want PF to be enabled for all TCs */
5384         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5385                 return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5386
5387         /* MFP enabled and iSCSI PF type */
5388         if (pf->hw.func_caps.iscsi)
5389                 return i40e_get_iscsi_tc_map(pf);
5390         else
5391                 return I40E_DEFAULT_TRAFFIC_CLASS;
5392 }
5393
5394 /**
5395  * i40e_vsi_get_bw_info - Query VSI BW Information
5396  * @vsi: the VSI being queried
5397  *
5398  * Returns 0 on success, negative value on failure
5399  **/
5400 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5401 {
5402         struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5403         struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5404         struct i40e_pf *pf = vsi->back;
5405         struct i40e_hw *hw = &pf->hw;
5406         i40e_status ret;
5407         u32 tc_bw_max;
5408         int i;
5409
5410         /* Get the VSI level BW configuration */
5411         ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5412         if (ret) {
5413                 dev_info(&pf->pdev->dev,
5414                          "couldn't get PF vsi bw config, err %s aq_err %s\n",
5415                          i40e_stat_str(&pf->hw, ret),
5416                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5417                 return -EINVAL;
5418         }
5419
5420         /* Get the VSI level BW configuration per TC */
5421         ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5422                                                NULL);
5423         if (ret) {
5424                 dev_info(&pf->pdev->dev,
5425                          "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
5426                          i40e_stat_str(&pf->hw, ret),
5427                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5428                 return -EINVAL;
5429         }
5430
5431         if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5432                 dev_info(&pf->pdev->dev,
5433                          "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5434                          bw_config.tc_valid_bits,
5435                          bw_ets_config.tc_valid_bits);
5436                 /* Still continuing */
5437         }
5438
5439         vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5440         vsi->bw_max_quanta = bw_config.max_bw;
5441         tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5442                     (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5443         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5444                 vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5445                 vsi->bw_ets_limit_credits[i] =
5446                                         le16_to_cpu(bw_ets_config.credits[i]);
5447                 /* 3 bits out of 4 for each TC */
5448                 vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5449         }
5450
5451         return 0;
5452 }
5453
5454 /**
5455  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5456  * @vsi: the VSI being configured
5457  * @enabled_tc: TC bitmap
5458  * @bw_share: BW shared credits per TC
5459  *
5460  * Returns 0 on success, negative value on failure
5461  **/
5462 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5463                                        u8 *bw_share)
5464 {
5465         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5466         struct i40e_pf *pf = vsi->back;
5467         i40e_status ret;
5468         int i;
5469
5470         /* There is no need to reset BW when mqprio mode is on.  */
5471         if (i40e_is_tc_mqprio_enabled(pf))
5472                 return 0;
5473         if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5474                 ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5475                 if (ret)
5476                         dev_info(&pf->pdev->dev,
5477                                  "Failed to reset tx rate for vsi->seid %u\n",
5478                                  vsi->seid);
5479                 return ret;
5480         }
5481         memset(&bw_data, 0, sizeof(bw_data));
5482         bw_data.tc_valid_bits = enabled_tc;
5483         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5484                 bw_data.tc_bw_credits[i] = bw_share[i];
5485
5486         ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5487         if (ret) {
5488                 dev_info(&pf->pdev->dev,
5489                          "AQ command Config VSI BW allocation per TC failed = %d\n",
5490                          pf->hw.aq.asq_last_status);
5491                 return -EINVAL;
5492         }
5493
5494         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5495                 vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5496
5497         return 0;
5498 }
5499
5500 /**
5501  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5502  * @vsi: the VSI being configured
5503  * @enabled_tc: TC map to be enabled
5504  *
5505  **/
5506 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5507 {
5508         struct net_device *netdev = vsi->netdev;
5509         struct i40e_pf *pf = vsi->back;
5510         struct i40e_hw *hw = &pf->hw;
5511         u8 netdev_tc = 0;
5512         int i;
5513         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5514
5515         if (!netdev)
5516                 return;
5517
5518         if (!enabled_tc) {
5519                 netdev_reset_tc(netdev);
5520                 return;
5521         }
5522
5523         /* Set up actual enabled TCs on the VSI */
5524         if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5525                 return;
5526
5527         /* set per TC queues for the VSI */
5528         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5529                 /* Only set TC queues for enabled tcs
5530                  *
5531                  * e.g. For a VSI that has TC0 and TC3 enabled the
5532                  * enabled_tc bitmap would be 0x00001001; the driver
5533                  * will set the numtc for netdev as 2 that will be
5534                  * referenced by the netdev layer as TC 0 and 1.
5535                  */
5536                 if (vsi->tc_config.enabled_tc & BIT(i))
5537                         netdev_set_tc_queue(netdev,
5538                                         vsi->tc_config.tc_info[i].netdev_tc,
5539                                         vsi->tc_config.tc_info[i].qcount,
5540                                         vsi->tc_config.tc_info[i].qoffset);
5541         }
5542
5543         if (i40e_is_tc_mqprio_enabled(pf))
5544                 return;
5545
5546         /* Assign UP2TC map for the VSI */
5547         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5548                 /* Get the actual TC# for the UP */
5549                 u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5550                 /* Get the mapped netdev TC# for the UP */
5551                 netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5552                 netdev_set_prio_tc_map(netdev, i, netdev_tc);
5553         }
5554 }
5555
5556 /**
5557  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5558  * @vsi: the VSI being configured
5559  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5560  **/
5561 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5562                                       struct i40e_vsi_context *ctxt)
5563 {
5564         /* copy just the sections touched not the entire info
5565          * since not all sections are valid as returned by
5566          * update vsi params
5567          */
5568         vsi->info.mapping_flags = ctxt->info.mapping_flags;
5569         memcpy(&vsi->info.queue_mapping,
5570                &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5571         memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5572                sizeof(vsi->info.tc_mapping));
5573 }
5574
5575 /**
5576  * i40e_update_adq_vsi_queues - update queue mapping for ADq VSI
5577  * @vsi: the VSI being reconfigured
5578  * @vsi_offset: offset from main VF VSI
5579  */
5580 int i40e_update_adq_vsi_queues(struct i40e_vsi *vsi, int vsi_offset)
5581 {
5582         struct i40e_vsi_context ctxt = {};
5583         struct i40e_pf *pf;
5584         struct i40e_hw *hw;
5585         int ret;
5586
5587         if (!vsi)
5588                 return I40E_ERR_PARAM;
5589         pf = vsi->back;
5590         hw = &pf->hw;
5591
5592         ctxt.seid = vsi->seid;
5593         ctxt.pf_num = hw->pf_id;
5594         ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id + vsi_offset;
5595         ctxt.uplink_seid = vsi->uplink_seid;
5596         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5597         ctxt.flags = I40E_AQ_VSI_TYPE_VF;
5598         ctxt.info = vsi->info;
5599
5600         i40e_vsi_setup_queue_map(vsi, &ctxt, vsi->tc_config.enabled_tc,
5601                                  false);
5602         if (vsi->reconfig_rss) {
5603                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
5604                                       vsi->num_queue_pairs);
5605                 ret = i40e_vsi_config_rss(vsi);
5606                 if (ret) {
5607                         dev_info(&pf->pdev->dev, "Failed to reconfig rss for num_queues\n");
5608                         return ret;
5609                 }
5610                 vsi->reconfig_rss = false;
5611         }
5612
5613         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5614         if (ret) {
5615                 dev_info(&pf->pdev->dev, "Update vsi config failed, err %s aq_err %s\n",
5616                          i40e_stat_str(hw, ret),
5617                          i40e_aq_str(hw, hw->aq.asq_last_status));
5618                 return ret;
5619         }
5620         /* update the local VSI info with updated queue map */
5621         i40e_vsi_update_queue_map(vsi, &ctxt);
5622         vsi->info.valid_sections = 0;
5623
5624         return ret;
5625 }
5626
5627 /**
5628  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5629  * @vsi: VSI to be configured
5630  * @enabled_tc: TC bitmap
5631  *
5632  * This configures a particular VSI for TCs that are mapped to the
5633  * given TC bitmap. It uses default bandwidth share for TCs across
5634  * VSIs to configure TC for a particular VSI.
5635  *
5636  * NOTE:
5637  * It is expected that the VSI queues have been quisced before calling
5638  * this function.
5639  **/
5640 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5641 {
5642         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5643         struct i40e_pf *pf = vsi->back;
5644         struct i40e_hw *hw = &pf->hw;
5645         struct i40e_vsi_context ctxt;
5646         int ret = 0;
5647         int i;
5648
5649         /* Check if enabled_tc is same as existing or new TCs */
5650         if (vsi->tc_config.enabled_tc == enabled_tc &&
5651             vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5652                 return ret;
5653
5654         /* Enable ETS TCs with equal BW Share for now across all VSIs */
5655         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5656                 if (enabled_tc & BIT(i))
5657                         bw_share[i] = 1;
5658         }
5659
5660         ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5661         if (ret) {
5662                 struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5663
5664                 dev_info(&pf->pdev->dev,
5665                          "Failed configuring TC map %d for VSI %d\n",
5666                          enabled_tc, vsi->seid);
5667                 ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5668                                                   &bw_config, NULL);
5669                 if (ret) {
5670                         dev_info(&pf->pdev->dev,
5671                                  "Failed querying vsi bw info, err %s aq_err %s\n",
5672                                  i40e_stat_str(hw, ret),
5673                                  i40e_aq_str(hw, hw->aq.asq_last_status));
5674                         goto out;
5675                 }
5676                 if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5677                         u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5678
5679                         if (!valid_tc)
5680                                 valid_tc = bw_config.tc_valid_bits;
5681                         /* Always enable TC0, no matter what */
5682                         valid_tc |= 1;
5683                         dev_info(&pf->pdev->dev,
5684                                  "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5685                                  enabled_tc, bw_config.tc_valid_bits, valid_tc);
5686                         enabled_tc = valid_tc;
5687                 }
5688
5689                 ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5690                 if (ret) {
5691                         dev_err(&pf->pdev->dev,
5692                                 "Unable to  configure TC map %d for VSI %d\n",
5693                                 enabled_tc, vsi->seid);
5694                         goto out;
5695                 }
5696         }
5697
5698         /* Update Queue Pairs Mapping for currently enabled UPs */
5699         ctxt.seid = vsi->seid;
5700         ctxt.pf_num = vsi->back->hw.pf_id;
5701         ctxt.vf_num = 0;
5702         ctxt.uplink_seid = vsi->uplink_seid;
5703         ctxt.info = vsi->info;
5704         if (i40e_is_tc_mqprio_enabled(pf)) {
5705                 ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5706                 if (ret)
5707                         goto out;
5708         } else {
5709                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5710         }
5711
5712         /* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5713          * queues changed.
5714          */
5715         if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5716                 vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5717                                       vsi->num_queue_pairs);
5718                 ret = i40e_vsi_config_rss(vsi);
5719                 if (ret) {
5720                         dev_info(&vsi->back->pdev->dev,
5721                                  "Failed to reconfig rss for num_queues\n");
5722                         return ret;
5723                 }
5724                 vsi->reconfig_rss = false;
5725         }
5726         if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5727                 ctxt.info.valid_sections |=
5728                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5729                 ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5730         }
5731
5732         /* Update the VSI after updating the VSI queue-mapping
5733          * information
5734          */
5735         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5736         if (ret) {
5737                 dev_info(&pf->pdev->dev,
5738                          "Update vsi tc config failed, err %s aq_err %s\n",
5739                          i40e_stat_str(hw, ret),
5740                          i40e_aq_str(hw, hw->aq.asq_last_status));
5741                 goto out;
5742         }
5743         /* update the local VSI info with updated queue map */
5744         i40e_vsi_update_queue_map(vsi, &ctxt);
5745         vsi->info.valid_sections = 0;
5746
5747         /* Update current VSI BW information */
5748         ret = i40e_vsi_get_bw_info(vsi);
5749         if (ret) {
5750                 dev_info(&pf->pdev->dev,
5751                          "Failed updating vsi bw info, err %s aq_err %s\n",
5752                          i40e_stat_str(hw, ret),
5753                          i40e_aq_str(hw, hw->aq.asq_last_status));
5754                 goto out;
5755         }
5756
5757         /* Update the netdev TC setup */
5758         i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5759 out:
5760         return ret;
5761 }
5762
5763 /**
5764  * i40e_get_link_speed - Returns link speed for the interface
5765  * @vsi: VSI to be configured
5766  *
5767  **/
5768 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5769 {
5770         struct i40e_pf *pf = vsi->back;
5771
5772         switch (pf->hw.phy.link_info.link_speed) {
5773         case I40E_LINK_SPEED_40GB:
5774                 return 40000;
5775         case I40E_LINK_SPEED_25GB:
5776                 return 25000;
5777         case I40E_LINK_SPEED_20GB:
5778                 return 20000;
5779         case I40E_LINK_SPEED_10GB:
5780                 return 10000;
5781         case I40E_LINK_SPEED_1GB:
5782                 return 1000;
5783         default:
5784                 return -EINVAL;
5785         }
5786 }
5787
5788 /**
5789  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5790  * @vsi: VSI to be configured
5791  * @seid: seid of the channel/VSI
5792  * @max_tx_rate: max TX rate to be configured as BW limit
5793  *
5794  * Helper function to set BW limit for a given VSI
5795  **/
5796 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5797 {
5798         struct i40e_pf *pf = vsi->back;
5799         u64 credits = 0;
5800         int speed = 0;
5801         int ret = 0;
5802
5803         speed = i40e_get_link_speed(vsi);
5804         if (max_tx_rate > speed) {
5805                 dev_err(&pf->pdev->dev,
5806                         "Invalid max tx rate %llu specified for VSI seid %d.",
5807                         max_tx_rate, seid);
5808                 return -EINVAL;
5809         }
5810         if (max_tx_rate && max_tx_rate < 50) {
5811                 dev_warn(&pf->pdev->dev,
5812                          "Setting max tx rate to minimum usable value of 50Mbps.\n");
5813                 max_tx_rate = 50;
5814         }
5815
5816         /* Tx rate credits are in values of 50Mbps, 0 is disabled */
5817         credits = max_tx_rate;
5818         do_div(credits, I40E_BW_CREDIT_DIVISOR);
5819         ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5820                                           I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5821         if (ret)
5822                 dev_err(&pf->pdev->dev,
5823                         "Failed set tx rate (%llu Mbps) for vsi->seid %u, err %s aq_err %s\n",
5824                         max_tx_rate, seid, i40e_stat_str(&pf->hw, ret),
5825                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5826         return ret;
5827 }
5828
5829 /**
5830  * i40e_remove_queue_channels - Remove queue channels for the TCs
5831  * @vsi: VSI to be configured
5832  *
5833  * Remove queue channels for the TCs
5834  **/
5835 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5836 {
5837         enum i40e_admin_queue_err last_aq_status;
5838         struct i40e_cloud_filter *cfilter;
5839         struct i40e_channel *ch, *ch_tmp;
5840         struct i40e_pf *pf = vsi->back;
5841         struct hlist_node *node;
5842         int ret, i;
5843
5844         /* Reset rss size that was stored when reconfiguring rss for
5845          * channel VSIs with non-power-of-2 queue count.
5846          */
5847         vsi->current_rss_size = 0;
5848
5849         /* perform cleanup for channels if they exist */
5850         if (list_empty(&vsi->ch_list))
5851                 return;
5852
5853         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5854                 struct i40e_vsi *p_vsi;
5855
5856                 list_del(&ch->list);
5857                 p_vsi = ch->parent_vsi;
5858                 if (!p_vsi || !ch->initialized) {
5859                         kfree(ch);
5860                         continue;
5861                 }
5862                 /* Reset queue contexts */
5863                 for (i = 0; i < ch->num_queue_pairs; i++) {
5864                         struct i40e_ring *tx_ring, *rx_ring;
5865                         u16 pf_q;
5866
5867                         pf_q = ch->base_queue + i;
5868                         tx_ring = vsi->tx_rings[pf_q];
5869                         tx_ring->ch = NULL;
5870
5871                         rx_ring = vsi->rx_rings[pf_q];
5872                         rx_ring->ch = NULL;
5873                 }
5874
5875                 /* Reset BW configured for this VSI via mqprio */
5876                 ret = i40e_set_bw_limit(vsi, ch->seid, 0);
5877                 if (ret)
5878                         dev_info(&vsi->back->pdev->dev,
5879                                  "Failed to reset tx rate for ch->seid %u\n",
5880                                  ch->seid);
5881
5882                 /* delete cloud filters associated with this channel */
5883                 hlist_for_each_entry_safe(cfilter, node,
5884                                           &pf->cloud_filter_list, cloud_node) {
5885                         if (cfilter->seid != ch->seid)
5886                                 continue;
5887
5888                         hash_del(&cfilter->cloud_node);
5889                         if (cfilter->dst_port)
5890                                 ret = i40e_add_del_cloud_filter_big_buf(vsi,
5891                                                                         cfilter,
5892                                                                         false);
5893                         else
5894                                 ret = i40e_add_del_cloud_filter(vsi, cfilter,
5895                                                                 false);
5896                         last_aq_status = pf->hw.aq.asq_last_status;
5897                         if (ret)
5898                                 dev_info(&pf->pdev->dev,
5899                                          "Failed to delete cloud filter, err %s aq_err %s\n",
5900                                          i40e_stat_str(&pf->hw, ret),
5901                                          i40e_aq_str(&pf->hw, last_aq_status));
5902                         kfree(cfilter);
5903                 }
5904
5905                 /* delete VSI from FW */
5906                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
5907                                              NULL);
5908                 if (ret)
5909                         dev_err(&vsi->back->pdev->dev,
5910                                 "unable to remove channel (%d) for parent VSI(%d)\n",
5911                                 ch->seid, p_vsi->seid);
5912                 kfree(ch);
5913         }
5914         INIT_LIST_HEAD(&vsi->ch_list);
5915 }
5916
5917 /**
5918  * i40e_get_max_queues_for_channel
5919  * @vsi: ptr to VSI to which channels are associated with
5920  *
5921  * Helper function which returns max value among the queue counts set on the
5922  * channels/TCs created.
5923  **/
5924 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
5925 {
5926         struct i40e_channel *ch, *ch_tmp;
5927         int max = 0;
5928
5929         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5930                 if (!ch->initialized)
5931                         continue;
5932                 if (ch->num_queue_pairs > max)
5933                         max = ch->num_queue_pairs;
5934         }
5935
5936         return max;
5937 }
5938
5939 /**
5940  * i40e_validate_num_queues - validate num_queues w.r.t channel
5941  * @pf: ptr to PF device
5942  * @num_queues: number of queues
5943  * @vsi: the parent VSI
5944  * @reconfig_rss: indicates should the RSS be reconfigured or not
5945  *
5946  * This function validates number of queues in the context of new channel
5947  * which is being established and determines if RSS should be reconfigured
5948  * or not for parent VSI.
5949  **/
5950 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
5951                                     struct i40e_vsi *vsi, bool *reconfig_rss)
5952 {
5953         int max_ch_queues;
5954
5955         if (!reconfig_rss)
5956                 return -EINVAL;
5957
5958         *reconfig_rss = false;
5959         if (vsi->current_rss_size) {
5960                 if (num_queues > vsi->current_rss_size) {
5961                         dev_dbg(&pf->pdev->dev,
5962                                 "Error: num_queues (%d) > vsi's current_size(%d)\n",
5963                                 num_queues, vsi->current_rss_size);
5964                         return -EINVAL;
5965                 } else if ((num_queues < vsi->current_rss_size) &&
5966                            (!is_power_of_2(num_queues))) {
5967                         dev_dbg(&pf->pdev->dev,
5968                                 "Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
5969                                 num_queues, vsi->current_rss_size);
5970                         return -EINVAL;
5971                 }
5972         }
5973
5974         if (!is_power_of_2(num_queues)) {
5975                 /* Find the max num_queues configured for channel if channel
5976                  * exist.
5977                  * if channel exist, then enforce 'num_queues' to be more than
5978                  * max ever queues configured for channel.
5979                  */
5980                 max_ch_queues = i40e_get_max_queues_for_channel(vsi);
5981                 if (num_queues < max_ch_queues) {
5982                         dev_dbg(&pf->pdev->dev,
5983                                 "Error: num_queues (%d) < max queues configured for channel(%d)\n",
5984                                 num_queues, max_ch_queues);
5985                         return -EINVAL;
5986                 }
5987                 *reconfig_rss = true;
5988         }
5989
5990         return 0;
5991 }
5992
5993 /**
5994  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
5995  * @vsi: the VSI being setup
5996  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
5997  *
5998  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
5999  **/
6000 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
6001 {
6002         struct i40e_pf *pf = vsi->back;
6003         u8 seed[I40E_HKEY_ARRAY_SIZE];
6004         struct i40e_hw *hw = &pf->hw;
6005         int local_rss_size;
6006         u8 *lut;
6007         int ret;
6008
6009         if (!vsi->rss_size)
6010                 return -EINVAL;
6011
6012         if (rss_size > vsi->rss_size)
6013                 return -EINVAL;
6014
6015         local_rss_size = min_t(int, vsi->rss_size, rss_size);
6016         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
6017         if (!lut)
6018                 return -ENOMEM;
6019
6020         /* Ignoring user configured lut if there is one */
6021         i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
6022
6023         /* Use user configured hash key if there is one, otherwise
6024          * use default.
6025          */
6026         if (vsi->rss_hkey_user)
6027                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
6028         else
6029                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
6030
6031         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
6032         if (ret) {
6033                 dev_info(&pf->pdev->dev,
6034                          "Cannot set RSS lut, err %s aq_err %s\n",
6035                          i40e_stat_str(hw, ret),
6036                          i40e_aq_str(hw, hw->aq.asq_last_status));
6037                 kfree(lut);
6038                 return ret;
6039         }
6040         kfree(lut);
6041
6042         /* Do the update w.r.t. storing rss_size */
6043         if (!vsi->orig_rss_size)
6044                 vsi->orig_rss_size = vsi->rss_size;
6045         vsi->current_rss_size = local_rss_size;
6046
6047         return ret;
6048 }
6049
6050 /**
6051  * i40e_channel_setup_queue_map - Setup a channel queue map
6052  * @pf: ptr to PF device
6053  * @ctxt: VSI context structure
6054  * @ch: ptr to channel structure
6055  *
6056  * Setup queue map for a specific channel
6057  **/
6058 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
6059                                          struct i40e_vsi_context *ctxt,
6060                                          struct i40e_channel *ch)
6061 {
6062         u16 qcount, qmap, sections = 0;
6063         u8 offset = 0;
6064         int pow;
6065
6066         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
6067         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
6068
6069         qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
6070         ch->num_queue_pairs = qcount;
6071
6072         /* find the next higher power-of-2 of num queue pairs */
6073         pow = ilog2(qcount);
6074         if (!is_power_of_2(qcount))
6075                 pow++;
6076
6077         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
6078                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
6079
6080         /* Setup queue TC[0].qmap for given VSI context */
6081         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
6082
6083         ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
6084         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
6085         ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
6086         ctxt->info.valid_sections |= cpu_to_le16(sections);
6087 }
6088
6089 /**
6090  * i40e_add_channel - add a channel by adding VSI
6091  * @pf: ptr to PF device
6092  * @uplink_seid: underlying HW switching element (VEB) ID
6093  * @ch: ptr to channel structure
6094  *
6095  * Add a channel (VSI) using add_vsi and queue_map
6096  **/
6097 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
6098                             struct i40e_channel *ch)
6099 {
6100         struct i40e_hw *hw = &pf->hw;
6101         struct i40e_vsi_context ctxt;
6102         u8 enabled_tc = 0x1; /* TC0 enabled */
6103         int ret;
6104
6105         if (ch->type != I40E_VSI_VMDQ2) {
6106                 dev_info(&pf->pdev->dev,
6107                          "add new vsi failed, ch->type %d\n", ch->type);
6108                 return -EINVAL;
6109         }
6110
6111         memset(&ctxt, 0, sizeof(ctxt));
6112         ctxt.pf_num = hw->pf_id;
6113         ctxt.vf_num = 0;
6114         ctxt.uplink_seid = uplink_seid;
6115         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
6116         if (ch->type == I40E_VSI_VMDQ2)
6117                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
6118
6119         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
6120                 ctxt.info.valid_sections |=
6121                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6122                 ctxt.info.switch_id =
6123                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6124         }
6125
6126         /* Set queue map for a given VSI context */
6127         i40e_channel_setup_queue_map(pf, &ctxt, ch);
6128
6129         /* Now time to create VSI */
6130         ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
6131         if (ret) {
6132                 dev_info(&pf->pdev->dev,
6133                          "add new vsi failed, err %s aq_err %s\n",
6134                          i40e_stat_str(&pf->hw, ret),
6135                          i40e_aq_str(&pf->hw,
6136                                      pf->hw.aq.asq_last_status));
6137                 return -ENOENT;
6138         }
6139
6140         /* Success, update channel, set enabled_tc only if the channel
6141          * is not a macvlan
6142          */
6143         ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
6144         ch->seid = ctxt.seid;
6145         ch->vsi_number = ctxt.vsi_number;
6146         ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
6147
6148         /* copy just the sections touched not the entire info
6149          * since not all sections are valid as returned by
6150          * update vsi params
6151          */
6152         ch->info.mapping_flags = ctxt.info.mapping_flags;
6153         memcpy(&ch->info.queue_mapping,
6154                &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
6155         memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
6156                sizeof(ctxt.info.tc_mapping));
6157
6158         return 0;
6159 }
6160
6161 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
6162                                   u8 *bw_share)
6163 {
6164         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
6165         i40e_status ret;
6166         int i;
6167
6168         memset(&bw_data, 0, sizeof(bw_data));
6169         bw_data.tc_valid_bits = ch->enabled_tc;
6170         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6171                 bw_data.tc_bw_credits[i] = bw_share[i];
6172
6173         ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
6174                                        &bw_data, NULL);
6175         if (ret) {
6176                 dev_info(&vsi->back->pdev->dev,
6177                          "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
6178                          vsi->back->hw.aq.asq_last_status, ch->seid);
6179                 return -EINVAL;
6180         }
6181
6182         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6183                 ch->info.qs_handle[i] = bw_data.qs_handles[i];
6184
6185         return 0;
6186 }
6187
6188 /**
6189  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6190  * @pf: ptr to PF device
6191  * @vsi: the VSI being setup
6192  * @ch: ptr to channel structure
6193  *
6194  * Configure TX rings associated with channel (VSI) since queues are being
6195  * from parent VSI.
6196  **/
6197 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6198                                        struct i40e_vsi *vsi,
6199                                        struct i40e_channel *ch)
6200 {
6201         i40e_status ret;
6202         int i;
6203         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6204
6205         /* Enable ETS TCs with equal BW Share for now across all VSIs */
6206         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6207                 if (ch->enabled_tc & BIT(i))
6208                         bw_share[i] = 1;
6209         }
6210
6211         /* configure BW for new VSI */
6212         ret = i40e_channel_config_bw(vsi, ch, bw_share);
6213         if (ret) {
6214                 dev_info(&vsi->back->pdev->dev,
6215                          "Failed configuring TC map %d for channel (seid %u)\n",
6216                          ch->enabled_tc, ch->seid);
6217                 return ret;
6218         }
6219
6220         for (i = 0; i < ch->num_queue_pairs; i++) {
6221                 struct i40e_ring *tx_ring, *rx_ring;
6222                 u16 pf_q;
6223
6224                 pf_q = ch->base_queue + i;
6225
6226                 /* Get to TX ring ptr of main VSI, for re-setup TX queue
6227                  * context
6228                  */
6229                 tx_ring = vsi->tx_rings[pf_q];
6230                 tx_ring->ch = ch;
6231
6232                 /* Get the RX ring ptr */
6233                 rx_ring = vsi->rx_rings[pf_q];
6234                 rx_ring->ch = ch;
6235         }
6236
6237         return 0;
6238 }
6239
6240 /**
6241  * i40e_setup_hw_channel - setup new channel
6242  * @pf: ptr to PF device
6243  * @vsi: the VSI being setup
6244  * @ch: ptr to channel structure
6245  * @uplink_seid: underlying HW switching element (VEB) ID
6246  * @type: type of channel to be created (VMDq2/VF)
6247  *
6248  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6249  * and configures TX rings accordingly
6250  **/
6251 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6252                                         struct i40e_vsi *vsi,
6253                                         struct i40e_channel *ch,
6254                                         u16 uplink_seid, u8 type)
6255 {
6256         int ret;
6257
6258         ch->initialized = false;
6259         ch->base_queue = vsi->next_base_queue;
6260         ch->type = type;
6261
6262         /* Proceed with creation of channel (VMDq2) VSI */
6263         ret = i40e_add_channel(pf, uplink_seid, ch);
6264         if (ret) {
6265                 dev_info(&pf->pdev->dev,
6266                          "failed to add_channel using uplink_seid %u\n",
6267                          uplink_seid);
6268                 return ret;
6269         }
6270
6271         /* Mark the successful creation of channel */
6272         ch->initialized = true;
6273
6274         /* Reconfigure TX queues using QTX_CTL register */
6275         ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6276         if (ret) {
6277                 dev_info(&pf->pdev->dev,
6278                          "failed to configure TX rings for channel %u\n",
6279                          ch->seid);
6280                 return ret;
6281         }
6282
6283         /* update 'next_base_queue' */
6284         vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6285         dev_dbg(&pf->pdev->dev,
6286                 "Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6287                 ch->seid, ch->vsi_number, ch->stat_counter_idx,
6288                 ch->num_queue_pairs,
6289                 vsi->next_base_queue);
6290         return ret;
6291 }
6292
6293 /**
6294  * i40e_setup_channel - setup new channel using uplink element
6295  * @pf: ptr to PF device
6296  * @vsi: pointer to the VSI to set up the channel within
6297  * @ch: ptr to channel structure
6298  *
6299  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6300  * and uplink switching element (uplink_seid)
6301  **/
6302 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6303                                struct i40e_channel *ch)
6304 {
6305         u8 vsi_type;
6306         u16 seid;
6307         int ret;
6308
6309         if (vsi->type == I40E_VSI_MAIN) {
6310                 vsi_type = I40E_VSI_VMDQ2;
6311         } else {
6312                 dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6313                         vsi->type);
6314                 return false;
6315         }
6316
6317         /* underlying switching element */
6318         seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6319
6320         /* create channel (VSI), configure TX rings */
6321         ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6322         if (ret) {
6323                 dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6324                 return false;
6325         }
6326
6327         return ch->initialized ? true : false;
6328 }
6329
6330 /**
6331  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6332  * @vsi: ptr to VSI which has PF backing
6333  *
6334  * Sets up switch mode correctly if it needs to be changed and perform
6335  * what are allowed modes.
6336  **/
6337 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6338 {
6339         u8 mode;
6340         struct i40e_pf *pf = vsi->back;
6341         struct i40e_hw *hw = &pf->hw;
6342         int ret;
6343
6344         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6345         if (ret)
6346                 return -EINVAL;
6347
6348         if (hw->dev_caps.switch_mode) {
6349                 /* if switch mode is set, support mode2 (non-tunneled for
6350                  * cloud filter) for now
6351                  */
6352                 u32 switch_mode = hw->dev_caps.switch_mode &
6353                                   I40E_SWITCH_MODE_MASK;
6354                 if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6355                         if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6356                                 return 0;
6357                         dev_err(&pf->pdev->dev,
6358                                 "Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6359                                 hw->dev_caps.switch_mode);
6360                         return -EINVAL;
6361                 }
6362         }
6363
6364         /* Set Bit 7 to be valid */
6365         mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6366
6367         /* Set L4type for TCP support */
6368         mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6369
6370         /* Set cloud filter mode */
6371         mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6372
6373         /* Prep mode field for set_switch_config */
6374         ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6375                                         pf->last_sw_conf_valid_flags,
6376                                         mode, NULL);
6377         if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6378                 dev_err(&pf->pdev->dev,
6379                         "couldn't set switch config bits, err %s aq_err %s\n",
6380                         i40e_stat_str(hw, ret),
6381                         i40e_aq_str(hw,
6382                                     hw->aq.asq_last_status));
6383
6384         return ret;
6385 }
6386
6387 /**
6388  * i40e_create_queue_channel - function to create channel
6389  * @vsi: VSI to be configured
6390  * @ch: ptr to channel (it contains channel specific params)
6391  *
6392  * This function creates channel (VSI) using num_queues specified by user,
6393  * reconfigs RSS if needed.
6394  **/
6395 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6396                               struct i40e_channel *ch)
6397 {
6398         struct i40e_pf *pf = vsi->back;
6399         bool reconfig_rss;
6400         int err;
6401
6402         if (!ch)
6403                 return -EINVAL;
6404
6405         if (!ch->num_queue_pairs) {
6406                 dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6407                         ch->num_queue_pairs);
6408                 return -EINVAL;
6409         }
6410
6411         /* validate user requested num_queues for channel */
6412         err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6413                                        &reconfig_rss);
6414         if (err) {
6415                 dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6416                          ch->num_queue_pairs);
6417                 return -EINVAL;
6418         }
6419
6420         /* By default we are in VEPA mode, if this is the first VF/VMDq
6421          * VSI to be added switch to VEB mode.
6422          */
6423
6424         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6425                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6426
6427                 if (vsi->type == I40E_VSI_MAIN) {
6428                         if (i40e_is_tc_mqprio_enabled(pf))
6429                                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
6430                         else
6431                                 i40e_do_reset_safe(pf, I40E_PF_RESET_FLAG);
6432                 }
6433                 /* now onwards for main VSI, number of queues will be value
6434                  * of TC0's queue count
6435                  */
6436         }
6437
6438         /* By this time, vsi->cnt_q_avail shall be set to non-zero and
6439          * it should be more than num_queues
6440          */
6441         if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6442                 dev_dbg(&pf->pdev->dev,
6443                         "Error: cnt_q_avail (%u) less than num_queues %d\n",
6444                         vsi->cnt_q_avail, ch->num_queue_pairs);
6445                 return -EINVAL;
6446         }
6447
6448         /* reconfig_rss only if vsi type is MAIN_VSI */
6449         if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6450                 err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6451                 if (err) {
6452                         dev_info(&pf->pdev->dev,
6453                                  "Error: unable to reconfig rss for num_queues (%u)\n",
6454                                  ch->num_queue_pairs);
6455                         return -EINVAL;
6456                 }
6457         }
6458
6459         if (!i40e_setup_channel(pf, vsi, ch)) {
6460                 dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6461                 return -EINVAL;
6462         }
6463
6464         dev_info(&pf->pdev->dev,
6465                  "Setup channel (id:%u) utilizing num_queues %d\n",
6466                  ch->seid, ch->num_queue_pairs);
6467
6468         /* configure VSI for BW limit */
6469         if (ch->max_tx_rate) {
6470                 u64 credits = ch->max_tx_rate;
6471
6472                 if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6473                         return -EINVAL;
6474
6475                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
6476                 dev_dbg(&pf->pdev->dev,
6477                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6478                         ch->max_tx_rate,
6479                         credits,
6480                         ch->seid);
6481         }
6482
6483         /* in case of VF, this will be main SRIOV VSI */
6484         ch->parent_vsi = vsi;
6485
6486         /* and update main_vsi's count for queue_available to use */
6487         vsi->cnt_q_avail -= ch->num_queue_pairs;
6488
6489         return 0;
6490 }
6491
6492 /**
6493  * i40e_configure_queue_channels - Add queue channel for the given TCs
6494  * @vsi: VSI to be configured
6495  *
6496  * Configures queue channel mapping to the given TCs
6497  **/
6498 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6499 {
6500         struct i40e_channel *ch;
6501         u64 max_rate = 0;
6502         int ret = 0, i;
6503
6504         /* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6505         vsi->tc_seid_map[0] = vsi->seid;
6506         for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6507                 if (vsi->tc_config.enabled_tc & BIT(i)) {
6508                         ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6509                         if (!ch) {
6510                                 ret = -ENOMEM;
6511                                 goto err_free;
6512                         }
6513
6514                         INIT_LIST_HEAD(&ch->list);
6515                         ch->num_queue_pairs =
6516                                 vsi->tc_config.tc_info[i].qcount;
6517                         ch->base_queue =
6518                                 vsi->tc_config.tc_info[i].qoffset;
6519
6520                         /* Bandwidth limit through tc interface is in bytes/s,
6521                          * change to Mbit/s
6522                          */
6523                         max_rate = vsi->mqprio_qopt.max_rate[i];
6524                         do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6525                         ch->max_tx_rate = max_rate;
6526
6527                         list_add_tail(&ch->list, &vsi->ch_list);
6528
6529                         ret = i40e_create_queue_channel(vsi, ch);
6530                         if (ret) {
6531                                 dev_err(&vsi->back->pdev->dev,
6532                                         "Failed creating queue channel with TC%d: queues %d\n",
6533                                         i, ch->num_queue_pairs);
6534                                 goto err_free;
6535                         }
6536                         vsi->tc_seid_map[i] = ch->seid;
6537                 }
6538         }
6539
6540         /* reset to reconfigure TX queue contexts */
6541         i40e_do_reset(vsi->back, I40E_PF_RESET_FLAG, true);
6542         return ret;
6543
6544 err_free:
6545         i40e_remove_queue_channels(vsi);
6546         return ret;
6547 }
6548
6549 /**
6550  * i40e_veb_config_tc - Configure TCs for given VEB
6551  * @veb: given VEB
6552  * @enabled_tc: TC bitmap
6553  *
6554  * Configures given TC bitmap for VEB (switching) element
6555  **/
6556 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6557 {
6558         struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6559         struct i40e_pf *pf = veb->pf;
6560         int ret = 0;
6561         int i;
6562
6563         /* No TCs or already enabled TCs just return */
6564         if (!enabled_tc || veb->enabled_tc == enabled_tc)
6565                 return ret;
6566
6567         bw_data.tc_valid_bits = enabled_tc;
6568         /* bw_data.absolute_credits is not set (relative) */
6569
6570         /* Enable ETS TCs with equal BW Share for now */
6571         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6572                 if (enabled_tc & BIT(i))
6573                         bw_data.tc_bw_share_credits[i] = 1;
6574         }
6575
6576         ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6577                                                    &bw_data, NULL);
6578         if (ret) {
6579                 dev_info(&pf->pdev->dev,
6580                          "VEB bw config failed, err %s aq_err %s\n",
6581                          i40e_stat_str(&pf->hw, ret),
6582                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6583                 goto out;
6584         }
6585
6586         /* Update the BW information */
6587         ret = i40e_veb_get_bw_info(veb);
6588         if (ret) {
6589                 dev_info(&pf->pdev->dev,
6590                          "Failed getting veb bw config, err %s aq_err %s\n",
6591                          i40e_stat_str(&pf->hw, ret),
6592                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6593         }
6594
6595 out:
6596         return ret;
6597 }
6598
6599 #ifdef CONFIG_I40E_DCB
6600 /**
6601  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6602  * @pf: PF struct
6603  *
6604  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6605  * the caller would've quiesce all the VSIs before calling
6606  * this function
6607  **/
6608 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6609 {
6610         u8 tc_map = 0;
6611         int ret;
6612         u8 v;
6613
6614         /* Enable the TCs available on PF to all VEBs */
6615         tc_map = i40e_pf_get_tc_map(pf);
6616         if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6617                 return;
6618
6619         for (v = 0; v < I40E_MAX_VEB; v++) {
6620                 if (!pf->veb[v])
6621                         continue;
6622                 ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6623                 if (ret) {
6624                         dev_info(&pf->pdev->dev,
6625                                  "Failed configuring TC for VEB seid=%d\n",
6626                                  pf->veb[v]->seid);
6627                         /* Will try to configure as many components */
6628                 }
6629         }
6630
6631         /* Update each VSI */
6632         for (v = 0; v < pf->num_alloc_vsi; v++) {
6633                 if (!pf->vsi[v])
6634                         continue;
6635
6636                 /* - Enable all TCs for the LAN VSI
6637                  * - For all others keep them at TC0 for now
6638                  */
6639                 if (v == pf->lan_vsi)
6640                         tc_map = i40e_pf_get_tc_map(pf);
6641                 else
6642                         tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6643
6644                 ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6645                 if (ret) {
6646                         dev_info(&pf->pdev->dev,
6647                                  "Failed configuring TC for VSI seid=%d\n",
6648                                  pf->vsi[v]->seid);
6649                         /* Will try to configure as many components */
6650                 } else {
6651                         /* Re-configure VSI vectors based on updated TC map */
6652                         i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6653                         if (pf->vsi[v]->netdev)
6654                                 i40e_dcbnl_set_all(pf->vsi[v]);
6655                 }
6656         }
6657 }
6658
6659 /**
6660  * i40e_resume_port_tx - Resume port Tx
6661  * @pf: PF struct
6662  *
6663  * Resume a port's Tx and issue a PF reset in case of failure to
6664  * resume.
6665  **/
6666 static int i40e_resume_port_tx(struct i40e_pf *pf)
6667 {
6668         struct i40e_hw *hw = &pf->hw;
6669         int ret;
6670
6671         ret = i40e_aq_resume_port_tx(hw, NULL);
6672         if (ret) {
6673                 dev_info(&pf->pdev->dev,
6674                          "Resume Port Tx failed, err %s aq_err %s\n",
6675                           i40e_stat_str(&pf->hw, ret),
6676                           i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6677                 /* Schedule PF reset to recover */
6678                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6679                 i40e_service_event_schedule(pf);
6680         }
6681
6682         return ret;
6683 }
6684
6685 /**
6686  * i40e_suspend_port_tx - Suspend port Tx
6687  * @pf: PF struct
6688  *
6689  * Suspend a port's Tx and issue a PF reset in case of failure.
6690  **/
6691 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6692 {
6693         struct i40e_hw *hw = &pf->hw;
6694         int ret;
6695
6696         ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6697         if (ret) {
6698                 dev_info(&pf->pdev->dev,
6699                          "Suspend Port Tx failed, err %s aq_err %s\n",
6700                          i40e_stat_str(&pf->hw, ret),
6701                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6702                 /* Schedule PF reset to recover */
6703                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6704                 i40e_service_event_schedule(pf);
6705         }
6706
6707         return ret;
6708 }
6709
6710 /**
6711  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6712  * @pf: PF being configured
6713  * @new_cfg: New DCBX configuration
6714  *
6715  * Program DCB settings into HW and reconfigure VEB/VSIs on
6716  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6717  **/
6718 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6719                                   struct i40e_dcbx_config *new_cfg)
6720 {
6721         struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6722         int ret;
6723
6724         /* Check if need reconfiguration */
6725         if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6726                 dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6727                 return 0;
6728         }
6729
6730         /* Config change disable all VSIs */
6731         i40e_pf_quiesce_all_vsi(pf);
6732
6733         /* Copy the new config to the current config */
6734         *old_cfg = *new_cfg;
6735         old_cfg->etsrec = old_cfg->etscfg;
6736         ret = i40e_set_dcb_config(&pf->hw);
6737         if (ret) {
6738                 dev_info(&pf->pdev->dev,
6739                          "Set DCB Config failed, err %s aq_err %s\n",
6740                          i40e_stat_str(&pf->hw, ret),
6741                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6742                 goto out;
6743         }
6744
6745         /* Changes in configuration update VEB/VSI */
6746         i40e_dcb_reconfigure(pf);
6747 out:
6748         /* In case of reset do not try to resume anything */
6749         if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6750                 /* Re-start the VSIs if disabled */
6751                 ret = i40e_resume_port_tx(pf);
6752                 /* In case of error no point in resuming VSIs */
6753                 if (ret)
6754                         goto err;
6755                 i40e_pf_unquiesce_all_vsi(pf);
6756         }
6757 err:
6758         return ret;
6759 }
6760
6761 /**
6762  * i40e_hw_dcb_config - Program new DCBX settings into HW
6763  * @pf: PF being configured
6764  * @new_cfg: New DCBX configuration
6765  *
6766  * Program DCB settings into HW and reconfigure VEB/VSIs on
6767  * given PF
6768  **/
6769 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6770 {
6771         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6772         u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6773         u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6774         struct i40e_dcbx_config *old_cfg;
6775         u8 mode[I40E_MAX_TRAFFIC_CLASS];
6776         struct i40e_rx_pb_config pb_cfg;
6777         struct i40e_hw *hw = &pf->hw;
6778         u8 num_ports = hw->num_ports;
6779         bool need_reconfig;
6780         int ret = -EINVAL;
6781         u8 lltc_map = 0;
6782         u8 tc_map = 0;
6783         u8 new_numtc;
6784         u8 i;
6785
6786         dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6787         /* Un-pack information to Program ETS HW via shared API
6788          * numtc, tcmap
6789          * LLTC map
6790          * ETS/NON-ETS arbiter mode
6791          * max exponent (credit refills)
6792          * Total number of ports
6793          * PFC priority bit-map
6794          * Priority Table
6795          * BW % per TC
6796          * Arbiter mode between UPs sharing same TC
6797          * TSA table (ETS or non-ETS)
6798          * EEE enabled or not
6799          * MFS TC table
6800          */
6801
6802         new_numtc = i40e_dcb_get_num_tc(new_cfg);
6803
6804         memset(&ets_data, 0, sizeof(ets_data));
6805         for (i = 0; i < new_numtc; i++) {
6806                 tc_map |= BIT(i);
6807                 switch (new_cfg->etscfg.tsatable[i]) {
6808                 case I40E_IEEE_TSA_ETS:
6809                         prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6810                         ets_data.tc_bw_share_credits[i] =
6811                                         new_cfg->etscfg.tcbwtable[i];
6812                         break;
6813                 case I40E_IEEE_TSA_STRICT:
6814                         prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6815                         lltc_map |= BIT(i);
6816                         ets_data.tc_bw_share_credits[i] =
6817                                         I40E_DCB_STRICT_PRIO_CREDITS;
6818                         break;
6819                 default:
6820                         /* Invalid TSA type */
6821                         need_reconfig = false;
6822                         goto out;
6823                 }
6824         }
6825
6826         old_cfg = &hw->local_dcbx_config;
6827         /* Check if need reconfiguration */
6828         need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6829
6830         /* If needed, enable/disable frame tagging, disable all VSIs
6831          * and suspend port tx
6832          */
6833         if (need_reconfig) {
6834                 /* Enable DCB tagging only when more than one TC */
6835                 if (new_numtc > 1)
6836                         pf->flags |= I40E_FLAG_DCB_ENABLED;
6837                 else
6838                         pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6839
6840                 set_bit(__I40E_PORT_SUSPENDED, pf->state);
6841                 /* Reconfiguration needed quiesce all VSIs */
6842                 i40e_pf_quiesce_all_vsi(pf);
6843                 ret = i40e_suspend_port_tx(pf);
6844                 if (ret)
6845                         goto err;
6846         }
6847
6848         /* Configure Port ETS Tx Scheduler */
6849         ets_data.tc_valid_bits = tc_map;
6850         ets_data.tc_strict_priority_flags = lltc_map;
6851         ret = i40e_aq_config_switch_comp_ets
6852                 (hw, pf->mac_seid, &ets_data,
6853                  i40e_aqc_opc_modify_switching_comp_ets, NULL);
6854         if (ret) {
6855                 dev_info(&pf->pdev->dev,
6856                          "Modify Port ETS failed, err %s aq_err %s\n",
6857                          i40e_stat_str(&pf->hw, ret),
6858                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6859                 goto out;
6860         }
6861
6862         /* Configure Rx ETS HW */
6863         memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
6864         i40e_dcb_hw_set_num_tc(hw, new_numtc);
6865         i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
6866                                    I40E_DCB_ARB_MODE_STRICT_PRIORITY,
6867                                    I40E_DCB_DEFAULT_MAX_EXPONENT,
6868                                    lltc_map);
6869         i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
6870         i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
6871                                      prio_type);
6872         i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
6873                                new_cfg->etscfg.prioritytable);
6874         i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
6875
6876         /* Configure Rx Packet Buffers in HW */
6877         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6878                 mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
6879                 mfs_tc[i] += I40E_PACKET_HDR_PAD;
6880         }
6881
6882         i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
6883                                          false, new_cfg->pfc.pfcenable,
6884                                          mfs_tc, &pb_cfg);
6885         i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
6886
6887         /* Update the local Rx Packet buffer config */
6888         pf->pb_cfg = pb_cfg;
6889
6890         /* Inform the FW about changes to DCB configuration */
6891         ret = i40e_aq_dcb_updated(&pf->hw, NULL);
6892         if (ret) {
6893                 dev_info(&pf->pdev->dev,
6894                          "DCB Updated failed, err %s aq_err %s\n",
6895                          i40e_stat_str(&pf->hw, ret),
6896                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6897                 goto out;
6898         }
6899
6900         /* Update the port DCBx configuration */
6901         *old_cfg = *new_cfg;
6902
6903         /* Changes in configuration update VEB/VSI */
6904         i40e_dcb_reconfigure(pf);
6905 out:
6906         /* Re-start the VSIs if disabled */
6907         if (need_reconfig) {
6908                 ret = i40e_resume_port_tx(pf);
6909
6910                 clear_bit(__I40E_PORT_SUSPENDED, pf->state);
6911                 /* In case of error no point in resuming VSIs */
6912                 if (ret)
6913                         goto err;
6914
6915                 /* Wait for the PF's queues to be disabled */
6916                 ret = i40e_pf_wait_queues_disabled(pf);
6917                 if (ret) {
6918                         /* Schedule PF reset to recover */
6919                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6920                         i40e_service_event_schedule(pf);
6921                         goto err;
6922                 } else {
6923                         i40e_pf_unquiesce_all_vsi(pf);
6924                         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
6925                         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
6926                 }
6927                 /* registers are set, lets apply */
6928                 if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
6929                         ret = i40e_hw_set_dcb_config(pf, new_cfg);
6930         }
6931
6932 err:
6933         return ret;
6934 }
6935
6936 /**
6937  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
6938  * @pf: PF being queried
6939  *
6940  * Set default DCB configuration in case DCB is to be done in SW.
6941  **/
6942 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
6943 {
6944         struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
6945         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6946         struct i40e_hw *hw = &pf->hw;
6947         int err;
6948
6949         if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
6950                 /* Update the local cached instance with TC0 ETS */
6951                 memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
6952                 pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
6953                 pf->tmp_cfg.etscfg.maxtcs = 0;
6954                 pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
6955                 pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
6956                 pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
6957                 pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
6958                 /* FW needs one App to configure HW */
6959                 pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
6960                 pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
6961                 pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
6962                 pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
6963
6964                 return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
6965         }
6966
6967         memset(&ets_data, 0, sizeof(ets_data));
6968         ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
6969         ets_data.tc_strict_priority_flags = 0; /* ETS */
6970         ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
6971
6972         /* Enable ETS on the Physical port */
6973         err = i40e_aq_config_switch_comp_ets
6974                 (hw, pf->mac_seid, &ets_data,
6975                  i40e_aqc_opc_enable_switching_comp_ets, NULL);
6976         if (err) {
6977                 dev_info(&pf->pdev->dev,
6978                          "Enable Port ETS failed, err %s aq_err %s\n",
6979                          i40e_stat_str(&pf->hw, err),
6980                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6981                 err = -ENOENT;
6982                 goto out;
6983         }
6984
6985         /* Update the local cached instance with TC0 ETS */
6986         dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
6987         dcb_cfg->etscfg.cbs = 0;
6988         dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
6989         dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
6990
6991 out:
6992         return err;
6993 }
6994
6995 /**
6996  * i40e_init_pf_dcb - Initialize DCB configuration
6997  * @pf: PF being configured
6998  *
6999  * Query the current DCB configuration and cache it
7000  * in the hardware structure
7001  **/
7002 static int i40e_init_pf_dcb(struct i40e_pf *pf)
7003 {
7004         struct i40e_hw *hw = &pf->hw;
7005         int err;
7006
7007         /* Do not enable DCB for SW1 and SW2 images even if the FW is capable
7008          * Also do not enable DCBx if FW LLDP agent is disabled
7009          */
7010         if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
7011                 dev_info(&pf->pdev->dev, "DCB is not supported.\n");
7012                 err = I40E_NOT_SUPPORTED;
7013                 goto out;
7014         }
7015         if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
7016                 dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
7017                 err = i40e_dcb_sw_default_config(pf);
7018                 if (err) {
7019                         dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
7020                         goto out;
7021                 }
7022                 dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
7023                 pf->dcbx_cap = DCB_CAP_DCBX_HOST |
7024                                DCB_CAP_DCBX_VER_IEEE;
7025                 /* at init capable but disabled */
7026                 pf->flags |= I40E_FLAG_DCB_CAPABLE;
7027                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7028                 goto out;
7029         }
7030         err = i40e_init_dcb(hw, true);
7031         if (!err) {
7032                 /* Device/Function is not DCBX capable */
7033                 if ((!hw->func_caps.dcb) ||
7034                     (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
7035                         dev_info(&pf->pdev->dev,
7036                                  "DCBX offload is not supported or is disabled for this PF.\n");
7037                 } else {
7038                         /* When status is not DISABLED then DCBX in FW */
7039                         pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
7040                                        DCB_CAP_DCBX_VER_IEEE;
7041
7042                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
7043                         /* Enable DCB tagging only when more than one TC
7044                          * or explicitly disable if only one TC
7045                          */
7046                         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
7047                                 pf->flags |= I40E_FLAG_DCB_ENABLED;
7048                         else
7049                                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7050                         dev_dbg(&pf->pdev->dev,
7051                                 "DCBX offload is supported for this PF.\n");
7052                 }
7053         } else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
7054                 dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
7055                 pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
7056         } else {
7057                 dev_info(&pf->pdev->dev,
7058                          "Query for DCB configuration failed, err %s aq_err %s\n",
7059                          i40e_stat_str(&pf->hw, err),
7060                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7061         }
7062
7063 out:
7064         return err;
7065 }
7066 #endif /* CONFIG_I40E_DCB */
7067
7068 /**
7069  * i40e_print_link_message - print link up or down
7070  * @vsi: the VSI for which link needs a message
7071  * @isup: true of link is up, false otherwise
7072  */
7073 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
7074 {
7075         enum i40e_aq_link_speed new_speed;
7076         struct i40e_pf *pf = vsi->back;
7077         char *speed = "Unknown";
7078         char *fc = "Unknown";
7079         char *fec = "";
7080         char *req_fec = "";
7081         char *an = "";
7082
7083         if (isup)
7084                 new_speed = pf->hw.phy.link_info.link_speed;
7085         else
7086                 new_speed = I40E_LINK_SPEED_UNKNOWN;
7087
7088         if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
7089                 return;
7090         vsi->current_isup = isup;
7091         vsi->current_speed = new_speed;
7092         if (!isup) {
7093                 netdev_info(vsi->netdev, "NIC Link is Down\n");
7094                 return;
7095         }
7096
7097         /* Warn user if link speed on NPAR enabled partition is not at
7098          * least 10GB
7099          */
7100         if (pf->hw.func_caps.npar_enable &&
7101             (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
7102              pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
7103                 netdev_warn(vsi->netdev,
7104                             "The partition detected link speed that is less than 10Gbps\n");
7105
7106         switch (pf->hw.phy.link_info.link_speed) {
7107         case I40E_LINK_SPEED_40GB:
7108                 speed = "40 G";
7109                 break;
7110         case I40E_LINK_SPEED_20GB:
7111                 speed = "20 G";
7112                 break;
7113         case I40E_LINK_SPEED_25GB:
7114                 speed = "25 G";
7115                 break;
7116         case I40E_LINK_SPEED_10GB:
7117                 speed = "10 G";
7118                 break;
7119         case I40E_LINK_SPEED_5GB:
7120                 speed = "5 G";
7121                 break;
7122         case I40E_LINK_SPEED_2_5GB:
7123                 speed = "2.5 G";
7124                 break;
7125         case I40E_LINK_SPEED_1GB:
7126                 speed = "1000 M";
7127                 break;
7128         case I40E_LINK_SPEED_100MB:
7129                 speed = "100 M";
7130                 break;
7131         default:
7132                 break;
7133         }
7134
7135         switch (pf->hw.fc.current_mode) {
7136         case I40E_FC_FULL:
7137                 fc = "RX/TX";
7138                 break;
7139         case I40E_FC_TX_PAUSE:
7140                 fc = "TX";
7141                 break;
7142         case I40E_FC_RX_PAUSE:
7143                 fc = "RX";
7144                 break;
7145         default:
7146                 fc = "None";
7147                 break;
7148         }
7149
7150         if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
7151                 req_fec = "None";
7152                 fec = "None";
7153                 an = "False";
7154
7155                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7156                         an = "True";
7157
7158                 if (pf->hw.phy.link_info.fec_info &
7159                     I40E_AQ_CONFIG_FEC_KR_ENA)
7160                         fec = "CL74 FC-FEC/BASE-R";
7161                 else if (pf->hw.phy.link_info.fec_info &
7162                          I40E_AQ_CONFIG_FEC_RS_ENA)
7163                         fec = "CL108 RS-FEC";
7164
7165                 /* 'CL108 RS-FEC' should be displayed when RS is requested, or
7166                  * both RS and FC are requested
7167                  */
7168                 if (vsi->back->hw.phy.link_info.req_fec_info &
7169                     (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
7170                         if (vsi->back->hw.phy.link_info.req_fec_info &
7171                             I40E_AQ_REQUEST_FEC_RS)
7172                                 req_fec = "CL108 RS-FEC";
7173                         else
7174                                 req_fec = "CL74 FC-FEC/BASE-R";
7175                 }
7176                 netdev_info(vsi->netdev,
7177                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7178                             speed, req_fec, fec, an, fc);
7179         } else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7180                 req_fec = "None";
7181                 fec = "None";
7182                 an = "False";
7183
7184                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7185                         an = "True";
7186
7187                 if (pf->hw.phy.link_info.fec_info &
7188                     I40E_AQ_CONFIG_FEC_KR_ENA)
7189                         fec = "CL74 FC-FEC/BASE-R";
7190
7191                 if (pf->hw.phy.link_info.req_fec_info &
7192                     I40E_AQ_REQUEST_FEC_KR)
7193                         req_fec = "CL74 FC-FEC/BASE-R";
7194
7195                 netdev_info(vsi->netdev,
7196                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7197                             speed, req_fec, fec, an, fc);
7198         } else {
7199                 netdev_info(vsi->netdev,
7200                             "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7201                             speed, fc);
7202         }
7203
7204 }
7205
7206 /**
7207  * i40e_up_complete - Finish the last steps of bringing up a connection
7208  * @vsi: the VSI being configured
7209  **/
7210 static int i40e_up_complete(struct i40e_vsi *vsi)
7211 {
7212         struct i40e_pf *pf = vsi->back;
7213         int err;
7214
7215         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7216                 i40e_vsi_configure_msix(vsi);
7217         else
7218                 i40e_configure_msi_and_legacy(vsi);
7219
7220         /* start rings */
7221         err = i40e_vsi_start_rings(vsi);
7222         if (err)
7223                 return err;
7224
7225         clear_bit(__I40E_VSI_DOWN, vsi->state);
7226         i40e_napi_enable_all(vsi);
7227         i40e_vsi_enable_irq(vsi);
7228
7229         if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7230             (vsi->netdev)) {
7231                 i40e_print_link_message(vsi, true);
7232                 netif_tx_start_all_queues(vsi->netdev);
7233                 netif_carrier_on(vsi->netdev);
7234         }
7235
7236         /* replay FDIR SB filters */
7237         if (vsi->type == I40E_VSI_FDIR) {
7238                 /* reset fd counters */
7239                 pf->fd_add_err = 0;
7240                 pf->fd_atr_cnt = 0;
7241                 i40e_fdir_filter_restore(vsi);
7242         }
7243
7244         /* On the next run of the service_task, notify any clients of the new
7245          * opened netdev
7246          */
7247         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7248         i40e_service_event_schedule(pf);
7249
7250         return 0;
7251 }
7252
7253 /**
7254  * i40e_vsi_reinit_locked - Reset the VSI
7255  * @vsi: the VSI being configured
7256  *
7257  * Rebuild the ring structs after some configuration
7258  * has changed, e.g. MTU size.
7259  **/
7260 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7261 {
7262         struct i40e_pf *pf = vsi->back;
7263
7264         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7265                 usleep_range(1000, 2000);
7266         i40e_down(vsi);
7267
7268         i40e_up(vsi);
7269         clear_bit(__I40E_CONFIG_BUSY, pf->state);
7270 }
7271
7272 /**
7273  * i40e_force_link_state - Force the link status
7274  * @pf: board private structure
7275  * @is_up: whether the link state should be forced up or down
7276  **/
7277 static i40e_status i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7278 {
7279         struct i40e_aq_get_phy_abilities_resp abilities;
7280         struct i40e_aq_set_phy_config config = {0};
7281         bool non_zero_phy_type = is_up;
7282         struct i40e_hw *hw = &pf->hw;
7283         i40e_status err;
7284         u64 mask;
7285         u8 speed;
7286
7287         /* Card might've been put in an unstable state by other drivers
7288          * and applications, which causes incorrect speed values being
7289          * set on startup. In order to clear speed registers, we call
7290          * get_phy_capabilities twice, once to get initial state of
7291          * available speeds, and once to get current PHY config.
7292          */
7293         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7294                                            NULL);
7295         if (err) {
7296                 dev_err(&pf->pdev->dev,
7297                         "failed to get phy cap., ret =  %s last_status =  %s\n",
7298                         i40e_stat_str(hw, err),
7299                         i40e_aq_str(hw, hw->aq.asq_last_status));
7300                 return err;
7301         }
7302         speed = abilities.link_speed;
7303
7304         /* Get the current phy config */
7305         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7306                                            NULL);
7307         if (err) {
7308                 dev_err(&pf->pdev->dev,
7309                         "failed to get phy cap., ret =  %s last_status =  %s\n",
7310                         i40e_stat_str(hw, err),
7311                         i40e_aq_str(hw, hw->aq.asq_last_status));
7312                 return err;
7313         }
7314
7315         /* If link needs to go up, but was not forced to go down,
7316          * and its speed values are OK, no need for a flap
7317          * if non_zero_phy_type was set, still need to force up
7318          */
7319         if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7320                 non_zero_phy_type = true;
7321         else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7322                 return I40E_SUCCESS;
7323
7324         /* To force link we need to set bits for all supported PHY types,
7325          * but there are now more than 32, so we need to split the bitmap
7326          * across two fields.
7327          */
7328         mask = I40E_PHY_TYPES_BITMASK;
7329         config.phy_type =
7330                 non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7331         config.phy_type_ext =
7332                 non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7333         /* Copy the old settings, except of phy_type */
7334         config.abilities = abilities.abilities;
7335         if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7336                 if (is_up)
7337                         config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7338                 else
7339                         config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7340         }
7341         if (abilities.link_speed != 0)
7342                 config.link_speed = abilities.link_speed;
7343         else
7344                 config.link_speed = speed;
7345         config.eee_capability = abilities.eee_capability;
7346         config.eeer = abilities.eeer_val;
7347         config.low_power_ctrl = abilities.d3_lpan;
7348         config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7349                             I40E_AQ_PHY_FEC_CONFIG_MASK;
7350         err = i40e_aq_set_phy_config(hw, &config, NULL);
7351
7352         if (err) {
7353                 dev_err(&pf->pdev->dev,
7354                         "set phy config ret =  %s last_status =  %s\n",
7355                         i40e_stat_str(&pf->hw, err),
7356                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7357                 return err;
7358         }
7359
7360         /* Update the link info */
7361         err = i40e_update_link_info(hw);
7362         if (err) {
7363                 /* Wait a little bit (on 40G cards it sometimes takes a really
7364                  * long time for link to come back from the atomic reset)
7365                  * and try once more
7366                  */
7367                 msleep(1000);
7368                 i40e_update_link_info(hw);
7369         }
7370
7371         i40e_aq_set_link_restart_an(hw, is_up, NULL);
7372
7373         return I40E_SUCCESS;
7374 }
7375
7376 /**
7377  * i40e_up - Bring the connection back up after being down
7378  * @vsi: the VSI being configured
7379  **/
7380 int i40e_up(struct i40e_vsi *vsi)
7381 {
7382         int err;
7383
7384         if (vsi->type == I40E_VSI_MAIN &&
7385             (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7386              vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7387                 i40e_force_link_state(vsi->back, true);
7388
7389         err = i40e_vsi_configure(vsi);
7390         if (!err)
7391                 err = i40e_up_complete(vsi);
7392
7393         return err;
7394 }
7395
7396 /**
7397  * i40e_down - Shutdown the connection processing
7398  * @vsi: the VSI being stopped
7399  **/
7400 void i40e_down(struct i40e_vsi *vsi)
7401 {
7402         int i;
7403
7404         /* It is assumed that the caller of this function
7405          * sets the vsi->state __I40E_VSI_DOWN bit.
7406          */
7407         if (vsi->netdev) {
7408                 netif_carrier_off(vsi->netdev);
7409                 netif_tx_disable(vsi->netdev);
7410         }
7411         i40e_vsi_disable_irq(vsi);
7412         i40e_vsi_stop_rings(vsi);
7413         if (vsi->type == I40E_VSI_MAIN &&
7414            (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7415             vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7416                 i40e_force_link_state(vsi->back, false);
7417         i40e_napi_disable_all(vsi);
7418
7419         for (i = 0; i < vsi->num_queue_pairs; i++) {
7420                 i40e_clean_tx_ring(vsi->tx_rings[i]);
7421                 if (i40e_enabled_xdp_vsi(vsi)) {
7422                         /* Make sure that in-progress ndo_xdp_xmit and
7423                          * ndo_xsk_wakeup calls are completed.
7424                          */
7425                         synchronize_rcu();
7426                         i40e_clean_tx_ring(vsi->xdp_rings[i]);
7427                 }
7428                 i40e_clean_rx_ring(vsi->rx_rings[i]);
7429         }
7430
7431 }
7432
7433 /**
7434  * i40e_validate_mqprio_qopt- validate queue mapping info
7435  * @vsi: the VSI being configured
7436  * @mqprio_qopt: queue parametrs
7437  **/
7438 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7439                                      struct tc_mqprio_qopt_offload *mqprio_qopt)
7440 {
7441         u64 sum_max_rate = 0;
7442         u64 max_rate = 0;
7443         int i;
7444
7445         if (mqprio_qopt->qopt.offset[0] != 0 ||
7446             mqprio_qopt->qopt.num_tc < 1 ||
7447             mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7448                 return -EINVAL;
7449         for (i = 0; ; i++) {
7450                 if (!mqprio_qopt->qopt.count[i])
7451                         return -EINVAL;
7452                 if (mqprio_qopt->min_rate[i]) {
7453                         dev_err(&vsi->back->pdev->dev,
7454                                 "Invalid min tx rate (greater than 0) specified\n");
7455                         return -EINVAL;
7456                 }
7457                 max_rate = mqprio_qopt->max_rate[i];
7458                 do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7459                 sum_max_rate += max_rate;
7460
7461                 if (i >= mqprio_qopt->qopt.num_tc - 1)
7462                         break;
7463                 if (mqprio_qopt->qopt.offset[i + 1] !=
7464                     (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7465                         return -EINVAL;
7466         }
7467         if (vsi->num_queue_pairs <
7468             (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7469                 dev_err(&vsi->back->pdev->dev,
7470                         "Failed to create traffic channel, insufficient number of queues.\n");
7471                 return -EINVAL;
7472         }
7473         if (sum_max_rate > i40e_get_link_speed(vsi)) {
7474                 dev_err(&vsi->back->pdev->dev,
7475                         "Invalid max tx rate specified\n");
7476                 return -EINVAL;
7477         }
7478         return 0;
7479 }
7480
7481 /**
7482  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7483  * @vsi: the VSI being configured
7484  **/
7485 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7486 {
7487         u16 qcount;
7488         int i;
7489
7490         /* Only TC0 is enabled */
7491         vsi->tc_config.numtc = 1;
7492         vsi->tc_config.enabled_tc = 1;
7493         qcount = min_t(int, vsi->alloc_queue_pairs,
7494                        i40e_pf_get_max_q_per_tc(vsi->back));
7495         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7496                 /* For the TC that is not enabled set the offset to default
7497                  * queue and allocate one queue for the given TC.
7498                  */
7499                 vsi->tc_config.tc_info[i].qoffset = 0;
7500                 if (i == 0)
7501                         vsi->tc_config.tc_info[i].qcount = qcount;
7502                 else
7503                         vsi->tc_config.tc_info[i].qcount = 1;
7504                 vsi->tc_config.tc_info[i].netdev_tc = 0;
7505         }
7506 }
7507
7508 /**
7509  * i40e_del_macvlan_filter
7510  * @hw: pointer to the HW structure
7511  * @seid: seid of the channel VSI
7512  * @macaddr: the mac address to apply as a filter
7513  * @aq_err: store the admin Q error
7514  *
7515  * This function deletes a mac filter on the channel VSI which serves as the
7516  * macvlan. Returns 0 on success.
7517  **/
7518 static i40e_status i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7519                                            const u8 *macaddr, int *aq_err)
7520 {
7521         struct i40e_aqc_remove_macvlan_element_data element;
7522         i40e_status status;
7523
7524         memset(&element, 0, sizeof(element));
7525         ether_addr_copy(element.mac_addr, macaddr);
7526         element.vlan_tag = 0;
7527         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7528         status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7529         *aq_err = hw->aq.asq_last_status;
7530
7531         return status;
7532 }
7533
7534 /**
7535  * i40e_add_macvlan_filter
7536  * @hw: pointer to the HW structure
7537  * @seid: seid of the channel VSI
7538  * @macaddr: the mac address to apply as a filter
7539  * @aq_err: store the admin Q error
7540  *
7541  * This function adds a mac filter on the channel VSI which serves as the
7542  * macvlan. Returns 0 on success.
7543  **/
7544 static i40e_status i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7545                                            const u8 *macaddr, int *aq_err)
7546 {
7547         struct i40e_aqc_add_macvlan_element_data element;
7548         i40e_status status;
7549         u16 cmd_flags = 0;
7550
7551         ether_addr_copy(element.mac_addr, macaddr);
7552         element.vlan_tag = 0;
7553         element.queue_number = 0;
7554         element.match_method = I40E_AQC_MM_ERR_NO_RES;
7555         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7556         element.flags = cpu_to_le16(cmd_flags);
7557         status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7558         *aq_err = hw->aq.asq_last_status;
7559
7560         return status;
7561 }
7562
7563 /**
7564  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7565  * @vsi: the VSI we want to access
7566  * @ch: the channel we want to access
7567  */
7568 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7569 {
7570         struct i40e_ring *tx_ring, *rx_ring;
7571         u16 pf_q;
7572         int i;
7573
7574         for (i = 0; i < ch->num_queue_pairs; i++) {
7575                 pf_q = ch->base_queue + i;
7576                 tx_ring = vsi->tx_rings[pf_q];
7577                 tx_ring->ch = NULL;
7578                 rx_ring = vsi->rx_rings[pf_q];
7579                 rx_ring->ch = NULL;
7580         }
7581 }
7582
7583 /**
7584  * i40e_free_macvlan_channels
7585  * @vsi: the VSI we want to access
7586  *
7587  * This function frees the Qs of the channel VSI from
7588  * the stack and also deletes the channel VSIs which
7589  * serve as macvlans.
7590  */
7591 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7592 {
7593         struct i40e_channel *ch, *ch_tmp;
7594         int ret;
7595
7596         if (list_empty(&vsi->macvlan_list))
7597                 return;
7598
7599         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7600                 struct i40e_vsi *parent_vsi;
7601
7602                 if (i40e_is_channel_macvlan(ch)) {
7603                         i40e_reset_ch_rings(vsi, ch);
7604                         clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7605                         netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7606                         netdev_set_sb_channel(ch->fwd->netdev, 0);
7607                         kfree(ch->fwd);
7608                         ch->fwd = NULL;
7609                 }
7610
7611                 list_del(&ch->list);
7612                 parent_vsi = ch->parent_vsi;
7613                 if (!parent_vsi || !ch->initialized) {
7614                         kfree(ch);
7615                         continue;
7616                 }
7617
7618                 /* remove the VSI */
7619                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7620                                              NULL);
7621                 if (ret)
7622                         dev_err(&vsi->back->pdev->dev,
7623                                 "unable to remove channel (%d) for parent VSI(%d)\n",
7624                                 ch->seid, parent_vsi->seid);
7625                 kfree(ch);
7626         }
7627         vsi->macvlan_cnt = 0;
7628 }
7629
7630 /**
7631  * i40e_fwd_ring_up - bring the macvlan device up
7632  * @vsi: the VSI we want to access
7633  * @vdev: macvlan netdevice
7634  * @fwd: the private fwd structure
7635  */
7636 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7637                             struct i40e_fwd_adapter *fwd)
7638 {
7639         struct i40e_channel *ch = NULL, *ch_tmp, *iter;
7640         int ret = 0, num_tc = 1,  i, aq_err;
7641         struct i40e_pf *pf = vsi->back;
7642         struct i40e_hw *hw = &pf->hw;
7643
7644         /* Go through the list and find an available channel */
7645         list_for_each_entry_safe(iter, ch_tmp, &vsi->macvlan_list, list) {
7646                 if (!i40e_is_channel_macvlan(iter)) {
7647                         iter->fwd = fwd;
7648                         /* record configuration for macvlan interface in vdev */
7649                         for (i = 0; i < num_tc; i++)
7650                                 netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7651                                                              i,
7652                                                              iter->num_queue_pairs,
7653                                                              iter->base_queue);
7654                         for (i = 0; i < iter->num_queue_pairs; i++) {
7655                                 struct i40e_ring *tx_ring, *rx_ring;
7656                                 u16 pf_q;
7657
7658                                 pf_q = iter->base_queue + i;
7659
7660                                 /* Get to TX ring ptr */
7661                                 tx_ring = vsi->tx_rings[pf_q];
7662                                 tx_ring->ch = iter;
7663
7664                                 /* Get the RX ring ptr */
7665                                 rx_ring = vsi->rx_rings[pf_q];
7666                                 rx_ring->ch = iter;
7667                         }
7668                         ch = iter;
7669                         break;
7670                 }
7671         }
7672
7673         if (!ch)
7674                 return -EINVAL;
7675
7676         /* Guarantee all rings are updated before we update the
7677          * MAC address filter.
7678          */
7679         wmb();
7680
7681         /* Add a mac filter */
7682         ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7683         if (ret) {
7684                 /* if we cannot add the MAC rule then disable the offload */
7685                 macvlan_release_l2fw_offload(vdev);
7686                 for (i = 0; i < ch->num_queue_pairs; i++) {
7687                         struct i40e_ring *rx_ring;
7688                         u16 pf_q;
7689
7690                         pf_q = ch->base_queue + i;
7691                         rx_ring = vsi->rx_rings[pf_q];
7692                         rx_ring->netdev = NULL;
7693                 }
7694                 dev_info(&pf->pdev->dev,
7695                          "Error adding mac filter on macvlan err %s, aq_err %s\n",
7696                           i40e_stat_str(hw, ret),
7697                           i40e_aq_str(hw, aq_err));
7698                 netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7699         }
7700
7701         return ret;
7702 }
7703
7704 /**
7705  * i40e_setup_macvlans - create the channels which will be macvlans
7706  * @vsi: the VSI we want to access
7707  * @macvlan_cnt: no. of macvlans to be setup
7708  * @qcnt: no. of Qs per macvlan
7709  * @vdev: macvlan netdevice
7710  */
7711 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7712                                struct net_device *vdev)
7713 {
7714         struct i40e_pf *pf = vsi->back;
7715         struct i40e_hw *hw = &pf->hw;
7716         struct i40e_vsi_context ctxt;
7717         u16 sections, qmap, num_qps;
7718         struct i40e_channel *ch;
7719         int i, pow, ret = 0;
7720         u8 offset = 0;
7721
7722         if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7723                 return -EINVAL;
7724
7725         num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7726
7727         /* find the next higher power-of-2 of num queue pairs */
7728         pow = fls(roundup_pow_of_two(num_qps) - 1);
7729
7730         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7731                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7732
7733         /* Setup context bits for the main VSI */
7734         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7735         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7736         memset(&ctxt, 0, sizeof(ctxt));
7737         ctxt.seid = vsi->seid;
7738         ctxt.pf_num = vsi->back->hw.pf_id;
7739         ctxt.vf_num = 0;
7740         ctxt.uplink_seid = vsi->uplink_seid;
7741         ctxt.info = vsi->info;
7742         ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7743         ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7744         ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7745         ctxt.info.valid_sections |= cpu_to_le16(sections);
7746
7747         /* Reconfigure RSS for main VSI with new max queue count */
7748         vsi->rss_size = max_t(u16, num_qps, qcnt);
7749         ret = i40e_vsi_config_rss(vsi);
7750         if (ret) {
7751                 dev_info(&pf->pdev->dev,
7752                          "Failed to reconfig RSS for num_queues (%u)\n",
7753                          vsi->rss_size);
7754                 return ret;
7755         }
7756         vsi->reconfig_rss = true;
7757         dev_dbg(&vsi->back->pdev->dev,
7758                 "Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7759         vsi->next_base_queue = num_qps;
7760         vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7761
7762         /* Update the VSI after updating the VSI queue-mapping
7763          * information
7764          */
7765         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7766         if (ret) {
7767                 dev_info(&pf->pdev->dev,
7768                          "Update vsi tc config failed, err %s aq_err %s\n",
7769                          i40e_stat_str(hw, ret),
7770                          i40e_aq_str(hw, hw->aq.asq_last_status));
7771                 return ret;
7772         }
7773         /* update the local VSI info with updated queue map */
7774         i40e_vsi_update_queue_map(vsi, &ctxt);
7775         vsi->info.valid_sections = 0;
7776
7777         /* Create channels for macvlans */
7778         INIT_LIST_HEAD(&vsi->macvlan_list);
7779         for (i = 0; i < macvlan_cnt; i++) {
7780                 ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7781                 if (!ch) {
7782                         ret = -ENOMEM;
7783                         goto err_free;
7784                 }
7785                 INIT_LIST_HEAD(&ch->list);
7786                 ch->num_queue_pairs = qcnt;
7787                 if (!i40e_setup_channel(pf, vsi, ch)) {
7788                         ret = -EINVAL;
7789                         kfree(ch);
7790                         goto err_free;
7791                 }
7792                 ch->parent_vsi = vsi;
7793                 vsi->cnt_q_avail -= ch->num_queue_pairs;
7794                 vsi->macvlan_cnt++;
7795                 list_add_tail(&ch->list, &vsi->macvlan_list);
7796         }
7797
7798         return ret;
7799
7800 err_free:
7801         dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7802         i40e_free_macvlan_channels(vsi);
7803
7804         return ret;
7805 }
7806
7807 /**
7808  * i40e_fwd_add - configure macvlans
7809  * @netdev: net device to configure
7810  * @vdev: macvlan netdevice
7811  **/
7812 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7813 {
7814         struct i40e_netdev_priv *np = netdev_priv(netdev);
7815         u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7816         struct i40e_vsi *vsi = np->vsi;
7817         struct i40e_pf *pf = vsi->back;
7818         struct i40e_fwd_adapter *fwd;
7819         int avail_macvlan, ret;
7820
7821         if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7822                 netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7823                 return ERR_PTR(-EINVAL);
7824         }
7825         if (i40e_is_tc_mqprio_enabled(pf)) {
7826                 netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7827                 return ERR_PTR(-EINVAL);
7828         }
7829         if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7830                 netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7831                 return ERR_PTR(-EINVAL);
7832         }
7833
7834         /* The macvlan device has to be a single Q device so that the
7835          * tc_to_txq field can be reused to pick the tx queue.
7836          */
7837         if (netif_is_multiqueue(vdev))
7838                 return ERR_PTR(-ERANGE);
7839
7840         if (!vsi->macvlan_cnt) {
7841                 /* reserve bit 0 for the pf device */
7842                 set_bit(0, vsi->fwd_bitmask);
7843
7844                 /* Try to reserve as many queues as possible for macvlans. First
7845                  * reserve 3/4th of max vectors, then half, then quarter and
7846                  * calculate Qs per macvlan as you go
7847                  */
7848                 vectors = pf->num_lan_msix;
7849                 if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7850                         /* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7851                         q_per_macvlan = 4;
7852                         macvlan_cnt = (vectors - 32) / 4;
7853                 } else if (vectors <= 64 && vectors > 32) {
7854                         /* allocate 2 Qs per macvlan and 16 Qs to the PF*/
7855                         q_per_macvlan = 2;
7856                         macvlan_cnt = (vectors - 16) / 2;
7857                 } else if (vectors <= 32 && vectors > 16) {
7858                         /* allocate 1 Q per macvlan and 16 Qs to the PF*/
7859                         q_per_macvlan = 1;
7860                         macvlan_cnt = vectors - 16;
7861                 } else if (vectors <= 16 && vectors > 8) {
7862                         /* allocate 1 Q per macvlan and 8 Qs to the PF */
7863                         q_per_macvlan = 1;
7864                         macvlan_cnt = vectors - 8;
7865                 } else {
7866                         /* allocate 1 Q per macvlan and 1 Q to the PF */
7867                         q_per_macvlan = 1;
7868                         macvlan_cnt = vectors - 1;
7869                 }
7870
7871                 if (macvlan_cnt == 0)
7872                         return ERR_PTR(-EBUSY);
7873
7874                 /* Quiesce VSI queues */
7875                 i40e_quiesce_vsi(vsi);
7876
7877                 /* sets up the macvlans but does not "enable" them */
7878                 ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
7879                                           vdev);
7880                 if (ret)
7881                         return ERR_PTR(ret);
7882
7883                 /* Unquiesce VSI */
7884                 i40e_unquiesce_vsi(vsi);
7885         }
7886         avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
7887                                             vsi->macvlan_cnt);
7888         if (avail_macvlan >= I40E_MAX_MACVLANS)
7889                 return ERR_PTR(-EBUSY);
7890
7891         /* create the fwd struct */
7892         fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
7893         if (!fwd)
7894                 return ERR_PTR(-ENOMEM);
7895
7896         set_bit(avail_macvlan, vsi->fwd_bitmask);
7897         fwd->bit_no = avail_macvlan;
7898         netdev_set_sb_channel(vdev, avail_macvlan);
7899         fwd->netdev = vdev;
7900
7901         if (!netif_running(netdev))
7902                 return fwd;
7903
7904         /* Set fwd ring up */
7905         ret = i40e_fwd_ring_up(vsi, vdev, fwd);
7906         if (ret) {
7907                 /* unbind the queues and drop the subordinate channel config */
7908                 netdev_unbind_sb_channel(netdev, vdev);
7909                 netdev_set_sb_channel(vdev, 0);
7910
7911                 kfree(fwd);
7912                 return ERR_PTR(-EINVAL);
7913         }
7914
7915         return fwd;
7916 }
7917
7918 /**
7919  * i40e_del_all_macvlans - Delete all the mac filters on the channels
7920  * @vsi: the VSI we want to access
7921  */
7922 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
7923 {
7924         struct i40e_channel *ch, *ch_tmp;
7925         struct i40e_pf *pf = vsi->back;
7926         struct i40e_hw *hw = &pf->hw;
7927         int aq_err, ret = 0;
7928
7929         if (list_empty(&vsi->macvlan_list))
7930                 return;
7931
7932         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7933                 if (i40e_is_channel_macvlan(ch)) {
7934                         ret = i40e_del_macvlan_filter(hw, ch->seid,
7935                                                       i40e_channel_mac(ch),
7936                                                       &aq_err);
7937                         if (!ret) {
7938                                 /* Reset queue contexts */
7939                                 i40e_reset_ch_rings(vsi, ch);
7940                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7941                                 netdev_unbind_sb_channel(vsi->netdev,
7942                                                          ch->fwd->netdev);
7943                                 netdev_set_sb_channel(ch->fwd->netdev, 0);
7944                                 kfree(ch->fwd);
7945                                 ch->fwd = NULL;
7946                         }
7947                 }
7948         }
7949 }
7950
7951 /**
7952  * i40e_fwd_del - delete macvlan interfaces
7953  * @netdev: net device to configure
7954  * @vdev: macvlan netdevice
7955  */
7956 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
7957 {
7958         struct i40e_netdev_priv *np = netdev_priv(netdev);
7959         struct i40e_fwd_adapter *fwd = vdev;
7960         struct i40e_channel *ch, *ch_tmp;
7961         struct i40e_vsi *vsi = np->vsi;
7962         struct i40e_pf *pf = vsi->back;
7963         struct i40e_hw *hw = &pf->hw;
7964         int aq_err, ret = 0;
7965
7966         /* Find the channel associated with the macvlan and del mac filter */
7967         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7968                 if (i40e_is_channel_macvlan(ch) &&
7969                     ether_addr_equal(i40e_channel_mac(ch),
7970                                      fwd->netdev->dev_addr)) {
7971                         ret = i40e_del_macvlan_filter(hw, ch->seid,
7972                                                       i40e_channel_mac(ch),
7973                                                       &aq_err);
7974                         if (!ret) {
7975                                 /* Reset queue contexts */
7976                                 i40e_reset_ch_rings(vsi, ch);
7977                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7978                                 netdev_unbind_sb_channel(netdev, fwd->netdev);
7979                                 netdev_set_sb_channel(fwd->netdev, 0);
7980                                 kfree(ch->fwd);
7981                                 ch->fwd = NULL;
7982                         } else {
7983                                 dev_info(&pf->pdev->dev,
7984                                          "Error deleting mac filter on macvlan err %s, aq_err %s\n",
7985                                           i40e_stat_str(hw, ret),
7986                                           i40e_aq_str(hw, aq_err));
7987                         }
7988                         break;
7989                 }
7990         }
7991 }
7992
7993 /**
7994  * i40e_setup_tc - configure multiple traffic classes
7995  * @netdev: net device to configure
7996  * @type_data: tc offload data
7997  **/
7998 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
7999 {
8000         struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
8001         struct i40e_netdev_priv *np = netdev_priv(netdev);
8002         struct i40e_vsi *vsi = np->vsi;
8003         struct i40e_pf *pf = vsi->back;
8004         u8 enabled_tc = 0, num_tc, hw;
8005         bool need_reset = false;
8006         int old_queue_pairs;
8007         int ret = -EINVAL;
8008         u16 mode;
8009         int i;
8010
8011         old_queue_pairs = vsi->num_queue_pairs;
8012         num_tc = mqprio_qopt->qopt.num_tc;
8013         hw = mqprio_qopt->qopt.hw;
8014         mode = mqprio_qopt->mode;
8015         if (!hw) {
8016                 pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8017                 memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
8018                 goto config_tc;
8019         }
8020
8021         /* Check if MFP enabled */
8022         if (pf->flags & I40E_FLAG_MFP_ENABLED) {
8023                 netdev_info(netdev,
8024                             "Configuring TC not supported in MFP mode\n");
8025                 return ret;
8026         }
8027         switch (mode) {
8028         case TC_MQPRIO_MODE_DCB:
8029                 pf->flags &= ~I40E_FLAG_TC_MQPRIO;
8030
8031                 /* Check if DCB enabled to continue */
8032                 if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
8033                         netdev_info(netdev,
8034                                     "DCB is not enabled for adapter\n");
8035                         return ret;
8036                 }
8037
8038                 /* Check whether tc count is within enabled limit */
8039                 if (num_tc > i40e_pf_get_num_tc(pf)) {
8040                         netdev_info(netdev,
8041                                     "TC count greater than enabled on link for adapter\n");
8042                         return ret;
8043                 }
8044                 break;
8045         case TC_MQPRIO_MODE_CHANNEL:
8046                 if (pf->flags & I40E_FLAG_DCB_ENABLED) {
8047                         netdev_info(netdev,
8048                                     "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
8049                         return ret;
8050                 }
8051                 if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8052                         return ret;
8053                 ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
8054                 if (ret)
8055                         return ret;
8056                 memcpy(&vsi->mqprio_qopt, mqprio_qopt,
8057                        sizeof(*mqprio_qopt));
8058                 pf->flags |= I40E_FLAG_TC_MQPRIO;
8059                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8060                 break;
8061         default:
8062                 return -EINVAL;
8063         }
8064
8065 config_tc:
8066         /* Generate TC map for number of tc requested */
8067         for (i = 0; i < num_tc; i++)
8068                 enabled_tc |= BIT(i);
8069
8070         /* Requesting same TC configuration as already enabled */
8071         if (enabled_tc == vsi->tc_config.enabled_tc &&
8072             mode != TC_MQPRIO_MODE_CHANNEL)
8073                 return 0;
8074
8075         /* Quiesce VSI queues */
8076         i40e_quiesce_vsi(vsi);
8077
8078         if (!hw && !i40e_is_tc_mqprio_enabled(pf))
8079                 i40e_remove_queue_channels(vsi);
8080
8081         /* Configure VSI for enabled TCs */
8082         ret = i40e_vsi_config_tc(vsi, enabled_tc);
8083         if (ret) {
8084                 netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
8085                             vsi->seid);
8086                 need_reset = true;
8087                 goto exit;
8088         } else if (enabled_tc &&
8089                    (!is_power_of_2(vsi->tc_config.tc_info[0].qcount))) {
8090                 netdev_info(netdev,
8091                             "Failed to create channel. Override queues (%u) not power of 2\n",
8092                             vsi->tc_config.tc_info[0].qcount);
8093                 ret = -EINVAL;
8094                 need_reset = true;
8095                 goto exit;
8096         }
8097
8098         dev_info(&vsi->back->pdev->dev,
8099                  "Setup channel (id:%u) utilizing num_queues %d\n",
8100                  vsi->seid, vsi->tc_config.tc_info[0].qcount);
8101
8102         if (i40e_is_tc_mqprio_enabled(pf)) {
8103                 if (vsi->mqprio_qopt.max_rate[0]) {
8104                         u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
8105
8106                         do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
8107                         ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
8108                         if (!ret) {
8109                                 u64 credits = max_tx_rate;
8110
8111                                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
8112                                 dev_dbg(&vsi->back->pdev->dev,
8113                                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
8114                                         max_tx_rate,
8115                                         credits,
8116                                         vsi->seid);
8117                         } else {
8118                                 need_reset = true;
8119                                 goto exit;
8120                         }
8121                 }
8122                 ret = i40e_configure_queue_channels(vsi);
8123                 if (ret) {
8124                         vsi->num_queue_pairs = old_queue_pairs;
8125                         netdev_info(netdev,
8126                                     "Failed configuring queue channels\n");
8127                         need_reset = true;
8128                         goto exit;
8129                 }
8130         }
8131
8132 exit:
8133         /* Reset the configuration data to defaults, only TC0 is enabled */
8134         if (need_reset) {
8135                 i40e_vsi_set_default_tc_config(vsi);
8136                 need_reset = false;
8137         }
8138
8139         /* Unquiesce VSI */
8140         i40e_unquiesce_vsi(vsi);
8141         return ret;
8142 }
8143
8144 /**
8145  * i40e_set_cld_element - sets cloud filter element data
8146  * @filter: cloud filter rule
8147  * @cld: ptr to cloud filter element data
8148  *
8149  * This is helper function to copy data into cloud filter element
8150  **/
8151 static inline void
8152 i40e_set_cld_element(struct i40e_cloud_filter *filter,
8153                      struct i40e_aqc_cloud_filters_element_data *cld)
8154 {
8155         u32 ipa;
8156         int i;
8157
8158         memset(cld, 0, sizeof(*cld));
8159         ether_addr_copy(cld->outer_mac, filter->dst_mac);
8160         ether_addr_copy(cld->inner_mac, filter->src_mac);
8161
8162         if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
8163                 return;
8164
8165         if (filter->n_proto == ETH_P_IPV6) {
8166 #define IPV6_MAX_INDEX  (ARRAY_SIZE(filter->dst_ipv6) - 1)
8167                 for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
8168                         ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
8169
8170                         *(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
8171                 }
8172         } else {
8173                 ipa = be32_to_cpu(filter->dst_ipv4);
8174
8175                 memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
8176         }
8177
8178         cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
8179
8180         /* tenant_id is not supported by FW now, once the support is enabled
8181          * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8182          */
8183         if (filter->tenant_id)
8184                 return;
8185 }
8186
8187 /**
8188  * i40e_add_del_cloud_filter - Add/del cloud filter
8189  * @vsi: pointer to VSI
8190  * @filter: cloud filter rule
8191  * @add: if true, add, if false, delete
8192  *
8193  * Add or delete a cloud filter for a specific flow spec.
8194  * Returns 0 if the filter were successfully added.
8195  **/
8196 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8197                               struct i40e_cloud_filter *filter, bool add)
8198 {
8199         struct i40e_aqc_cloud_filters_element_data cld_filter;
8200         struct i40e_pf *pf = vsi->back;
8201         int ret;
8202         static const u16 flag_table[128] = {
8203                 [I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8204                         I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8205                 [I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8206                         I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8207                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8208                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8209                 [I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8210                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8211                 [I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8212                         I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8213                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8214                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8215                 [I40E_CLOUD_FILTER_FLAGS_IIP] =
8216                         I40E_AQC_ADD_CLOUD_FILTER_IIP,
8217         };
8218
8219         if (filter->flags >= ARRAY_SIZE(flag_table))
8220                 return I40E_ERR_CONFIG;
8221
8222         memset(&cld_filter, 0, sizeof(cld_filter));
8223
8224         /* copy element needed to add cloud filter from filter */
8225         i40e_set_cld_element(filter, &cld_filter);
8226
8227         if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8228                 cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8229                                              I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8230
8231         if (filter->n_proto == ETH_P_IPV6)
8232                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8233                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8234         else
8235                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8236                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8237
8238         if (add)
8239                 ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8240                                                 &cld_filter, 1);
8241         else
8242                 ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8243                                                 &cld_filter, 1);
8244         if (ret)
8245                 dev_dbg(&pf->pdev->dev,
8246                         "Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8247                         add ? "add" : "delete", filter->dst_port, ret,
8248                         pf->hw.aq.asq_last_status);
8249         else
8250                 dev_info(&pf->pdev->dev,
8251                          "%s cloud filter for VSI: %d\n",
8252                          add ? "Added" : "Deleted", filter->seid);
8253         return ret;
8254 }
8255
8256 /**
8257  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8258  * @vsi: pointer to VSI
8259  * @filter: cloud filter rule
8260  * @add: if true, add, if false, delete
8261  *
8262  * Add or delete a cloud filter for a specific flow spec using big buffer.
8263  * Returns 0 if the filter were successfully added.
8264  **/
8265 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8266                                       struct i40e_cloud_filter *filter,
8267                                       bool add)
8268 {
8269         struct i40e_aqc_cloud_filters_element_bb cld_filter;
8270         struct i40e_pf *pf = vsi->back;
8271         int ret;
8272
8273         /* Both (src/dst) valid mac_addr are not supported */
8274         if ((is_valid_ether_addr(filter->dst_mac) &&
8275              is_valid_ether_addr(filter->src_mac)) ||
8276             (is_multicast_ether_addr(filter->dst_mac) &&
8277              is_multicast_ether_addr(filter->src_mac)))
8278                 return -EOPNOTSUPP;
8279
8280         /* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8281          * ports are not supported via big buffer now.
8282          */
8283         if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8284                 return -EOPNOTSUPP;
8285
8286         /* adding filter using src_port/src_ip is not supported at this stage */
8287         if (filter->src_port ||
8288             (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8289             !ipv6_addr_any(&filter->ip.v6.src_ip6))
8290                 return -EOPNOTSUPP;
8291
8292         memset(&cld_filter, 0, sizeof(cld_filter));
8293
8294         /* copy element needed to add cloud filter from filter */
8295         i40e_set_cld_element(filter, &cld_filter.element);
8296
8297         if (is_valid_ether_addr(filter->dst_mac) ||
8298             is_valid_ether_addr(filter->src_mac) ||
8299             is_multicast_ether_addr(filter->dst_mac) ||
8300             is_multicast_ether_addr(filter->src_mac)) {
8301                 /* MAC + IP : unsupported mode */
8302                 if (filter->dst_ipv4)
8303                         return -EOPNOTSUPP;
8304
8305                 /* since we validated that L4 port must be valid before
8306                  * we get here, start with respective "flags" value
8307                  * and update if vlan is present or not
8308                  */
8309                 cld_filter.element.flags =
8310                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8311
8312                 if (filter->vlan_id) {
8313                         cld_filter.element.flags =
8314                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8315                 }
8316
8317         } else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8318                    !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8319                 cld_filter.element.flags =
8320                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8321                 if (filter->n_proto == ETH_P_IPV6)
8322                         cld_filter.element.flags |=
8323                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8324                 else
8325                         cld_filter.element.flags |=
8326                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8327         } else {
8328                 dev_err(&pf->pdev->dev,
8329                         "either mac or ip has to be valid for cloud filter\n");
8330                 return -EINVAL;
8331         }
8332
8333         /* Now copy L4 port in Byte 6..7 in general fields */
8334         cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8335                                                 be16_to_cpu(filter->dst_port);
8336
8337         if (add) {
8338                 /* Validate current device switch mode, change if necessary */
8339                 ret = i40e_validate_and_set_switch_mode(vsi);
8340                 if (ret) {
8341                         dev_err(&pf->pdev->dev,
8342                                 "failed to set switch mode, ret %d\n",
8343                                 ret);
8344                         return ret;
8345                 }
8346
8347                 ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8348                                                    &cld_filter, 1);
8349         } else {
8350                 ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8351                                                    &cld_filter, 1);
8352         }
8353
8354         if (ret)
8355                 dev_dbg(&pf->pdev->dev,
8356                         "Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8357                         add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8358         else
8359                 dev_info(&pf->pdev->dev,
8360                          "%s cloud filter for VSI: %d, L4 port: %d\n",
8361                          add ? "add" : "delete", filter->seid,
8362                          ntohs(filter->dst_port));
8363         return ret;
8364 }
8365
8366 /**
8367  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8368  * @vsi: Pointer to VSI
8369  * @f: Pointer to struct flow_cls_offload
8370  * @filter: Pointer to cloud filter structure
8371  *
8372  **/
8373 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8374                                  struct flow_cls_offload *f,
8375                                  struct i40e_cloud_filter *filter)
8376 {
8377         struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8378         struct flow_dissector *dissector = rule->match.dissector;
8379         u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8380         struct i40e_pf *pf = vsi->back;
8381         u8 field_flags = 0;
8382
8383         if (dissector->used_keys &
8384             ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
8385               BIT(FLOW_DISSECTOR_KEY_BASIC) |
8386               BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8387               BIT(FLOW_DISSECTOR_KEY_VLAN) |
8388               BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8389               BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8390               BIT(FLOW_DISSECTOR_KEY_PORTS) |
8391               BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8392                 dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
8393                         dissector->used_keys);
8394                 return -EOPNOTSUPP;
8395         }
8396
8397         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8398                 struct flow_match_enc_keyid match;
8399
8400                 flow_rule_match_enc_keyid(rule, &match);
8401                 if (match.mask->keyid != 0)
8402                         field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8403
8404                 filter->tenant_id = be32_to_cpu(match.key->keyid);
8405         }
8406
8407         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8408                 struct flow_match_basic match;
8409
8410                 flow_rule_match_basic(rule, &match);
8411                 n_proto_key = ntohs(match.key->n_proto);
8412                 n_proto_mask = ntohs(match.mask->n_proto);
8413
8414                 if (n_proto_key == ETH_P_ALL) {
8415                         n_proto_key = 0;
8416                         n_proto_mask = 0;
8417                 }
8418                 filter->n_proto = n_proto_key & n_proto_mask;
8419                 filter->ip_proto = match.key->ip_proto;
8420         }
8421
8422         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8423                 struct flow_match_eth_addrs match;
8424
8425                 flow_rule_match_eth_addrs(rule, &match);
8426
8427                 /* use is_broadcast and is_zero to check for all 0xf or 0 */
8428                 if (!is_zero_ether_addr(match.mask->dst)) {
8429                         if (is_broadcast_ether_addr(match.mask->dst)) {
8430                                 field_flags |= I40E_CLOUD_FIELD_OMAC;
8431                         } else {
8432                                 dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8433                                         match.mask->dst);
8434                                 return I40E_ERR_CONFIG;
8435                         }
8436                 }
8437
8438                 if (!is_zero_ether_addr(match.mask->src)) {
8439                         if (is_broadcast_ether_addr(match.mask->src)) {
8440                                 field_flags |= I40E_CLOUD_FIELD_IMAC;
8441                         } else {
8442                                 dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8443                                         match.mask->src);
8444                                 return I40E_ERR_CONFIG;
8445                         }
8446                 }
8447                 ether_addr_copy(filter->dst_mac, match.key->dst);
8448                 ether_addr_copy(filter->src_mac, match.key->src);
8449         }
8450
8451         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8452                 struct flow_match_vlan match;
8453
8454                 flow_rule_match_vlan(rule, &match);
8455                 if (match.mask->vlan_id) {
8456                         if (match.mask->vlan_id == VLAN_VID_MASK) {
8457                                 field_flags |= I40E_CLOUD_FIELD_IVLAN;
8458
8459                         } else {
8460                                 dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8461                                         match.mask->vlan_id);
8462                                 return I40E_ERR_CONFIG;
8463                         }
8464                 }
8465
8466                 filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8467         }
8468
8469         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8470                 struct flow_match_control match;
8471
8472                 flow_rule_match_control(rule, &match);
8473                 addr_type = match.key->addr_type;
8474         }
8475
8476         if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8477                 struct flow_match_ipv4_addrs match;
8478
8479                 flow_rule_match_ipv4_addrs(rule, &match);
8480                 if (match.mask->dst) {
8481                         if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8482                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8483                         } else {
8484                                 dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8485                                         &match.mask->dst);
8486                                 return I40E_ERR_CONFIG;
8487                         }
8488                 }
8489
8490                 if (match.mask->src) {
8491                         if (match.mask->src == cpu_to_be32(0xffffffff)) {
8492                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8493                         } else {
8494                                 dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8495                                         &match.mask->src);
8496                                 return I40E_ERR_CONFIG;
8497                         }
8498                 }
8499
8500                 if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8501                         dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8502                         return I40E_ERR_CONFIG;
8503                 }
8504                 filter->dst_ipv4 = match.key->dst;
8505                 filter->src_ipv4 = match.key->src;
8506         }
8507
8508         if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8509                 struct flow_match_ipv6_addrs match;
8510
8511                 flow_rule_match_ipv6_addrs(rule, &match);
8512
8513                 /* src and dest IPV6 address should not be LOOPBACK
8514                  * (0:0:0:0:0:0:0:1), which can be represented as ::1
8515                  */
8516                 if (ipv6_addr_loopback(&match.key->dst) ||
8517                     ipv6_addr_loopback(&match.key->src)) {
8518                         dev_err(&pf->pdev->dev,
8519                                 "Bad ipv6, addr is LOOPBACK\n");
8520                         return I40E_ERR_CONFIG;
8521                 }
8522                 if (!ipv6_addr_any(&match.mask->dst) ||
8523                     !ipv6_addr_any(&match.mask->src))
8524                         field_flags |= I40E_CLOUD_FIELD_IIP;
8525
8526                 memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8527                        sizeof(filter->src_ipv6));
8528                 memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8529                        sizeof(filter->dst_ipv6));
8530         }
8531
8532         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8533                 struct flow_match_ports match;
8534
8535                 flow_rule_match_ports(rule, &match);
8536                 if (match.mask->src) {
8537                         if (match.mask->src == cpu_to_be16(0xffff)) {
8538                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8539                         } else {
8540                                 dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8541                                         be16_to_cpu(match.mask->src));
8542                                 return I40E_ERR_CONFIG;
8543                         }
8544                 }
8545
8546                 if (match.mask->dst) {
8547                         if (match.mask->dst == cpu_to_be16(0xffff)) {
8548                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8549                         } else {
8550                                 dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8551                                         be16_to_cpu(match.mask->dst));
8552                                 return I40E_ERR_CONFIG;
8553                         }
8554                 }
8555
8556                 filter->dst_port = match.key->dst;
8557                 filter->src_port = match.key->src;
8558
8559                 switch (filter->ip_proto) {
8560                 case IPPROTO_TCP:
8561                 case IPPROTO_UDP:
8562                         break;
8563                 default:
8564                         dev_err(&pf->pdev->dev,
8565                                 "Only UDP and TCP transport are supported\n");
8566                         return -EINVAL;
8567                 }
8568         }
8569         filter->flags = field_flags;
8570         return 0;
8571 }
8572
8573 /**
8574  * i40e_handle_tclass: Forward to a traffic class on the device
8575  * @vsi: Pointer to VSI
8576  * @tc: traffic class index on the device
8577  * @filter: Pointer to cloud filter structure
8578  *
8579  **/
8580 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8581                               struct i40e_cloud_filter *filter)
8582 {
8583         struct i40e_channel *ch, *ch_tmp;
8584
8585         /* direct to a traffic class on the same device */
8586         if (tc == 0) {
8587                 filter->seid = vsi->seid;
8588                 return 0;
8589         } else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8590                 if (!filter->dst_port) {
8591                         dev_err(&vsi->back->pdev->dev,
8592                                 "Specify destination port to direct to traffic class that is not default\n");
8593                         return -EINVAL;
8594                 }
8595                 if (list_empty(&vsi->ch_list))
8596                         return -EINVAL;
8597                 list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8598                                          list) {
8599                         if (ch->seid == vsi->tc_seid_map[tc])
8600                                 filter->seid = ch->seid;
8601                 }
8602                 return 0;
8603         }
8604         dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8605         return -EINVAL;
8606 }
8607
8608 /**
8609  * i40e_configure_clsflower - Configure tc flower filters
8610  * @vsi: Pointer to VSI
8611  * @cls_flower: Pointer to struct flow_cls_offload
8612  *
8613  **/
8614 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8615                                     struct flow_cls_offload *cls_flower)
8616 {
8617         int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8618         struct i40e_cloud_filter *filter = NULL;
8619         struct i40e_pf *pf = vsi->back;
8620         int err = 0;
8621
8622         if (tc < 0) {
8623                 dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8624                 return -EOPNOTSUPP;
8625         }
8626
8627         if (!tc) {
8628                 dev_err(&pf->pdev->dev, "Unable to add filter because of invalid destination");
8629                 return -EINVAL;
8630         }
8631
8632         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8633             test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8634                 return -EBUSY;
8635
8636         if (pf->fdir_pf_active_filters ||
8637             (!hlist_empty(&pf->fdir_filter_list))) {
8638                 dev_err(&vsi->back->pdev->dev,
8639                         "Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8640                 return -EINVAL;
8641         }
8642
8643         if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8644                 dev_err(&vsi->back->pdev->dev,
8645                         "Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8646                 vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8647                 vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8648         }
8649
8650         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8651         if (!filter)
8652                 return -ENOMEM;
8653
8654         filter->cookie = cls_flower->cookie;
8655
8656         err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8657         if (err < 0)
8658                 goto err;
8659
8660         err = i40e_handle_tclass(vsi, tc, filter);
8661         if (err < 0)
8662                 goto err;
8663
8664         /* Add cloud filter */
8665         if (filter->dst_port)
8666                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8667         else
8668                 err = i40e_add_del_cloud_filter(vsi, filter, true);
8669
8670         if (err) {
8671                 dev_err(&pf->pdev->dev, "Failed to add cloud filter, err %d\n",
8672                         err);
8673                 goto err;
8674         }
8675
8676         /* add filter to the ordered list */
8677         INIT_HLIST_NODE(&filter->cloud_node);
8678
8679         hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8680
8681         pf->num_cloud_filters++;
8682
8683         return err;
8684 err:
8685         kfree(filter);
8686         return err;
8687 }
8688
8689 /**
8690  * i40e_find_cloud_filter - Find the could filter in the list
8691  * @vsi: Pointer to VSI
8692  * @cookie: filter specific cookie
8693  *
8694  **/
8695 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8696                                                         unsigned long *cookie)
8697 {
8698         struct i40e_cloud_filter *filter = NULL;
8699         struct hlist_node *node2;
8700
8701         hlist_for_each_entry_safe(filter, node2,
8702                                   &vsi->back->cloud_filter_list, cloud_node)
8703                 if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8704                         return filter;
8705         return NULL;
8706 }
8707
8708 /**
8709  * i40e_delete_clsflower - Remove tc flower filters
8710  * @vsi: Pointer to VSI
8711  * @cls_flower: Pointer to struct flow_cls_offload
8712  *
8713  **/
8714 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8715                                  struct flow_cls_offload *cls_flower)
8716 {
8717         struct i40e_cloud_filter *filter = NULL;
8718         struct i40e_pf *pf = vsi->back;
8719         int err = 0;
8720
8721         filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8722
8723         if (!filter)
8724                 return -EINVAL;
8725
8726         hash_del(&filter->cloud_node);
8727
8728         if (filter->dst_port)
8729                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8730         else
8731                 err = i40e_add_del_cloud_filter(vsi, filter, false);
8732
8733         kfree(filter);
8734         if (err) {
8735                 dev_err(&pf->pdev->dev,
8736                         "Failed to delete cloud filter, err %s\n",
8737                         i40e_stat_str(&pf->hw, err));
8738                 return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8739         }
8740
8741         pf->num_cloud_filters--;
8742         if (!pf->num_cloud_filters)
8743                 if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8744                     !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8745                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8746                         pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8747                         pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8748                 }
8749         return 0;
8750 }
8751
8752 /**
8753  * i40e_setup_tc_cls_flower - flower classifier offloads
8754  * @np: net device to configure
8755  * @cls_flower: offload data
8756  **/
8757 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8758                                     struct flow_cls_offload *cls_flower)
8759 {
8760         struct i40e_vsi *vsi = np->vsi;
8761
8762         switch (cls_flower->command) {
8763         case FLOW_CLS_REPLACE:
8764                 return i40e_configure_clsflower(vsi, cls_flower);
8765         case FLOW_CLS_DESTROY:
8766                 return i40e_delete_clsflower(vsi, cls_flower);
8767         case FLOW_CLS_STATS:
8768                 return -EOPNOTSUPP;
8769         default:
8770                 return -EOPNOTSUPP;
8771         }
8772 }
8773
8774 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8775                                   void *cb_priv)
8776 {
8777         struct i40e_netdev_priv *np = cb_priv;
8778
8779         if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8780                 return -EOPNOTSUPP;
8781
8782         switch (type) {
8783         case TC_SETUP_CLSFLOWER:
8784                 return i40e_setup_tc_cls_flower(np, type_data);
8785
8786         default:
8787                 return -EOPNOTSUPP;
8788         }
8789 }
8790
8791 static LIST_HEAD(i40e_block_cb_list);
8792
8793 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8794                            void *type_data)
8795 {
8796         struct i40e_netdev_priv *np = netdev_priv(netdev);
8797
8798         switch (type) {
8799         case TC_SETUP_QDISC_MQPRIO:
8800                 return i40e_setup_tc(netdev, type_data);
8801         case TC_SETUP_BLOCK:
8802                 return flow_block_cb_setup_simple(type_data,
8803                                                   &i40e_block_cb_list,
8804                                                   i40e_setup_tc_block_cb,
8805                                                   np, np, true);
8806         default:
8807                 return -EOPNOTSUPP;
8808         }
8809 }
8810
8811 /**
8812  * i40e_open - Called when a network interface is made active
8813  * @netdev: network interface device structure
8814  *
8815  * The open entry point is called when a network interface is made
8816  * active by the system (IFF_UP).  At this point all resources needed
8817  * for transmit and receive operations are allocated, the interrupt
8818  * handler is registered with the OS, the netdev watchdog subtask is
8819  * enabled, and the stack is notified that the interface is ready.
8820  *
8821  * Returns 0 on success, negative value on failure
8822  **/
8823 int i40e_open(struct net_device *netdev)
8824 {
8825         struct i40e_netdev_priv *np = netdev_priv(netdev);
8826         struct i40e_vsi *vsi = np->vsi;
8827         struct i40e_pf *pf = vsi->back;
8828         int err;
8829
8830         /* disallow open during test or if eeprom is broken */
8831         if (test_bit(__I40E_TESTING, pf->state) ||
8832             test_bit(__I40E_BAD_EEPROM, pf->state))
8833                 return -EBUSY;
8834
8835         netif_carrier_off(netdev);
8836
8837         if (i40e_force_link_state(pf, true))
8838                 return -EAGAIN;
8839
8840         err = i40e_vsi_open(vsi);
8841         if (err)
8842                 return err;
8843
8844         /* configure global TSO hardware offload settings */
8845         wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8846                                                        TCP_FLAG_FIN) >> 16);
8847         wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8848                                                        TCP_FLAG_FIN |
8849                                                        TCP_FLAG_CWR) >> 16);
8850         wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8851         udp_tunnel_get_rx_info(netdev);
8852
8853         return 0;
8854 }
8855
8856 /**
8857  * i40e_netif_set_realnum_tx_rx_queues - Update number of tx/rx queues
8858  * @vsi: vsi structure
8859  *
8860  * This updates netdev's number of tx/rx queues
8861  *
8862  * Returns status of setting tx/rx queues
8863  **/
8864 static int i40e_netif_set_realnum_tx_rx_queues(struct i40e_vsi *vsi)
8865 {
8866         int ret;
8867
8868         ret = netif_set_real_num_rx_queues(vsi->netdev,
8869                                            vsi->num_queue_pairs);
8870         if (ret)
8871                 return ret;
8872
8873         return netif_set_real_num_tx_queues(vsi->netdev,
8874                                             vsi->num_queue_pairs);
8875 }
8876
8877 /**
8878  * i40e_vsi_open -
8879  * @vsi: the VSI to open
8880  *
8881  * Finish initialization of the VSI.
8882  *
8883  * Returns 0 on success, negative value on failure
8884  *
8885  * Note: expects to be called while under rtnl_lock()
8886  **/
8887 int i40e_vsi_open(struct i40e_vsi *vsi)
8888 {
8889         struct i40e_pf *pf = vsi->back;
8890         char int_name[I40E_INT_NAME_STR_LEN];
8891         int err;
8892
8893         /* allocate descriptors */
8894         err = i40e_vsi_setup_tx_resources(vsi);
8895         if (err)
8896                 goto err_setup_tx;
8897         err = i40e_vsi_setup_rx_resources(vsi);
8898         if (err)
8899                 goto err_setup_rx;
8900
8901         err = i40e_vsi_configure(vsi);
8902         if (err)
8903                 goto err_setup_rx;
8904
8905         if (vsi->netdev) {
8906                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
8907                          dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
8908                 err = i40e_vsi_request_irq(vsi, int_name);
8909                 if (err)
8910                         goto err_setup_rx;
8911
8912                 /* Notify the stack of the actual queue counts. */
8913                 err = i40e_netif_set_realnum_tx_rx_queues(vsi);
8914                 if (err)
8915                         goto err_set_queues;
8916
8917         } else if (vsi->type == I40E_VSI_FDIR) {
8918                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
8919                          dev_driver_string(&pf->pdev->dev),
8920                          dev_name(&pf->pdev->dev));
8921                 err = i40e_vsi_request_irq(vsi, int_name);
8922                 if (err)
8923                         goto err_setup_rx;
8924
8925         } else {
8926                 err = -EINVAL;
8927                 goto err_setup_rx;
8928         }
8929
8930         err = i40e_up_complete(vsi);
8931         if (err)
8932                 goto err_up_complete;
8933
8934         return 0;
8935
8936 err_up_complete:
8937         i40e_down(vsi);
8938 err_set_queues:
8939         i40e_vsi_free_irq(vsi);
8940 err_setup_rx:
8941         i40e_vsi_free_rx_resources(vsi);
8942 err_setup_tx:
8943         i40e_vsi_free_tx_resources(vsi);
8944         if (vsi == pf->vsi[pf->lan_vsi])
8945                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
8946
8947         return err;
8948 }
8949
8950 /**
8951  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
8952  * @pf: Pointer to PF
8953  *
8954  * This function destroys the hlist where all the Flow Director
8955  * filters were saved.
8956  **/
8957 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
8958 {
8959         struct i40e_fdir_filter *filter;
8960         struct i40e_flex_pit *pit_entry, *tmp;
8961         struct hlist_node *node2;
8962
8963         hlist_for_each_entry_safe(filter, node2,
8964                                   &pf->fdir_filter_list, fdir_node) {
8965                 hlist_del(&filter->fdir_node);
8966                 kfree(filter);
8967         }
8968
8969         list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
8970                 list_del(&pit_entry->list);
8971                 kfree(pit_entry);
8972         }
8973         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
8974
8975         list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
8976                 list_del(&pit_entry->list);
8977                 kfree(pit_entry);
8978         }
8979         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
8980
8981         pf->fdir_pf_active_filters = 0;
8982         i40e_reset_fdir_filter_cnt(pf);
8983
8984         /* Reprogram the default input set for TCP/IPv4 */
8985         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
8986                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8987                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8988
8989         /* Reprogram the default input set for TCP/IPv6 */
8990         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
8991                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
8992                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8993
8994         /* Reprogram the default input set for UDP/IPv4 */
8995         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
8996                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8997                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8998
8999         /* Reprogram the default input set for UDP/IPv6 */
9000         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
9001                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9002                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9003
9004         /* Reprogram the default input set for SCTP/IPv4 */
9005         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
9006                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9007                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9008
9009         /* Reprogram the default input set for SCTP/IPv6 */
9010         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
9011                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
9012                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9013
9014         /* Reprogram the default input set for Other/IPv4 */
9015         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
9016                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9017
9018         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
9019                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9020
9021         /* Reprogram the default input set for Other/IPv6 */
9022         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
9023                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9024
9025         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
9026                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
9027 }
9028
9029 /**
9030  * i40e_cloud_filter_exit - Cleans up the cloud filters
9031  * @pf: Pointer to PF
9032  *
9033  * This function destroys the hlist where all the cloud filters
9034  * were saved.
9035  **/
9036 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
9037 {
9038         struct i40e_cloud_filter *cfilter;
9039         struct hlist_node *node;
9040
9041         hlist_for_each_entry_safe(cfilter, node,
9042                                   &pf->cloud_filter_list, cloud_node) {
9043                 hlist_del(&cfilter->cloud_node);
9044                 kfree(cfilter);
9045         }
9046         pf->num_cloud_filters = 0;
9047
9048         if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
9049             !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
9050                 pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9051                 pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
9052                 pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
9053         }
9054 }
9055
9056 /**
9057  * i40e_close - Disables a network interface
9058  * @netdev: network interface device structure
9059  *
9060  * The close entry point is called when an interface is de-activated
9061  * by the OS.  The hardware is still under the driver's control, but
9062  * this netdev interface is disabled.
9063  *
9064  * Returns 0, this is not allowed to fail
9065  **/
9066 int i40e_close(struct net_device *netdev)
9067 {
9068         struct i40e_netdev_priv *np = netdev_priv(netdev);
9069         struct i40e_vsi *vsi = np->vsi;
9070
9071         i40e_vsi_close(vsi);
9072
9073         return 0;
9074 }
9075
9076 /**
9077  * i40e_do_reset - Start a PF or Core Reset sequence
9078  * @pf: board private structure
9079  * @reset_flags: which reset is requested
9080  * @lock_acquired: indicates whether or not the lock has been acquired
9081  * before this function was called.
9082  *
9083  * The essential difference in resets is that the PF Reset
9084  * doesn't clear the packet buffers, doesn't reset the PE
9085  * firmware, and doesn't bother the other PFs on the chip.
9086  **/
9087 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
9088 {
9089         u32 val;
9090
9091         /* do the biggest reset indicated */
9092         if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
9093
9094                 /* Request a Global Reset
9095                  *
9096                  * This will start the chip's countdown to the actual full
9097                  * chip reset event, and a warning interrupt to be sent
9098                  * to all PFs, including the requestor.  Our handler
9099                  * for the warning interrupt will deal with the shutdown
9100                  * and recovery of the switch setup.
9101                  */
9102                 dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
9103                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9104                 val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
9105                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9106
9107         } else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
9108
9109                 /* Request a Core Reset
9110                  *
9111                  * Same as Global Reset, except does *not* include the MAC/PHY
9112                  */
9113                 dev_dbg(&pf->pdev->dev, "CoreR requested\n");
9114                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
9115                 val |= I40E_GLGEN_RTRIG_CORER_MASK;
9116                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
9117                 i40e_flush(&pf->hw);
9118
9119         } else if (reset_flags & I40E_PF_RESET_FLAG) {
9120
9121                 /* Request a PF Reset
9122                  *
9123                  * Resets only the PF-specific registers
9124                  *
9125                  * This goes directly to the tear-down and rebuild of
9126                  * the switch, since we need to do all the recovery as
9127                  * for the Core Reset.
9128                  */
9129                 dev_dbg(&pf->pdev->dev, "PFR requested\n");
9130                 i40e_handle_reset_warning(pf, lock_acquired);
9131
9132         } else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
9133                 /* Request a PF Reset
9134                  *
9135                  * Resets PF and reinitializes PFs VSI.
9136                  */
9137                 i40e_prep_for_reset(pf);
9138                 i40e_reset_and_rebuild(pf, true, lock_acquired);
9139                 dev_info(&pf->pdev->dev,
9140                          pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
9141                          "FW LLDP is disabled\n" :
9142                          "FW LLDP is enabled\n");
9143
9144         } else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
9145                 int v;
9146
9147                 /* Find the VSI(s) that requested a re-init */
9148                 dev_info(&pf->pdev->dev,
9149                          "VSI reinit requested\n");
9150                 for (v = 0; v < pf->num_alloc_vsi; v++) {
9151                         struct i40e_vsi *vsi = pf->vsi[v];
9152
9153                         if (vsi != NULL &&
9154                             test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
9155                                                vsi->state))
9156                                 i40e_vsi_reinit_locked(pf->vsi[v]);
9157                 }
9158         } else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
9159                 int v;
9160
9161                 /* Find the VSI(s) that needs to be brought down */
9162                 dev_info(&pf->pdev->dev, "VSI down requested\n");
9163                 for (v = 0; v < pf->num_alloc_vsi; v++) {
9164                         struct i40e_vsi *vsi = pf->vsi[v];
9165
9166                         if (vsi != NULL &&
9167                             test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
9168                                                vsi->state)) {
9169                                 set_bit(__I40E_VSI_DOWN, vsi->state);
9170                                 i40e_down(vsi);
9171                         }
9172                 }
9173         } else {
9174                 dev_info(&pf->pdev->dev,
9175                          "bad reset request 0x%08x\n", reset_flags);
9176         }
9177 }
9178
9179 #ifdef CONFIG_I40E_DCB
9180 /**
9181  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
9182  * @pf: board private structure
9183  * @old_cfg: current DCB config
9184  * @new_cfg: new DCB config
9185  **/
9186 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
9187                             struct i40e_dcbx_config *old_cfg,
9188                             struct i40e_dcbx_config *new_cfg)
9189 {
9190         bool need_reconfig = false;
9191
9192         /* Check if ETS configuration has changed */
9193         if (memcmp(&new_cfg->etscfg,
9194                    &old_cfg->etscfg,
9195                    sizeof(new_cfg->etscfg))) {
9196                 /* If Priority Table has changed reconfig is needed */
9197                 if (memcmp(&new_cfg->etscfg.prioritytable,
9198                            &old_cfg->etscfg.prioritytable,
9199                            sizeof(new_cfg->etscfg.prioritytable))) {
9200                         need_reconfig = true;
9201                         dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9202                 }
9203
9204                 if (memcmp(&new_cfg->etscfg.tcbwtable,
9205                            &old_cfg->etscfg.tcbwtable,
9206                            sizeof(new_cfg->etscfg.tcbwtable)))
9207                         dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9208
9209                 if (memcmp(&new_cfg->etscfg.tsatable,
9210                            &old_cfg->etscfg.tsatable,
9211                            sizeof(new_cfg->etscfg.tsatable)))
9212                         dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9213         }
9214
9215         /* Check if PFC configuration has changed */
9216         if (memcmp(&new_cfg->pfc,
9217                    &old_cfg->pfc,
9218                    sizeof(new_cfg->pfc))) {
9219                 need_reconfig = true;
9220                 dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9221         }
9222
9223         /* Check if APP Table has changed */
9224         if (memcmp(&new_cfg->app,
9225                    &old_cfg->app,
9226                    sizeof(new_cfg->app))) {
9227                 need_reconfig = true;
9228                 dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9229         }
9230
9231         dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9232         return need_reconfig;
9233 }
9234
9235 /**
9236  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9237  * @pf: board private structure
9238  * @e: event info posted on ARQ
9239  **/
9240 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9241                                   struct i40e_arq_event_info *e)
9242 {
9243         struct i40e_aqc_lldp_get_mib *mib =
9244                 (struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9245         struct i40e_hw *hw = &pf->hw;
9246         struct i40e_dcbx_config tmp_dcbx_cfg;
9247         bool need_reconfig = false;
9248         int ret = 0;
9249         u8 type;
9250
9251         /* X710-T*L 2.5G and 5G speeds don't support DCB */
9252         if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9253             (hw->phy.link_info.link_speed &
9254              ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9255              !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9256                 /* let firmware decide if the DCB should be disabled */
9257                 pf->flags |= I40E_FLAG_DCB_CAPABLE;
9258
9259         /* Not DCB capable or capability disabled */
9260         if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9261                 return ret;
9262
9263         /* Ignore if event is not for Nearest Bridge */
9264         type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9265                 & I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9266         dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9267         if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9268                 return ret;
9269
9270         /* Check MIB Type and return if event for Remote MIB update */
9271         type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9272         dev_dbg(&pf->pdev->dev,
9273                 "LLDP event mib type %s\n", type ? "remote" : "local");
9274         if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9275                 /* Update the remote cached instance and return */
9276                 ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9277                                 I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9278                                 &hw->remote_dcbx_config);
9279                 goto exit;
9280         }
9281
9282         /* Store the old configuration */
9283         tmp_dcbx_cfg = hw->local_dcbx_config;
9284
9285         /* Reset the old DCBx configuration data */
9286         memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9287         /* Get updated DCBX data from firmware */
9288         ret = i40e_get_dcb_config(&pf->hw);
9289         if (ret) {
9290                 /* X710-T*L 2.5G and 5G speeds don't support DCB */
9291                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9292                     (hw->phy.link_info.link_speed &
9293                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9294                         dev_warn(&pf->pdev->dev,
9295                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9296                         pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9297                 } else {
9298                         dev_info(&pf->pdev->dev,
9299                                  "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
9300                                  i40e_stat_str(&pf->hw, ret),
9301                                  i40e_aq_str(&pf->hw,
9302                                              pf->hw.aq.asq_last_status));
9303                 }
9304                 goto exit;
9305         }
9306
9307         /* No change detected in DCBX configs */
9308         if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9309                     sizeof(tmp_dcbx_cfg))) {
9310                 dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9311                 goto exit;
9312         }
9313
9314         need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9315                                                &hw->local_dcbx_config);
9316
9317         i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9318
9319         if (!need_reconfig)
9320                 goto exit;
9321
9322         /* Enable DCB tagging only when more than one TC */
9323         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9324                 pf->flags |= I40E_FLAG_DCB_ENABLED;
9325         else
9326                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9327
9328         set_bit(__I40E_PORT_SUSPENDED, pf->state);
9329         /* Reconfiguration needed quiesce all VSIs */
9330         i40e_pf_quiesce_all_vsi(pf);
9331
9332         /* Changes in configuration update VEB/VSI */
9333         i40e_dcb_reconfigure(pf);
9334
9335         ret = i40e_resume_port_tx(pf);
9336
9337         clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9338         /* In case of error no point in resuming VSIs */
9339         if (ret)
9340                 goto exit;
9341
9342         /* Wait for the PF's queues to be disabled */
9343         ret = i40e_pf_wait_queues_disabled(pf);
9344         if (ret) {
9345                 /* Schedule PF reset to recover */
9346                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9347                 i40e_service_event_schedule(pf);
9348         } else {
9349                 i40e_pf_unquiesce_all_vsi(pf);
9350                 set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9351                 set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9352         }
9353
9354 exit:
9355         return ret;
9356 }
9357 #endif /* CONFIG_I40E_DCB */
9358
9359 /**
9360  * i40e_do_reset_safe - Protected reset path for userland calls.
9361  * @pf: board private structure
9362  * @reset_flags: which reset is requested
9363  *
9364  **/
9365 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9366 {
9367         rtnl_lock();
9368         i40e_do_reset(pf, reset_flags, true);
9369         rtnl_unlock();
9370 }
9371
9372 /**
9373  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9374  * @pf: board private structure
9375  * @e: event info posted on ARQ
9376  *
9377  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9378  * and VF queues
9379  **/
9380 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9381                                            struct i40e_arq_event_info *e)
9382 {
9383         struct i40e_aqc_lan_overflow *data =
9384                 (struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9385         u32 queue = le32_to_cpu(data->prtdcb_rupto);
9386         u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9387         struct i40e_hw *hw = &pf->hw;
9388         struct i40e_vf *vf;
9389         u16 vf_id;
9390
9391         dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9392                 queue, qtx_ctl);
9393
9394         /* Queue belongs to VF, find the VF and issue VF reset */
9395         if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9396             >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9397                 vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9398                          >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9399                 vf_id -= hw->func_caps.vf_base_id;
9400                 vf = &pf->vf[vf_id];
9401                 i40e_vc_notify_vf_reset(vf);
9402                 /* Allow VF to process pending reset notification */
9403                 msleep(20);
9404                 i40e_reset_vf(vf, false);
9405         }
9406 }
9407
9408 /**
9409  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9410  * @pf: board private structure
9411  **/
9412 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9413 {
9414         u32 val, fcnt_prog;
9415
9416         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9417         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9418         return fcnt_prog;
9419 }
9420
9421 /**
9422  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9423  * @pf: board private structure
9424  **/
9425 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9426 {
9427         u32 val, fcnt_prog;
9428
9429         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9430         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9431                     ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9432                       I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9433         return fcnt_prog;
9434 }
9435
9436 /**
9437  * i40e_get_global_fd_count - Get total FD filters programmed on device
9438  * @pf: board private structure
9439  **/
9440 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9441 {
9442         u32 val, fcnt_prog;
9443
9444         val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9445         fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9446                     ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9447                      I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9448         return fcnt_prog;
9449 }
9450
9451 /**
9452  * i40e_reenable_fdir_sb - Restore FDir SB capability
9453  * @pf: board private structure
9454  **/
9455 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9456 {
9457         if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9458                 if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9459                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9460                         dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9461 }
9462
9463 /**
9464  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9465  * @pf: board private structure
9466  **/
9467 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9468 {
9469         if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9470                 /* ATR uses the same filtering logic as SB rules. It only
9471                  * functions properly if the input set mask is at the default
9472                  * settings. It is safe to restore the default input set
9473                  * because there are no active TCPv4 filter rules.
9474                  */
9475                 i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9476                                         I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9477                                         I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9478
9479                 if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9480                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9481                         dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9482         }
9483 }
9484
9485 /**
9486  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9487  * @pf: board private structure
9488  * @filter: FDir filter to remove
9489  */
9490 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9491                                        struct i40e_fdir_filter *filter)
9492 {
9493         /* Update counters */
9494         pf->fdir_pf_active_filters--;
9495         pf->fd_inv = 0;
9496
9497         switch (filter->flow_type) {
9498         case TCP_V4_FLOW:
9499                 pf->fd_tcp4_filter_cnt--;
9500                 break;
9501         case UDP_V4_FLOW:
9502                 pf->fd_udp4_filter_cnt--;
9503                 break;
9504         case SCTP_V4_FLOW:
9505                 pf->fd_sctp4_filter_cnt--;
9506                 break;
9507         case TCP_V6_FLOW:
9508                 pf->fd_tcp6_filter_cnt--;
9509                 break;
9510         case UDP_V6_FLOW:
9511                 pf->fd_udp6_filter_cnt--;
9512                 break;
9513         case SCTP_V6_FLOW:
9514                 pf->fd_udp6_filter_cnt--;
9515                 break;
9516         case IP_USER_FLOW:
9517                 switch (filter->ipl4_proto) {
9518                 case IPPROTO_TCP:
9519                         pf->fd_tcp4_filter_cnt--;
9520                         break;
9521                 case IPPROTO_UDP:
9522                         pf->fd_udp4_filter_cnt--;
9523                         break;
9524                 case IPPROTO_SCTP:
9525                         pf->fd_sctp4_filter_cnt--;
9526                         break;
9527                 case IPPROTO_IP:
9528                         pf->fd_ip4_filter_cnt--;
9529                         break;
9530                 }
9531                 break;
9532         case IPV6_USER_FLOW:
9533                 switch (filter->ipl4_proto) {
9534                 case IPPROTO_TCP:
9535                         pf->fd_tcp6_filter_cnt--;
9536                         break;
9537                 case IPPROTO_UDP:
9538                         pf->fd_udp6_filter_cnt--;
9539                         break;
9540                 case IPPROTO_SCTP:
9541                         pf->fd_sctp6_filter_cnt--;
9542                         break;
9543                 case IPPROTO_IP:
9544                         pf->fd_ip6_filter_cnt--;
9545                         break;
9546                 }
9547                 break;
9548         }
9549
9550         /* Remove the filter from the list and free memory */
9551         hlist_del(&filter->fdir_node);
9552         kfree(filter);
9553 }
9554
9555 /**
9556  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9557  * @pf: board private structure
9558  **/
9559 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9560 {
9561         struct i40e_fdir_filter *filter;
9562         u32 fcnt_prog, fcnt_avail;
9563         struct hlist_node *node;
9564
9565         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9566                 return;
9567
9568         /* Check if we have enough room to re-enable FDir SB capability. */
9569         fcnt_prog = i40e_get_global_fd_count(pf);
9570         fcnt_avail = pf->fdir_pf_filter_count;
9571         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9572             (pf->fd_add_err == 0) ||
9573             (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9574                 i40e_reenable_fdir_sb(pf);
9575
9576         /* We should wait for even more space before re-enabling ATR.
9577          * Additionally, we cannot enable ATR as long as we still have TCP SB
9578          * rules active.
9579          */
9580         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9581             pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9582                 i40e_reenable_fdir_atr(pf);
9583
9584         /* if hw had a problem adding a filter, delete it */
9585         if (pf->fd_inv > 0) {
9586                 hlist_for_each_entry_safe(filter, node,
9587                                           &pf->fdir_filter_list, fdir_node)
9588                         if (filter->fd_id == pf->fd_inv)
9589                                 i40e_delete_invalid_filter(pf, filter);
9590         }
9591 }
9592
9593 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9594 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9595 /**
9596  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9597  * @pf: board private structure
9598  **/
9599 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9600 {
9601         unsigned long min_flush_time;
9602         int flush_wait_retry = 50;
9603         bool disable_atr = false;
9604         int fd_room;
9605         int reg;
9606
9607         if (!time_after(jiffies, pf->fd_flush_timestamp +
9608                                  (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9609                 return;
9610
9611         /* If the flush is happening too quick and we have mostly SB rules we
9612          * should not re-enable ATR for some time.
9613          */
9614         min_flush_time = pf->fd_flush_timestamp +
9615                          (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9616         fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9617
9618         if (!(time_after(jiffies, min_flush_time)) &&
9619             (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9620                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9621                         dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9622                 disable_atr = true;
9623         }
9624
9625         pf->fd_flush_timestamp = jiffies;
9626         set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9627         /* flush all filters */
9628         wr32(&pf->hw, I40E_PFQF_CTL_1,
9629              I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9630         i40e_flush(&pf->hw);
9631         pf->fd_flush_cnt++;
9632         pf->fd_add_err = 0;
9633         do {
9634                 /* Check FD flush status every 5-6msec */
9635                 usleep_range(5000, 6000);
9636                 reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9637                 if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9638                         break;
9639         } while (flush_wait_retry--);
9640         if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9641                 dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9642         } else {
9643                 /* replay sideband filters */
9644                 i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9645                 if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9646                         clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9647                 clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9648                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9649                         dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9650         }
9651 }
9652
9653 /**
9654  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9655  * @pf: board private structure
9656  **/
9657 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9658 {
9659         return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9660 }
9661
9662 /**
9663  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9664  * @pf: board private structure
9665  **/
9666 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9667 {
9668
9669         /* if interface is down do nothing */
9670         if (test_bit(__I40E_DOWN, pf->state))
9671                 return;
9672
9673         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9674                 i40e_fdir_flush_and_replay(pf);
9675
9676         i40e_fdir_check_and_reenable(pf);
9677
9678 }
9679
9680 /**
9681  * i40e_vsi_link_event - notify VSI of a link event
9682  * @vsi: vsi to be notified
9683  * @link_up: link up or down
9684  **/
9685 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9686 {
9687         if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9688                 return;
9689
9690         switch (vsi->type) {
9691         case I40E_VSI_MAIN:
9692                 if (!vsi->netdev || !vsi->netdev_registered)
9693                         break;
9694
9695                 if (link_up) {
9696                         netif_carrier_on(vsi->netdev);
9697                         netif_tx_wake_all_queues(vsi->netdev);
9698                 } else {
9699                         netif_carrier_off(vsi->netdev);
9700                         netif_tx_stop_all_queues(vsi->netdev);
9701                 }
9702                 break;
9703
9704         case I40E_VSI_SRIOV:
9705         case I40E_VSI_VMDQ2:
9706         case I40E_VSI_CTRL:
9707         case I40E_VSI_IWARP:
9708         case I40E_VSI_MIRROR:
9709         default:
9710                 /* there is no notification for other VSIs */
9711                 break;
9712         }
9713 }
9714
9715 /**
9716  * i40e_veb_link_event - notify elements on the veb of a link event
9717  * @veb: veb to be notified
9718  * @link_up: link up or down
9719  **/
9720 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9721 {
9722         struct i40e_pf *pf;
9723         int i;
9724
9725         if (!veb || !veb->pf)
9726                 return;
9727         pf = veb->pf;
9728
9729         /* depth first... */
9730         for (i = 0; i < I40E_MAX_VEB; i++)
9731                 if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9732                         i40e_veb_link_event(pf->veb[i], link_up);
9733
9734         /* ... now the local VSIs */
9735         for (i = 0; i < pf->num_alloc_vsi; i++)
9736                 if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9737                         i40e_vsi_link_event(pf->vsi[i], link_up);
9738 }
9739
9740 /**
9741  * i40e_link_event - Update netif_carrier status
9742  * @pf: board private structure
9743  **/
9744 static void i40e_link_event(struct i40e_pf *pf)
9745 {
9746         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9747         u8 new_link_speed, old_link_speed;
9748         i40e_status status;
9749         bool new_link, old_link;
9750 #ifdef CONFIG_I40E_DCB
9751         int err;
9752 #endif /* CONFIG_I40E_DCB */
9753
9754         /* set this to force the get_link_status call to refresh state */
9755         pf->hw.phy.get_link_info = true;
9756         old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9757         status = i40e_get_link_status(&pf->hw, &new_link);
9758
9759         /* On success, disable temp link polling */
9760         if (status == I40E_SUCCESS) {
9761                 clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9762         } else {
9763                 /* Enable link polling temporarily until i40e_get_link_status
9764                  * returns I40E_SUCCESS
9765                  */
9766                 set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9767                 dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9768                         status);
9769                 return;
9770         }
9771
9772         old_link_speed = pf->hw.phy.link_info_old.link_speed;
9773         new_link_speed = pf->hw.phy.link_info.link_speed;
9774
9775         if (new_link == old_link &&
9776             new_link_speed == old_link_speed &&
9777             (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9778              new_link == netif_carrier_ok(vsi->netdev)))
9779                 return;
9780
9781         i40e_print_link_message(vsi, new_link);
9782
9783         /* Notify the base of the switch tree connected to
9784          * the link.  Floating VEBs are not notified.
9785          */
9786         if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9787                 i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9788         else
9789                 i40e_vsi_link_event(vsi, new_link);
9790
9791         if (pf->vf)
9792                 i40e_vc_notify_link_state(pf);
9793
9794         if (pf->flags & I40E_FLAG_PTP)
9795                 i40e_ptp_set_increment(pf);
9796 #ifdef CONFIG_I40E_DCB
9797         if (new_link == old_link)
9798                 return;
9799         /* Not SW DCB so firmware will take care of default settings */
9800         if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9801                 return;
9802
9803         /* We cover here only link down, as after link up in case of SW DCB
9804          * SW LLDP agent will take care of setting it up
9805          */
9806         if (!new_link) {
9807                 dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9808                 memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9809                 err = i40e_dcb_sw_default_config(pf);
9810                 if (err) {
9811                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9812                                        I40E_FLAG_DCB_ENABLED);
9813                 } else {
9814                         pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9815                                        DCB_CAP_DCBX_VER_IEEE;
9816                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
9817                         pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9818                 }
9819         }
9820 #endif /* CONFIG_I40E_DCB */
9821 }
9822
9823 /**
9824  * i40e_watchdog_subtask - periodic checks not using event driven response
9825  * @pf: board private structure
9826  **/
9827 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9828 {
9829         int i;
9830
9831         /* if interface is down do nothing */
9832         if (test_bit(__I40E_DOWN, pf->state) ||
9833             test_bit(__I40E_CONFIG_BUSY, pf->state))
9834                 return;
9835
9836         /* make sure we don't do these things too often */
9837         if (time_before(jiffies, (pf->service_timer_previous +
9838                                   pf->service_timer_period)))
9839                 return;
9840         pf->service_timer_previous = jiffies;
9841
9842         if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9843             test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9844                 i40e_link_event(pf);
9845
9846         /* Update the stats for active netdevs so the network stack
9847          * can look at updated numbers whenever it cares to
9848          */
9849         for (i = 0; i < pf->num_alloc_vsi; i++)
9850                 if (pf->vsi[i] && pf->vsi[i]->netdev)
9851                         i40e_update_stats(pf->vsi[i]);
9852
9853         if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9854                 /* Update the stats for the active switching components */
9855                 for (i = 0; i < I40E_MAX_VEB; i++)
9856                         if (pf->veb[i])
9857                                 i40e_update_veb_stats(pf->veb[i]);
9858         }
9859
9860         i40e_ptp_rx_hang(pf);
9861         i40e_ptp_tx_hang(pf);
9862 }
9863
9864 /**
9865  * i40e_reset_subtask - Set up for resetting the device and driver
9866  * @pf: board private structure
9867  **/
9868 static void i40e_reset_subtask(struct i40e_pf *pf)
9869 {
9870         u32 reset_flags = 0;
9871
9872         if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
9873                 reset_flags |= BIT(__I40E_REINIT_REQUESTED);
9874                 clear_bit(__I40E_REINIT_REQUESTED, pf->state);
9875         }
9876         if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
9877                 reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
9878                 clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9879         }
9880         if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
9881                 reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
9882                 clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
9883         }
9884         if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
9885                 reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
9886                 clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
9887         }
9888         if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
9889                 reset_flags |= BIT(__I40E_DOWN_REQUESTED);
9890                 clear_bit(__I40E_DOWN_REQUESTED, pf->state);
9891         }
9892
9893         /* If there's a recovery already waiting, it takes
9894          * precedence before starting a new reset sequence.
9895          */
9896         if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
9897                 i40e_prep_for_reset(pf);
9898                 i40e_reset(pf);
9899                 i40e_rebuild(pf, false, false);
9900         }
9901
9902         /* If we're already down or resetting, just bail */
9903         if (reset_flags &&
9904             !test_bit(__I40E_DOWN, pf->state) &&
9905             !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
9906                 i40e_do_reset(pf, reset_flags, false);
9907         }
9908 }
9909
9910 /**
9911  * i40e_handle_link_event - Handle link event
9912  * @pf: board private structure
9913  * @e: event info posted on ARQ
9914  **/
9915 static void i40e_handle_link_event(struct i40e_pf *pf,
9916                                    struct i40e_arq_event_info *e)
9917 {
9918         struct i40e_aqc_get_link_status *status =
9919                 (struct i40e_aqc_get_link_status *)&e->desc.params.raw;
9920
9921         /* Do a new status request to re-enable LSE reporting
9922          * and load new status information into the hw struct
9923          * This completely ignores any state information
9924          * in the ARQ event info, instead choosing to always
9925          * issue the AQ update link status command.
9926          */
9927         i40e_link_event(pf);
9928
9929         /* Check if module meets thermal requirements */
9930         if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
9931                 dev_err(&pf->pdev->dev,
9932                         "Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
9933                 dev_err(&pf->pdev->dev,
9934                         "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9935         } else {
9936                 /* check for unqualified module, if link is down, suppress
9937                  * the message if link was forced to be down.
9938                  */
9939                 if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
9940                     (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
9941                     (!(status->link_info & I40E_AQ_LINK_UP)) &&
9942                     (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
9943                         dev_err(&pf->pdev->dev,
9944                                 "Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
9945                         dev_err(&pf->pdev->dev,
9946                                 "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9947                 }
9948         }
9949 }
9950
9951 /**
9952  * i40e_clean_adminq_subtask - Clean the AdminQ rings
9953  * @pf: board private structure
9954  **/
9955 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
9956 {
9957         struct i40e_arq_event_info event;
9958         struct i40e_hw *hw = &pf->hw;
9959         u16 pending, i = 0;
9960         i40e_status ret;
9961         u16 opcode;
9962         u32 oldval;
9963         u32 val;
9964
9965         /* Do not run clean AQ when PF reset fails */
9966         if (test_bit(__I40E_RESET_FAILED, pf->state))
9967                 return;
9968
9969         /* check for error indications */
9970         val = rd32(&pf->hw, pf->hw.aq.arq.len);
9971         oldval = val;
9972         if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
9973                 if (hw->debug_mask & I40E_DEBUG_AQ)
9974                         dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
9975                 val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
9976         }
9977         if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
9978                 if (hw->debug_mask & I40E_DEBUG_AQ)
9979                         dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
9980                 val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
9981                 pf->arq_overflows++;
9982         }
9983         if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
9984                 if (hw->debug_mask & I40E_DEBUG_AQ)
9985                         dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
9986                 val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
9987         }
9988         if (oldval != val)
9989                 wr32(&pf->hw, pf->hw.aq.arq.len, val);
9990
9991         val = rd32(&pf->hw, pf->hw.aq.asq.len);
9992         oldval = val;
9993         if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
9994                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9995                         dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
9996                 val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
9997         }
9998         if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
9999                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10000                         dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
10001                 val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
10002         }
10003         if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
10004                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
10005                         dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
10006                 val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
10007         }
10008         if (oldval != val)
10009                 wr32(&pf->hw, pf->hw.aq.asq.len, val);
10010
10011         event.buf_len = I40E_MAX_AQ_BUF_SIZE;
10012         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
10013         if (!event.msg_buf)
10014                 return;
10015
10016         do {
10017                 ret = i40e_clean_arq_element(hw, &event, &pending);
10018                 if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
10019                         break;
10020                 else if (ret) {
10021                         dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
10022                         break;
10023                 }
10024
10025                 opcode = le16_to_cpu(event.desc.opcode);
10026                 switch (opcode) {
10027
10028                 case i40e_aqc_opc_get_link_status:
10029                         rtnl_lock();
10030                         i40e_handle_link_event(pf, &event);
10031                         rtnl_unlock();
10032                         break;
10033                 case i40e_aqc_opc_send_msg_to_pf:
10034                         ret = i40e_vc_process_vf_msg(pf,
10035                                         le16_to_cpu(event.desc.retval),
10036                                         le32_to_cpu(event.desc.cookie_high),
10037                                         le32_to_cpu(event.desc.cookie_low),
10038                                         event.msg_buf,
10039                                         event.msg_len);
10040                         break;
10041                 case i40e_aqc_opc_lldp_update_mib:
10042                         dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
10043 #ifdef CONFIG_I40E_DCB
10044                         rtnl_lock();
10045                         i40e_handle_lldp_event(pf, &event);
10046                         rtnl_unlock();
10047 #endif /* CONFIG_I40E_DCB */
10048                         break;
10049                 case i40e_aqc_opc_event_lan_overflow:
10050                         dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
10051                         i40e_handle_lan_overflow_event(pf, &event);
10052                         break;
10053                 case i40e_aqc_opc_send_msg_to_peer:
10054                         dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
10055                         break;
10056                 case i40e_aqc_opc_nvm_erase:
10057                 case i40e_aqc_opc_nvm_update:
10058                 case i40e_aqc_opc_oem_post_update:
10059                         i40e_debug(&pf->hw, I40E_DEBUG_NVM,
10060                                    "ARQ NVM operation 0x%04x completed\n",
10061                                    opcode);
10062                         break;
10063                 default:
10064                         dev_info(&pf->pdev->dev,
10065                                  "ARQ: Unknown event 0x%04x ignored\n",
10066                                  opcode);
10067                         break;
10068                 }
10069         } while (i++ < pf->adminq_work_limit);
10070
10071         if (i < pf->adminq_work_limit)
10072                 clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
10073
10074         /* re-enable Admin queue interrupt cause */
10075         val = rd32(hw, I40E_PFINT_ICR0_ENA);
10076         val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
10077         wr32(hw, I40E_PFINT_ICR0_ENA, val);
10078         i40e_flush(hw);
10079
10080         kfree(event.msg_buf);
10081 }
10082
10083 /**
10084  * i40e_verify_eeprom - make sure eeprom is good to use
10085  * @pf: board private structure
10086  **/
10087 static void i40e_verify_eeprom(struct i40e_pf *pf)
10088 {
10089         int err;
10090
10091         err = i40e_diag_eeprom_test(&pf->hw);
10092         if (err) {
10093                 /* retry in case of garbage read */
10094                 err = i40e_diag_eeprom_test(&pf->hw);
10095                 if (err) {
10096                         dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
10097                                  err);
10098                         set_bit(__I40E_BAD_EEPROM, pf->state);
10099                 }
10100         }
10101
10102         if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
10103                 dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
10104                 clear_bit(__I40E_BAD_EEPROM, pf->state);
10105         }
10106 }
10107
10108 /**
10109  * i40e_enable_pf_switch_lb
10110  * @pf: pointer to the PF structure
10111  *
10112  * enable switch loop back or die - no point in a return value
10113  **/
10114 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
10115 {
10116         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10117         struct i40e_vsi_context ctxt;
10118         int ret;
10119
10120         ctxt.seid = pf->main_vsi_seid;
10121         ctxt.pf_num = pf->hw.pf_id;
10122         ctxt.vf_num = 0;
10123         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10124         if (ret) {
10125                 dev_info(&pf->pdev->dev,
10126                          "couldn't get PF vsi config, err %s aq_err %s\n",
10127                          i40e_stat_str(&pf->hw, ret),
10128                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10129                 return;
10130         }
10131         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10132         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10133         ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10134
10135         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10136         if (ret) {
10137                 dev_info(&pf->pdev->dev,
10138                          "update vsi switch failed, err %s aq_err %s\n",
10139                          i40e_stat_str(&pf->hw, ret),
10140                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10141         }
10142 }
10143
10144 /**
10145  * i40e_disable_pf_switch_lb
10146  * @pf: pointer to the PF structure
10147  *
10148  * disable switch loop back or die - no point in a return value
10149  **/
10150 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
10151 {
10152         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10153         struct i40e_vsi_context ctxt;
10154         int ret;
10155
10156         ctxt.seid = pf->main_vsi_seid;
10157         ctxt.pf_num = pf->hw.pf_id;
10158         ctxt.vf_num = 0;
10159         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
10160         if (ret) {
10161                 dev_info(&pf->pdev->dev,
10162                          "couldn't get PF vsi config, err %s aq_err %s\n",
10163                          i40e_stat_str(&pf->hw, ret),
10164                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10165                 return;
10166         }
10167         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
10168         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
10169         ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
10170
10171         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
10172         if (ret) {
10173                 dev_info(&pf->pdev->dev,
10174                          "update vsi switch failed, err %s aq_err %s\n",
10175                          i40e_stat_str(&pf->hw, ret),
10176                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10177         }
10178 }
10179
10180 /**
10181  * i40e_config_bridge_mode - Configure the HW bridge mode
10182  * @veb: pointer to the bridge instance
10183  *
10184  * Configure the loop back mode for the LAN VSI that is downlink to the
10185  * specified HW bridge instance. It is expected this function is called
10186  * when a new HW bridge is instantiated.
10187  **/
10188 static void i40e_config_bridge_mode(struct i40e_veb *veb)
10189 {
10190         struct i40e_pf *pf = veb->pf;
10191
10192         if (pf->hw.debug_mask & I40E_DEBUG_LAN)
10193                 dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
10194                          veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
10195         if (veb->bridge_mode & BRIDGE_MODE_VEPA)
10196                 i40e_disable_pf_switch_lb(pf);
10197         else
10198                 i40e_enable_pf_switch_lb(pf);
10199 }
10200
10201 /**
10202  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10203  * @veb: pointer to the VEB instance
10204  *
10205  * This is a recursive function that first builds the attached VSIs then
10206  * recurses in to build the next layer of VEB.  We track the connections
10207  * through our own index numbers because the seid's from the HW could
10208  * change across the reset.
10209  **/
10210 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10211 {
10212         struct i40e_vsi *ctl_vsi = NULL;
10213         struct i40e_pf *pf = veb->pf;
10214         int v, veb_idx;
10215         int ret;
10216
10217         /* build VSI that owns this VEB, temporarily attached to base VEB */
10218         for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10219                 if (pf->vsi[v] &&
10220                     pf->vsi[v]->veb_idx == veb->idx &&
10221                     pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10222                         ctl_vsi = pf->vsi[v];
10223                         break;
10224                 }
10225         }
10226         if (!ctl_vsi) {
10227                 dev_info(&pf->pdev->dev,
10228                          "missing owner VSI for veb_idx %d\n", veb->idx);
10229                 ret = -ENOENT;
10230                 goto end_reconstitute;
10231         }
10232         if (ctl_vsi != pf->vsi[pf->lan_vsi])
10233                 ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10234         ret = i40e_add_vsi(ctl_vsi);
10235         if (ret) {
10236                 dev_info(&pf->pdev->dev,
10237                          "rebuild of veb_idx %d owner VSI failed: %d\n",
10238                          veb->idx, ret);
10239                 goto end_reconstitute;
10240         }
10241         i40e_vsi_reset_stats(ctl_vsi);
10242
10243         /* create the VEB in the switch and move the VSI onto the VEB */
10244         ret = i40e_add_veb(veb, ctl_vsi);
10245         if (ret)
10246                 goto end_reconstitute;
10247
10248         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10249                 veb->bridge_mode = BRIDGE_MODE_VEB;
10250         else
10251                 veb->bridge_mode = BRIDGE_MODE_VEPA;
10252         i40e_config_bridge_mode(veb);
10253
10254         /* create the remaining VSIs attached to this VEB */
10255         for (v = 0; v < pf->num_alloc_vsi; v++) {
10256                 if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10257                         continue;
10258
10259                 if (pf->vsi[v]->veb_idx == veb->idx) {
10260                         struct i40e_vsi *vsi = pf->vsi[v];
10261
10262                         vsi->uplink_seid = veb->seid;
10263                         ret = i40e_add_vsi(vsi);
10264                         if (ret) {
10265                                 dev_info(&pf->pdev->dev,
10266                                          "rebuild of vsi_idx %d failed: %d\n",
10267                                          v, ret);
10268                                 goto end_reconstitute;
10269                         }
10270                         i40e_vsi_reset_stats(vsi);
10271                 }
10272         }
10273
10274         /* create any VEBs attached to this VEB - RECURSION */
10275         for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10276                 if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10277                         pf->veb[veb_idx]->uplink_seid = veb->seid;
10278                         ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10279                         if (ret)
10280                                 break;
10281                 }
10282         }
10283
10284 end_reconstitute:
10285         return ret;
10286 }
10287
10288 /**
10289  * i40e_get_capabilities - get info about the HW
10290  * @pf: the PF struct
10291  * @list_type: AQ capability to be queried
10292  **/
10293 static int i40e_get_capabilities(struct i40e_pf *pf,
10294                                  enum i40e_admin_queue_opc list_type)
10295 {
10296         struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10297         u16 data_size;
10298         int buf_len;
10299         int err;
10300
10301         buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10302         do {
10303                 cap_buf = kzalloc(buf_len, GFP_KERNEL);
10304                 if (!cap_buf)
10305                         return -ENOMEM;
10306
10307                 /* this loads the data into the hw struct for us */
10308                 err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10309                                                     &data_size, list_type,
10310                                                     NULL);
10311                 /* data loaded, buffer no longer needed */
10312                 kfree(cap_buf);
10313
10314                 if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10315                         /* retry with a larger buffer */
10316                         buf_len = data_size;
10317                 } else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10318                         dev_info(&pf->pdev->dev,
10319                                  "capability discovery failed, err %s aq_err %s\n",
10320                                  i40e_stat_str(&pf->hw, err),
10321                                  i40e_aq_str(&pf->hw,
10322                                              pf->hw.aq.asq_last_status));
10323                         return -ENODEV;
10324                 }
10325         } while (err);
10326
10327         if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10328                 if (list_type == i40e_aqc_opc_list_func_capabilities) {
10329                         dev_info(&pf->pdev->dev,
10330                                  "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",
10331                                  pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10332                                  pf->hw.func_caps.num_msix_vectors,
10333                                  pf->hw.func_caps.num_msix_vectors_vf,
10334                                  pf->hw.func_caps.fd_filters_guaranteed,
10335                                  pf->hw.func_caps.fd_filters_best_effort,
10336                                  pf->hw.func_caps.num_tx_qp,
10337                                  pf->hw.func_caps.num_vsis);
10338                 } else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10339                         dev_info(&pf->pdev->dev,
10340                                  "switch_mode=0x%04x, function_valid=0x%08x\n",
10341                                  pf->hw.dev_caps.switch_mode,
10342                                  pf->hw.dev_caps.valid_functions);
10343                         dev_info(&pf->pdev->dev,
10344                                  "SR-IOV=%d, num_vfs for all function=%u\n",
10345                                  pf->hw.dev_caps.sr_iov_1_1,
10346                                  pf->hw.dev_caps.num_vfs);
10347                         dev_info(&pf->pdev->dev,
10348                                  "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10349                                  pf->hw.dev_caps.num_vsis,
10350                                  pf->hw.dev_caps.num_rx_qp,
10351                                  pf->hw.dev_caps.num_tx_qp);
10352                 }
10353         }
10354         if (list_type == i40e_aqc_opc_list_func_capabilities) {
10355 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10356                        + pf->hw.func_caps.num_vfs)
10357                 if (pf->hw.revision_id == 0 &&
10358                     pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10359                         dev_info(&pf->pdev->dev,
10360                                  "got num_vsis %d, setting num_vsis to %d\n",
10361                                  pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10362                         pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10363                 }
10364         }
10365         return 0;
10366 }
10367
10368 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10369
10370 /**
10371  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10372  * @pf: board private structure
10373  **/
10374 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10375 {
10376         struct i40e_vsi *vsi;
10377
10378         /* quick workaround for an NVM issue that leaves a critical register
10379          * uninitialized
10380          */
10381         if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10382                 static const u32 hkey[] = {
10383                         0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10384                         0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10385                         0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10386                         0x95b3a76d};
10387                 int i;
10388
10389                 for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10390                         wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10391         }
10392
10393         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10394                 return;
10395
10396         /* find existing VSI and see if it needs configuring */
10397         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10398
10399         /* create a new VSI if none exists */
10400         if (!vsi) {
10401                 vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10402                                      pf->vsi[pf->lan_vsi]->seid, 0);
10403                 if (!vsi) {
10404                         dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10405                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10406                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10407                         return;
10408                 }
10409         }
10410
10411         i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10412 }
10413
10414 /**
10415  * i40e_fdir_teardown - release the Flow Director resources
10416  * @pf: board private structure
10417  **/
10418 static void i40e_fdir_teardown(struct i40e_pf *pf)
10419 {
10420         struct i40e_vsi *vsi;
10421
10422         i40e_fdir_filter_exit(pf);
10423         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10424         if (vsi)
10425                 i40e_vsi_release(vsi);
10426 }
10427
10428 /**
10429  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10430  * @vsi: PF main vsi
10431  * @seid: seid of main or channel VSIs
10432  *
10433  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10434  * existed before reset
10435  **/
10436 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10437 {
10438         struct i40e_cloud_filter *cfilter;
10439         struct i40e_pf *pf = vsi->back;
10440         struct hlist_node *node;
10441         i40e_status ret;
10442
10443         /* Add cloud filters back if they exist */
10444         hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10445                                   cloud_node) {
10446                 if (cfilter->seid != seid)
10447                         continue;
10448
10449                 if (cfilter->dst_port)
10450                         ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10451                                                                 true);
10452                 else
10453                         ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10454
10455                 if (ret) {
10456                         dev_dbg(&pf->pdev->dev,
10457                                 "Failed to rebuild cloud filter, err %s aq_err %s\n",
10458                                 i40e_stat_str(&pf->hw, ret),
10459                                 i40e_aq_str(&pf->hw,
10460                                             pf->hw.aq.asq_last_status));
10461                         return ret;
10462                 }
10463         }
10464         return 0;
10465 }
10466
10467 /**
10468  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10469  * @vsi: PF main vsi
10470  *
10471  * Rebuilds channel VSIs if they existed before reset
10472  **/
10473 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10474 {
10475         struct i40e_channel *ch, *ch_tmp;
10476         i40e_status ret;
10477
10478         if (list_empty(&vsi->ch_list))
10479                 return 0;
10480
10481         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10482                 if (!ch->initialized)
10483                         break;
10484                 /* Proceed with creation of channel (VMDq2) VSI */
10485                 ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10486                 if (ret) {
10487                         dev_info(&vsi->back->pdev->dev,
10488                                  "failed to rebuild channels using uplink_seid %u\n",
10489                                  vsi->uplink_seid);
10490                         return ret;
10491                 }
10492                 /* Reconfigure TX queues using QTX_CTL register */
10493                 ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10494                 if (ret) {
10495                         dev_info(&vsi->back->pdev->dev,
10496                                  "failed to configure TX rings for channel %u\n",
10497                                  ch->seid);
10498                         return ret;
10499                 }
10500                 /* update 'next_base_queue' */
10501                 vsi->next_base_queue = vsi->next_base_queue +
10502                                                         ch->num_queue_pairs;
10503                 if (ch->max_tx_rate) {
10504                         u64 credits = ch->max_tx_rate;
10505
10506                         if (i40e_set_bw_limit(vsi, ch->seid,
10507                                               ch->max_tx_rate))
10508                                 return -EINVAL;
10509
10510                         do_div(credits, I40E_BW_CREDIT_DIVISOR);
10511                         dev_dbg(&vsi->back->pdev->dev,
10512                                 "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10513                                 ch->max_tx_rate,
10514                                 credits,
10515                                 ch->seid);
10516                 }
10517                 ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10518                 if (ret) {
10519                         dev_dbg(&vsi->back->pdev->dev,
10520                                 "Failed to rebuild cloud filters for channel VSI %u\n",
10521                                 ch->seid);
10522                         return ret;
10523                 }
10524         }
10525         return 0;
10526 }
10527
10528 /**
10529  * i40e_prep_for_reset - prep for the core to reset
10530  * @pf: board private structure
10531  *
10532  * Close up the VFs and other things in prep for PF Reset.
10533   **/
10534 static void i40e_prep_for_reset(struct i40e_pf *pf)
10535 {
10536         struct i40e_hw *hw = &pf->hw;
10537         i40e_status ret = 0;
10538         u32 v;
10539
10540         clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10541         if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10542                 return;
10543         if (i40e_check_asq_alive(&pf->hw))
10544                 i40e_vc_notify_reset(pf);
10545
10546         dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10547
10548         /* quiesce the VSIs and their queues that are not already DOWN */
10549         i40e_pf_quiesce_all_vsi(pf);
10550
10551         for (v = 0; v < pf->num_alloc_vsi; v++) {
10552                 if (pf->vsi[v])
10553                         pf->vsi[v]->seid = 0;
10554         }
10555
10556         i40e_shutdown_adminq(&pf->hw);
10557
10558         /* call shutdown HMC */
10559         if (hw->hmc.hmc_obj) {
10560                 ret = i40e_shutdown_lan_hmc(hw);
10561                 if (ret)
10562                         dev_warn(&pf->pdev->dev,
10563                                  "shutdown_lan_hmc failed: %d\n", ret);
10564         }
10565
10566         /* Save the current PTP time so that we can restore the time after the
10567          * reset completes.
10568          */
10569         i40e_ptp_save_hw_time(pf);
10570 }
10571
10572 /**
10573  * i40e_send_version - update firmware with driver version
10574  * @pf: PF struct
10575  */
10576 static void i40e_send_version(struct i40e_pf *pf)
10577 {
10578         struct i40e_driver_version dv;
10579
10580         dv.major_version = 0xff;
10581         dv.minor_version = 0xff;
10582         dv.build_version = 0xff;
10583         dv.subbuild_version = 0;
10584         strlcpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10585         i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10586 }
10587
10588 /**
10589  * i40e_get_oem_version - get OEM specific version information
10590  * @hw: pointer to the hardware structure
10591  **/
10592 static void i40e_get_oem_version(struct i40e_hw *hw)
10593 {
10594         u16 block_offset = 0xffff;
10595         u16 block_length = 0;
10596         u16 capabilities = 0;
10597         u16 gen_snap = 0;
10598         u16 release = 0;
10599
10600 #define I40E_SR_NVM_OEM_VERSION_PTR             0x1B
10601 #define I40E_NVM_OEM_LENGTH_OFFSET              0x00
10602 #define I40E_NVM_OEM_CAPABILITIES_OFFSET        0x01
10603 #define I40E_NVM_OEM_GEN_OFFSET                 0x02
10604 #define I40E_NVM_OEM_RELEASE_OFFSET             0x03
10605 #define I40E_NVM_OEM_CAPABILITIES_MASK          0x000F
10606 #define I40E_NVM_OEM_LENGTH                     3
10607
10608         /* Check if pointer to OEM version block is valid. */
10609         i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10610         if (block_offset == 0xffff)
10611                 return;
10612
10613         /* Check if OEM version block has correct length. */
10614         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10615                            &block_length);
10616         if (block_length < I40E_NVM_OEM_LENGTH)
10617                 return;
10618
10619         /* Check if OEM version format is as expected. */
10620         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10621                            &capabilities);
10622         if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10623                 return;
10624
10625         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10626                            &gen_snap);
10627         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10628                            &release);
10629         hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10630         hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10631 }
10632
10633 /**
10634  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10635  * @pf: board private structure
10636  **/
10637 static int i40e_reset(struct i40e_pf *pf)
10638 {
10639         struct i40e_hw *hw = &pf->hw;
10640         i40e_status ret;
10641
10642         ret = i40e_pf_reset(hw);
10643         if (ret) {
10644                 dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10645                 set_bit(__I40E_RESET_FAILED, pf->state);
10646                 clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10647         } else {
10648                 pf->pfr_count++;
10649         }
10650         return ret;
10651 }
10652
10653 /**
10654  * i40e_rebuild - rebuild using a saved config
10655  * @pf: board private structure
10656  * @reinit: if the Main VSI needs to re-initialized.
10657  * @lock_acquired: indicates whether or not the lock has been acquired
10658  * before this function was called.
10659  **/
10660 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10661 {
10662         const bool is_recovery_mode_reported = i40e_check_recovery_mode(pf);
10663         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10664         struct i40e_hw *hw = &pf->hw;
10665         i40e_status ret;
10666         u32 val;
10667         int v;
10668
10669         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10670             is_recovery_mode_reported)
10671                 i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10672
10673         if (test_bit(__I40E_DOWN, pf->state) &&
10674             !test_bit(__I40E_RECOVERY_MODE, pf->state))
10675                 goto clear_recovery;
10676         dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10677
10678         /* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10679         ret = i40e_init_adminq(&pf->hw);
10680         if (ret) {
10681                 dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
10682                          i40e_stat_str(&pf->hw, ret),
10683                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10684                 goto clear_recovery;
10685         }
10686         i40e_get_oem_version(&pf->hw);
10687
10688         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state)) {
10689                 /* The following delay is necessary for firmware update. */
10690                 mdelay(1000);
10691         }
10692
10693         /* re-verify the eeprom if we just had an EMP reset */
10694         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10695                 i40e_verify_eeprom(pf);
10696
10697         /* if we are going out of or into recovery mode we have to act
10698          * accordingly with regard to resources initialization
10699          * and deinitialization
10700          */
10701         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10702                 if (i40e_get_capabilities(pf,
10703                                           i40e_aqc_opc_list_func_capabilities))
10704                         goto end_unlock;
10705
10706                 if (is_recovery_mode_reported) {
10707                         /* we're staying in recovery mode so we'll reinitialize
10708                          * misc vector here
10709                          */
10710                         if (i40e_setup_misc_vector_for_recovery_mode(pf))
10711                                 goto end_unlock;
10712                 } else {
10713                         if (!lock_acquired)
10714                                 rtnl_lock();
10715                         /* we're going out of recovery mode so we'll free
10716                          * the IRQ allocated specifically for recovery mode
10717                          * and restore the interrupt scheme
10718                          */
10719                         free_irq(pf->pdev->irq, pf);
10720                         i40e_clear_interrupt_scheme(pf);
10721                         if (i40e_restore_interrupt_scheme(pf))
10722                                 goto end_unlock;
10723                 }
10724
10725                 /* tell the firmware that we're starting */
10726                 i40e_send_version(pf);
10727
10728                 /* bail out in case recovery mode was detected, as there is
10729                  * no need for further configuration.
10730                  */
10731                 goto end_unlock;
10732         }
10733
10734         i40e_clear_pxe_mode(hw);
10735         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10736         if (ret)
10737                 goto end_core_reset;
10738
10739         ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10740                                 hw->func_caps.num_rx_qp, 0, 0);
10741         if (ret) {
10742                 dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10743                 goto end_core_reset;
10744         }
10745         ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10746         if (ret) {
10747                 dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10748                 goto end_core_reset;
10749         }
10750
10751 #ifdef CONFIG_I40E_DCB
10752         /* Enable FW to write a default DCB config on link-up
10753          * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10754          * is not supported with new link speed
10755          */
10756         if (i40e_is_tc_mqprio_enabled(pf)) {
10757                 i40e_aq_set_dcb_parameters(hw, false, NULL);
10758         } else {
10759                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10760                     (hw->phy.link_info.link_speed &
10761                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10762                         i40e_aq_set_dcb_parameters(hw, false, NULL);
10763                         dev_warn(&pf->pdev->dev,
10764                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10765                         pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10766                 } else {
10767                         i40e_aq_set_dcb_parameters(hw, true, NULL);
10768                         ret = i40e_init_pf_dcb(pf);
10769                         if (ret) {
10770                                 dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10771                                          ret);
10772                                 pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10773                                 /* Continue without DCB enabled */
10774                         }
10775                 }
10776         }
10777
10778 #endif /* CONFIG_I40E_DCB */
10779         if (!lock_acquired)
10780                 rtnl_lock();
10781         ret = i40e_setup_pf_switch(pf, reinit, true);
10782         if (ret)
10783                 goto end_unlock;
10784
10785         /* The driver only wants link up/down and module qualification
10786          * reports from firmware.  Note the negative logic.
10787          */
10788         ret = i40e_aq_set_phy_int_mask(&pf->hw,
10789                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
10790                                          I40E_AQ_EVENT_MEDIA_NA |
10791                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10792         if (ret)
10793                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
10794                          i40e_stat_str(&pf->hw, ret),
10795                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10796
10797         /* Rebuild the VSIs and VEBs that existed before reset.
10798          * They are still in our local switch element arrays, so only
10799          * need to rebuild the switch model in the HW.
10800          *
10801          * If there were VEBs but the reconstitution failed, we'll try
10802          * to recover minimal use by getting the basic PF VSI working.
10803          */
10804         if (vsi->uplink_seid != pf->mac_seid) {
10805                 dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10806                 /* find the one VEB connected to the MAC, and find orphans */
10807                 for (v = 0; v < I40E_MAX_VEB; v++) {
10808                         if (!pf->veb[v])
10809                                 continue;
10810
10811                         if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10812                             pf->veb[v]->uplink_seid == 0) {
10813                                 ret = i40e_reconstitute_veb(pf->veb[v]);
10814
10815                                 if (!ret)
10816                                         continue;
10817
10818                                 /* If Main VEB failed, we're in deep doodoo,
10819                                  * so give up rebuilding the switch and set up
10820                                  * for minimal rebuild of PF VSI.
10821                                  * If orphan failed, we'll report the error
10822                                  * but try to keep going.
10823                                  */
10824                                 if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10825                                         dev_info(&pf->pdev->dev,
10826                                                  "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10827                                                  ret);
10828                                         vsi->uplink_seid = pf->mac_seid;
10829                                         break;
10830                                 } else if (pf->veb[v]->uplink_seid == 0) {
10831                                         dev_info(&pf->pdev->dev,
10832                                                  "rebuild of orphan VEB failed: %d\n",
10833                                                  ret);
10834                                 }
10835                         }
10836                 }
10837         }
10838
10839         if (vsi->uplink_seid == pf->mac_seid) {
10840                 dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
10841                 /* no VEB, so rebuild only the Main VSI */
10842                 ret = i40e_add_vsi(vsi);
10843                 if (ret) {
10844                         dev_info(&pf->pdev->dev,
10845                                  "rebuild of Main VSI failed: %d\n", ret);
10846                         goto end_unlock;
10847                 }
10848         }
10849
10850         if (vsi->mqprio_qopt.max_rate[0]) {
10851                 u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
10852                 u64 credits = 0;
10853
10854                 do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
10855                 ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
10856                 if (ret)
10857                         goto end_unlock;
10858
10859                 credits = max_tx_rate;
10860                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
10861                 dev_dbg(&vsi->back->pdev->dev,
10862                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10863                         max_tx_rate,
10864                         credits,
10865                         vsi->seid);
10866         }
10867
10868         ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
10869         if (ret)
10870                 goto end_unlock;
10871
10872         /* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
10873          * for this main VSI if they exist
10874          */
10875         ret = i40e_rebuild_channels(vsi);
10876         if (ret)
10877                 goto end_unlock;
10878
10879         /* Reconfigure hardware for allowing smaller MSS in the case
10880          * of TSO, so that we avoid the MDD being fired and causing
10881          * a reset in the case of small MSS+TSO.
10882          */
10883 #define I40E_REG_MSS          0x000E64DC
10884 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
10885 #define I40E_64BYTE_MSS       0x400000
10886         val = rd32(hw, I40E_REG_MSS);
10887         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
10888                 val &= ~I40E_REG_MSS_MIN_MASK;
10889                 val |= I40E_64BYTE_MSS;
10890                 wr32(hw, I40E_REG_MSS, val);
10891         }
10892
10893         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
10894                 msleep(75);
10895                 ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
10896                 if (ret)
10897                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
10898                                  i40e_stat_str(&pf->hw, ret),
10899                                  i40e_aq_str(&pf->hw,
10900                                              pf->hw.aq.asq_last_status));
10901         }
10902         /* reinit the misc interrupt */
10903         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
10904                 ret = i40e_setup_misc_vector(pf);
10905
10906         /* Add a filter to drop all Flow control frames from any VSI from being
10907          * transmitted. By doing so we stop a malicious VF from sending out
10908          * PAUSE or PFC frames and potentially controlling traffic for other
10909          * PF/VF VSIs.
10910          * The FW can still send Flow control frames if enabled.
10911          */
10912         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
10913                                                        pf->main_vsi_seid);
10914
10915         /* restart the VSIs that were rebuilt and running before the reset */
10916         i40e_pf_unquiesce_all_vsi(pf);
10917
10918         /* Release the RTNL lock before we start resetting VFs */
10919         if (!lock_acquired)
10920                 rtnl_unlock();
10921
10922         /* Restore promiscuous settings */
10923         ret = i40e_set_promiscuous(pf, pf->cur_promisc);
10924         if (ret)
10925                 dev_warn(&pf->pdev->dev,
10926                          "Failed to restore promiscuous setting: %s, err %s aq_err %s\n",
10927                          pf->cur_promisc ? "on" : "off",
10928                          i40e_stat_str(&pf->hw, ret),
10929                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10930
10931         i40e_reset_all_vfs(pf, true);
10932
10933         /* tell the firmware that we're starting */
10934         i40e_send_version(pf);
10935
10936         /* We've already released the lock, so don't do it again */
10937         goto end_core_reset;
10938
10939 end_unlock:
10940         if (!lock_acquired)
10941                 rtnl_unlock();
10942 end_core_reset:
10943         clear_bit(__I40E_RESET_FAILED, pf->state);
10944 clear_recovery:
10945         clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10946         clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
10947 }
10948
10949 /**
10950  * i40e_reset_and_rebuild - reset and rebuild using a saved config
10951  * @pf: board private structure
10952  * @reinit: if the Main VSI needs to re-initialized.
10953  * @lock_acquired: indicates whether or not the lock has been acquired
10954  * before this function was called.
10955  **/
10956 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
10957                                    bool lock_acquired)
10958 {
10959         int ret;
10960
10961         if (test_bit(__I40E_IN_REMOVE, pf->state))
10962                 return;
10963         /* Now we wait for GRST to settle out.
10964          * We don't have to delete the VEBs or VSIs from the hw switch
10965          * because the reset will make them disappear.
10966          */
10967         ret = i40e_reset(pf);
10968         if (!ret)
10969                 i40e_rebuild(pf, reinit, lock_acquired);
10970 }
10971
10972 /**
10973  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
10974  * @pf: board private structure
10975  *
10976  * Close up the VFs and other things in prep for a Core Reset,
10977  * then get ready to rebuild the world.
10978  * @lock_acquired: indicates whether or not the lock has been acquired
10979  * before this function was called.
10980  **/
10981 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
10982 {
10983         i40e_prep_for_reset(pf);
10984         i40e_reset_and_rebuild(pf, false, lock_acquired);
10985 }
10986
10987 /**
10988  * i40e_handle_mdd_event
10989  * @pf: pointer to the PF structure
10990  *
10991  * Called from the MDD irq handler to identify possibly malicious vfs
10992  **/
10993 static void i40e_handle_mdd_event(struct i40e_pf *pf)
10994 {
10995         struct i40e_hw *hw = &pf->hw;
10996         bool mdd_detected = false;
10997         struct i40e_vf *vf;
10998         u32 reg;
10999         int i;
11000
11001         if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
11002                 return;
11003
11004         /* find what triggered the MDD event */
11005         reg = rd32(hw, I40E_GL_MDET_TX);
11006         if (reg & I40E_GL_MDET_TX_VALID_MASK) {
11007                 u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
11008                                 I40E_GL_MDET_TX_PF_NUM_SHIFT;
11009                 u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
11010                                 I40E_GL_MDET_TX_VF_NUM_SHIFT;
11011                 u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
11012                                 I40E_GL_MDET_TX_EVENT_SHIFT;
11013                 u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
11014                                 I40E_GL_MDET_TX_QUEUE_SHIFT) -
11015                                 pf->hw.func_caps.base_queue;
11016                 if (netif_msg_tx_err(pf))
11017                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
11018                                  event, queue, pf_num, vf_num);
11019                 wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
11020                 mdd_detected = true;
11021         }
11022         reg = rd32(hw, I40E_GL_MDET_RX);
11023         if (reg & I40E_GL_MDET_RX_VALID_MASK) {
11024                 u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
11025                                 I40E_GL_MDET_RX_FUNCTION_SHIFT;
11026                 u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
11027                                 I40E_GL_MDET_RX_EVENT_SHIFT;
11028                 u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
11029                                 I40E_GL_MDET_RX_QUEUE_SHIFT) -
11030                                 pf->hw.func_caps.base_queue;
11031                 if (netif_msg_rx_err(pf))
11032                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
11033                                  event, queue, func);
11034                 wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
11035                 mdd_detected = true;
11036         }
11037
11038         if (mdd_detected) {
11039                 reg = rd32(hw, I40E_PF_MDET_TX);
11040                 if (reg & I40E_PF_MDET_TX_VALID_MASK) {
11041                         wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
11042                         dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
11043                 }
11044                 reg = rd32(hw, I40E_PF_MDET_RX);
11045                 if (reg & I40E_PF_MDET_RX_VALID_MASK) {
11046                         wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
11047                         dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
11048                 }
11049         }
11050
11051         /* see if one of the VFs needs its hand slapped */
11052         for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
11053                 vf = &(pf->vf[i]);
11054                 reg = rd32(hw, I40E_VP_MDET_TX(i));
11055                 if (reg & I40E_VP_MDET_TX_VALID_MASK) {
11056                         wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
11057                         vf->num_mdd_events++;
11058                         dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
11059                                  i);
11060                         dev_info(&pf->pdev->dev,
11061                                  "Use PF Control I/F to re-enable the VF\n");
11062                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11063                 }
11064
11065                 reg = rd32(hw, I40E_VP_MDET_RX(i));
11066                 if (reg & I40E_VP_MDET_RX_VALID_MASK) {
11067                         wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
11068                         vf->num_mdd_events++;
11069                         dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
11070                                  i);
11071                         dev_info(&pf->pdev->dev,
11072                                  "Use PF Control I/F to re-enable the VF\n");
11073                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
11074                 }
11075         }
11076
11077         /* re-enable mdd interrupt cause */
11078         clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
11079         reg = rd32(hw, I40E_PFINT_ICR0_ENA);
11080         reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
11081         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
11082         i40e_flush(hw);
11083 }
11084
11085 /**
11086  * i40e_service_task - Run the driver's async subtasks
11087  * @work: pointer to work_struct containing our data
11088  **/
11089 static void i40e_service_task(struct work_struct *work)
11090 {
11091         struct i40e_pf *pf = container_of(work,
11092                                           struct i40e_pf,
11093                                           service_task);
11094         unsigned long start_time = jiffies;
11095
11096         /* don't bother with service tasks if a reset is in progress */
11097         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
11098             test_bit(__I40E_SUSPENDED, pf->state))
11099                 return;
11100
11101         if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
11102                 return;
11103
11104         if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
11105                 i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
11106                 i40e_sync_filters_subtask(pf);
11107                 i40e_reset_subtask(pf);
11108                 i40e_handle_mdd_event(pf);
11109                 i40e_vc_process_vflr_event(pf);
11110                 i40e_watchdog_subtask(pf);
11111                 i40e_fdir_reinit_subtask(pf);
11112                 if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
11113                         /* Client subtask will reopen next time through. */
11114                         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
11115                                                            true);
11116                 } else {
11117                         i40e_client_subtask(pf);
11118                         if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
11119                                                pf->state))
11120                                 i40e_notify_client_of_l2_param_changes(
11121                                                                 pf->vsi[pf->lan_vsi]);
11122                 }
11123                 i40e_sync_filters_subtask(pf);
11124         } else {
11125                 i40e_reset_subtask(pf);
11126         }
11127
11128         i40e_clean_adminq_subtask(pf);
11129
11130         /* flush memory to make sure state is correct before next watchdog */
11131         smp_mb__before_atomic();
11132         clear_bit(__I40E_SERVICE_SCHED, pf->state);
11133
11134         /* If the tasks have taken longer than one timer cycle or there
11135          * is more work to be done, reschedule the service task now
11136          * rather than wait for the timer to tick again.
11137          */
11138         if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
11139             test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)             ||
11140             test_bit(__I40E_MDD_EVENT_PENDING, pf->state)                ||
11141             test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
11142                 i40e_service_event_schedule(pf);
11143 }
11144
11145 /**
11146  * i40e_service_timer - timer callback
11147  * @t: timer list pointer
11148  **/
11149 static void i40e_service_timer(struct timer_list *t)
11150 {
11151         struct i40e_pf *pf = from_timer(pf, t, service_timer);
11152
11153         mod_timer(&pf->service_timer,
11154                   round_jiffies(jiffies + pf->service_timer_period));
11155         i40e_service_event_schedule(pf);
11156 }
11157
11158 /**
11159  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
11160  * @vsi: the VSI being configured
11161  **/
11162 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
11163 {
11164         struct i40e_pf *pf = vsi->back;
11165
11166         switch (vsi->type) {
11167         case I40E_VSI_MAIN:
11168                 vsi->alloc_queue_pairs = pf->num_lan_qps;
11169                 if (!vsi->num_tx_desc)
11170                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11171                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11172                 if (!vsi->num_rx_desc)
11173                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11174                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11175                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11176                         vsi->num_q_vectors = pf->num_lan_msix;
11177                 else
11178                         vsi->num_q_vectors = 1;
11179
11180                 break;
11181
11182         case I40E_VSI_FDIR:
11183                 vsi->alloc_queue_pairs = 1;
11184                 vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11185                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
11186                 vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
11187                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
11188                 vsi->num_q_vectors = pf->num_fdsb_msix;
11189                 break;
11190
11191         case I40E_VSI_VMDQ2:
11192                 vsi->alloc_queue_pairs = pf->num_vmdq_qps;
11193                 if (!vsi->num_tx_desc)
11194                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11195                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11196                 if (!vsi->num_rx_desc)
11197                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11198                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11199                 vsi->num_q_vectors = pf->num_vmdq_msix;
11200                 break;
11201
11202         case I40E_VSI_SRIOV:
11203                 vsi->alloc_queue_pairs = pf->num_vf_qps;
11204                 if (!vsi->num_tx_desc)
11205                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11206                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11207                 if (!vsi->num_rx_desc)
11208                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11209                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11210                 break;
11211
11212         default:
11213                 WARN_ON(1);
11214                 return -ENODATA;
11215         }
11216
11217         if (is_kdump_kernel()) {
11218                 vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11219                 vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11220         }
11221
11222         return 0;
11223 }
11224
11225 /**
11226  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11227  * @vsi: VSI pointer
11228  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11229  *
11230  * On error: returns error code (negative)
11231  * On success: returns 0
11232  **/
11233 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11234 {
11235         struct i40e_ring **next_rings;
11236         int size;
11237         int ret = 0;
11238
11239         /* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11240         size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11241                (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11242         vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11243         if (!vsi->tx_rings)
11244                 return -ENOMEM;
11245         next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11246         if (i40e_enabled_xdp_vsi(vsi)) {
11247                 vsi->xdp_rings = next_rings;
11248                 next_rings += vsi->alloc_queue_pairs;
11249         }
11250         vsi->rx_rings = next_rings;
11251
11252         if (alloc_qvectors) {
11253                 /* allocate memory for q_vector pointers */
11254                 size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11255                 vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11256                 if (!vsi->q_vectors) {
11257                         ret = -ENOMEM;
11258                         goto err_vectors;
11259                 }
11260         }
11261         return ret;
11262
11263 err_vectors:
11264         kfree(vsi->tx_rings);
11265         return ret;
11266 }
11267
11268 /**
11269  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11270  * @pf: board private structure
11271  * @type: type of VSI
11272  *
11273  * On error: returns error code (negative)
11274  * On success: returns vsi index in PF (positive)
11275  **/
11276 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11277 {
11278         int ret = -ENODEV;
11279         struct i40e_vsi *vsi;
11280         int vsi_idx;
11281         int i;
11282
11283         /* Need to protect the allocation of the VSIs at the PF level */
11284         mutex_lock(&pf->switch_mutex);
11285
11286         /* VSI list may be fragmented if VSI creation/destruction has
11287          * been happening.  We can afford to do a quick scan to look
11288          * for any free VSIs in the list.
11289          *
11290          * find next empty vsi slot, looping back around if necessary
11291          */
11292         i = pf->next_vsi;
11293         while (i < pf->num_alloc_vsi && pf->vsi[i])
11294                 i++;
11295         if (i >= pf->num_alloc_vsi) {
11296                 i = 0;
11297                 while (i < pf->next_vsi && pf->vsi[i])
11298                         i++;
11299         }
11300
11301         if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11302                 vsi_idx = i;             /* Found one! */
11303         } else {
11304                 ret = -ENODEV;
11305                 goto unlock_pf;  /* out of VSI slots! */
11306         }
11307         pf->next_vsi = ++i;
11308
11309         vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11310         if (!vsi) {
11311                 ret = -ENOMEM;
11312                 goto unlock_pf;
11313         }
11314         vsi->type = type;
11315         vsi->back = pf;
11316         set_bit(__I40E_VSI_DOWN, vsi->state);
11317         vsi->flags = 0;
11318         vsi->idx = vsi_idx;
11319         vsi->int_rate_limit = 0;
11320         vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11321                                 pf->rss_table_size : 64;
11322         vsi->netdev_registered = false;
11323         vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11324         hash_init(vsi->mac_filter_hash);
11325         vsi->irqs_ready = false;
11326
11327         if (type == I40E_VSI_MAIN) {
11328                 vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11329                 if (!vsi->af_xdp_zc_qps)
11330                         goto err_rings;
11331         }
11332
11333         ret = i40e_set_num_rings_in_vsi(vsi);
11334         if (ret)
11335                 goto err_rings;
11336
11337         ret = i40e_vsi_alloc_arrays(vsi, true);
11338         if (ret)
11339                 goto err_rings;
11340
11341         /* Setup default MSIX irq handler for VSI */
11342         i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11343
11344         /* Initialize VSI lock */
11345         spin_lock_init(&vsi->mac_filter_hash_lock);
11346         pf->vsi[vsi_idx] = vsi;
11347         ret = vsi_idx;
11348         goto unlock_pf;
11349
11350 err_rings:
11351         bitmap_free(vsi->af_xdp_zc_qps);
11352         pf->next_vsi = i - 1;
11353         kfree(vsi);
11354 unlock_pf:
11355         mutex_unlock(&pf->switch_mutex);
11356         return ret;
11357 }
11358
11359 /**
11360  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11361  * @vsi: VSI pointer
11362  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11363  *
11364  * On error: returns error code (negative)
11365  * On success: returns 0
11366  **/
11367 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11368 {
11369         /* free the ring and vector containers */
11370         if (free_qvectors) {
11371                 kfree(vsi->q_vectors);
11372                 vsi->q_vectors = NULL;
11373         }
11374         kfree(vsi->tx_rings);
11375         vsi->tx_rings = NULL;
11376         vsi->rx_rings = NULL;
11377         vsi->xdp_rings = NULL;
11378 }
11379
11380 /**
11381  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11382  * and lookup table
11383  * @vsi: Pointer to VSI structure
11384  */
11385 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11386 {
11387         if (!vsi)
11388                 return;
11389
11390         kfree(vsi->rss_hkey_user);
11391         vsi->rss_hkey_user = NULL;
11392
11393         kfree(vsi->rss_lut_user);
11394         vsi->rss_lut_user = NULL;
11395 }
11396
11397 /**
11398  * i40e_vsi_clear - Deallocate the VSI provided
11399  * @vsi: the VSI being un-configured
11400  **/
11401 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11402 {
11403         struct i40e_pf *pf;
11404
11405         if (!vsi)
11406                 return 0;
11407
11408         if (!vsi->back)
11409                 goto free_vsi;
11410         pf = vsi->back;
11411
11412         mutex_lock(&pf->switch_mutex);
11413         if (!pf->vsi[vsi->idx]) {
11414                 dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11415                         vsi->idx, vsi->idx, vsi->type);
11416                 goto unlock_vsi;
11417         }
11418
11419         if (pf->vsi[vsi->idx] != vsi) {
11420                 dev_err(&pf->pdev->dev,
11421                         "pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11422                         pf->vsi[vsi->idx]->idx,
11423                         pf->vsi[vsi->idx]->type,
11424                         vsi->idx, vsi->type);
11425                 goto unlock_vsi;
11426         }
11427
11428         /* updates the PF for this cleared vsi */
11429         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11430         i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11431
11432         bitmap_free(vsi->af_xdp_zc_qps);
11433         i40e_vsi_free_arrays(vsi, true);
11434         i40e_clear_rss_config_user(vsi);
11435
11436         pf->vsi[vsi->idx] = NULL;
11437         if (vsi->idx < pf->next_vsi)
11438                 pf->next_vsi = vsi->idx;
11439
11440 unlock_vsi:
11441         mutex_unlock(&pf->switch_mutex);
11442 free_vsi:
11443         kfree(vsi);
11444
11445         return 0;
11446 }
11447
11448 /**
11449  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11450  * @vsi: the VSI being cleaned
11451  **/
11452 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11453 {
11454         int i;
11455
11456         if (vsi->tx_rings && vsi->tx_rings[0]) {
11457                 for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11458                         kfree_rcu(vsi->tx_rings[i], rcu);
11459                         WRITE_ONCE(vsi->tx_rings[i], NULL);
11460                         WRITE_ONCE(vsi->rx_rings[i], NULL);
11461                         if (vsi->xdp_rings)
11462                                 WRITE_ONCE(vsi->xdp_rings[i], NULL);
11463                 }
11464         }
11465 }
11466
11467 /**
11468  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11469  * @vsi: the VSI being configured
11470  **/
11471 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11472 {
11473         int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11474         struct i40e_pf *pf = vsi->back;
11475         struct i40e_ring *ring;
11476
11477         /* Set basic values in the rings to be used later during open() */
11478         for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11479                 /* allocate space for both Tx and Rx in one shot */
11480                 ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11481                 if (!ring)
11482                         goto err_out;
11483
11484                 ring->queue_index = i;
11485                 ring->reg_idx = vsi->base_queue + i;
11486                 ring->ring_active = false;
11487                 ring->vsi = vsi;
11488                 ring->netdev = vsi->netdev;
11489                 ring->dev = &pf->pdev->dev;
11490                 ring->count = vsi->num_tx_desc;
11491                 ring->size = 0;
11492                 ring->dcb_tc = 0;
11493                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11494                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11495                 ring->itr_setting = pf->tx_itr_default;
11496                 WRITE_ONCE(vsi->tx_rings[i], ring++);
11497
11498                 if (!i40e_enabled_xdp_vsi(vsi))
11499                         goto setup_rx;
11500
11501                 ring->queue_index = vsi->alloc_queue_pairs + i;
11502                 ring->reg_idx = vsi->base_queue + ring->queue_index;
11503                 ring->ring_active = false;
11504                 ring->vsi = vsi;
11505                 ring->netdev = NULL;
11506                 ring->dev = &pf->pdev->dev;
11507                 ring->count = vsi->num_tx_desc;
11508                 ring->size = 0;
11509                 ring->dcb_tc = 0;
11510                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11511                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11512                 set_ring_xdp(ring);
11513                 ring->itr_setting = pf->tx_itr_default;
11514                 WRITE_ONCE(vsi->xdp_rings[i], ring++);
11515
11516 setup_rx:
11517                 ring->queue_index = i;
11518                 ring->reg_idx = vsi->base_queue + i;
11519                 ring->ring_active = false;
11520                 ring->vsi = vsi;
11521                 ring->netdev = vsi->netdev;
11522                 ring->dev = &pf->pdev->dev;
11523                 ring->count = vsi->num_rx_desc;
11524                 ring->size = 0;
11525                 ring->dcb_tc = 0;
11526                 ring->itr_setting = pf->rx_itr_default;
11527                 WRITE_ONCE(vsi->rx_rings[i], ring);
11528         }
11529
11530         return 0;
11531
11532 err_out:
11533         i40e_vsi_clear_rings(vsi);
11534         return -ENOMEM;
11535 }
11536
11537 /**
11538  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11539  * @pf: board private structure
11540  * @vectors: the number of MSI-X vectors to request
11541  *
11542  * Returns the number of vectors reserved, or error
11543  **/
11544 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11545 {
11546         vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11547                                         I40E_MIN_MSIX, vectors);
11548         if (vectors < 0) {
11549                 dev_info(&pf->pdev->dev,
11550                          "MSI-X vector reservation failed: %d\n", vectors);
11551                 vectors = 0;
11552         }
11553
11554         return vectors;
11555 }
11556
11557 /**
11558  * i40e_init_msix - Setup the MSIX capability
11559  * @pf: board private structure
11560  *
11561  * Work with the OS to set up the MSIX vectors needed.
11562  *
11563  * Returns the number of vectors reserved or negative on failure
11564  **/
11565 static int i40e_init_msix(struct i40e_pf *pf)
11566 {
11567         struct i40e_hw *hw = &pf->hw;
11568         int cpus, extra_vectors;
11569         int vectors_left;
11570         int v_budget, i;
11571         int v_actual;
11572         int iwarp_requested = 0;
11573
11574         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11575                 return -ENODEV;
11576
11577         /* The number of vectors we'll request will be comprised of:
11578          *   - Add 1 for "other" cause for Admin Queue events, etc.
11579          *   - The number of LAN queue pairs
11580          *      - Queues being used for RSS.
11581          *              We don't need as many as max_rss_size vectors.
11582          *              use rss_size instead in the calculation since that
11583          *              is governed by number of cpus in the system.
11584          *      - assumes symmetric Tx/Rx pairing
11585          *   - The number of VMDq pairs
11586          *   - The CPU count within the NUMA node if iWARP is enabled
11587          * Once we count this up, try the request.
11588          *
11589          * If we can't get what we want, we'll simplify to nearly nothing
11590          * and try again.  If that still fails, we punt.
11591          */
11592         vectors_left = hw->func_caps.num_msix_vectors;
11593         v_budget = 0;
11594
11595         /* reserve one vector for miscellaneous handler */
11596         if (vectors_left) {
11597                 v_budget++;
11598                 vectors_left--;
11599         }
11600
11601         /* reserve some vectors for the main PF traffic queues. Initially we
11602          * only reserve at most 50% of the available vectors, in the case that
11603          * the number of online CPUs is large. This ensures that we can enable
11604          * extra features as well. Once we've enabled the other features, we
11605          * will use any remaining vectors to reach as close as we can to the
11606          * number of online CPUs.
11607          */
11608         cpus = num_online_cpus();
11609         pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11610         vectors_left -= pf->num_lan_msix;
11611
11612         /* reserve one vector for sideband flow director */
11613         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11614                 if (vectors_left) {
11615                         pf->num_fdsb_msix = 1;
11616                         v_budget++;
11617                         vectors_left--;
11618                 } else {
11619                         pf->num_fdsb_msix = 0;
11620                 }
11621         }
11622
11623         /* can we reserve enough for iWARP? */
11624         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11625                 iwarp_requested = pf->num_iwarp_msix;
11626
11627                 if (!vectors_left)
11628                         pf->num_iwarp_msix = 0;
11629                 else if (vectors_left < pf->num_iwarp_msix)
11630                         pf->num_iwarp_msix = 1;
11631                 v_budget += pf->num_iwarp_msix;
11632                 vectors_left -= pf->num_iwarp_msix;
11633         }
11634
11635         /* any vectors left over go for VMDq support */
11636         if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11637                 if (!vectors_left) {
11638                         pf->num_vmdq_msix = 0;
11639                         pf->num_vmdq_qps = 0;
11640                 } else {
11641                         int vmdq_vecs_wanted =
11642                                 pf->num_vmdq_vsis * pf->num_vmdq_qps;
11643                         int vmdq_vecs =
11644                                 min_t(int, vectors_left, vmdq_vecs_wanted);
11645
11646                         /* if we're short on vectors for what's desired, we limit
11647                          * the queues per vmdq.  If this is still more than are
11648                          * available, the user will need to change the number of
11649                          * queues/vectors used by the PF later with the ethtool
11650                          * channels command
11651                          */
11652                         if (vectors_left < vmdq_vecs_wanted) {
11653                                 pf->num_vmdq_qps = 1;
11654                                 vmdq_vecs_wanted = pf->num_vmdq_vsis;
11655                                 vmdq_vecs = min_t(int,
11656                                                   vectors_left,
11657                                                   vmdq_vecs_wanted);
11658                         }
11659                         pf->num_vmdq_msix = pf->num_vmdq_qps;
11660
11661                         v_budget += vmdq_vecs;
11662                         vectors_left -= vmdq_vecs;
11663                 }
11664         }
11665
11666         /* On systems with a large number of SMP cores, we previously limited
11667          * the number of vectors for num_lan_msix to be at most 50% of the
11668          * available vectors, to allow for other features. Now, we add back
11669          * the remaining vectors. However, we ensure that the total
11670          * num_lan_msix will not exceed num_online_cpus(). To do this, we
11671          * calculate the number of vectors we can add without going over the
11672          * cap of CPUs. For systems with a small number of CPUs this will be
11673          * zero.
11674          */
11675         extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11676         pf->num_lan_msix += extra_vectors;
11677         vectors_left -= extra_vectors;
11678
11679         WARN(vectors_left < 0,
11680              "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11681
11682         v_budget += pf->num_lan_msix;
11683         pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11684                                    GFP_KERNEL);
11685         if (!pf->msix_entries)
11686                 return -ENOMEM;
11687
11688         for (i = 0; i < v_budget; i++)
11689                 pf->msix_entries[i].entry = i;
11690         v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11691
11692         if (v_actual < I40E_MIN_MSIX) {
11693                 pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11694                 kfree(pf->msix_entries);
11695                 pf->msix_entries = NULL;
11696                 pci_disable_msix(pf->pdev);
11697                 return -ENODEV;
11698
11699         } else if (v_actual == I40E_MIN_MSIX) {
11700                 /* Adjust for minimal MSIX use */
11701                 pf->num_vmdq_vsis = 0;
11702                 pf->num_vmdq_qps = 0;
11703                 pf->num_lan_qps = 1;
11704                 pf->num_lan_msix = 1;
11705
11706         } else if (v_actual != v_budget) {
11707                 /* If we have limited resources, we will start with no vectors
11708                  * for the special features and then allocate vectors to some
11709                  * of these features based on the policy and at the end disable
11710                  * the features that did not get any vectors.
11711                  */
11712                 int vec;
11713
11714                 dev_info(&pf->pdev->dev,
11715                          "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11716                          v_actual, v_budget);
11717                 /* reserve the misc vector */
11718                 vec = v_actual - 1;
11719
11720                 /* Scale vector usage down */
11721                 pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11722                 pf->num_vmdq_vsis = 1;
11723                 pf->num_vmdq_qps = 1;
11724
11725                 /* partition out the remaining vectors */
11726                 switch (vec) {
11727                 case 2:
11728                         pf->num_lan_msix = 1;
11729                         break;
11730                 case 3:
11731                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11732                                 pf->num_lan_msix = 1;
11733                                 pf->num_iwarp_msix = 1;
11734                         } else {
11735                                 pf->num_lan_msix = 2;
11736                         }
11737                         break;
11738                 default:
11739                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11740                                 pf->num_iwarp_msix = min_t(int, (vec / 3),
11741                                                  iwarp_requested);
11742                                 pf->num_vmdq_vsis = min_t(int, (vec / 3),
11743                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11744                         } else {
11745                                 pf->num_vmdq_vsis = min_t(int, (vec / 2),
11746                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11747                         }
11748                         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11749                                 pf->num_fdsb_msix = 1;
11750                                 vec--;
11751                         }
11752                         pf->num_lan_msix = min_t(int,
11753                                (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11754                                                               pf->num_lan_msix);
11755                         pf->num_lan_qps = pf->num_lan_msix;
11756                         break;
11757                 }
11758         }
11759
11760         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11761             (pf->num_fdsb_msix == 0)) {
11762                 dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11763                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11764                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11765         }
11766         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11767             (pf->num_vmdq_msix == 0)) {
11768                 dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11769                 pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11770         }
11771
11772         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11773             (pf->num_iwarp_msix == 0)) {
11774                 dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11775                 pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11776         }
11777         i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11778                    "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11779                    pf->num_lan_msix,
11780                    pf->num_vmdq_msix * pf->num_vmdq_vsis,
11781                    pf->num_fdsb_msix,
11782                    pf->num_iwarp_msix);
11783
11784         return v_actual;
11785 }
11786
11787 /**
11788  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11789  * @vsi: the VSI being configured
11790  * @v_idx: index of the vector in the vsi struct
11791  *
11792  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11793  **/
11794 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11795 {
11796         struct i40e_q_vector *q_vector;
11797
11798         /* allocate q_vector */
11799         q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11800         if (!q_vector)
11801                 return -ENOMEM;
11802
11803         q_vector->vsi = vsi;
11804         q_vector->v_idx = v_idx;
11805         cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11806
11807         if (vsi->netdev)
11808                 netif_napi_add(vsi->netdev, &q_vector->napi,
11809                                i40e_napi_poll, NAPI_POLL_WEIGHT);
11810
11811         /* tie q_vector and vsi together */
11812         vsi->q_vectors[v_idx] = q_vector;
11813
11814         return 0;
11815 }
11816
11817 /**
11818  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11819  * @vsi: the VSI being configured
11820  *
11821  * We allocate one q_vector per queue interrupt.  If allocation fails we
11822  * return -ENOMEM.
11823  **/
11824 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11825 {
11826         struct i40e_pf *pf = vsi->back;
11827         int err, v_idx, num_q_vectors;
11828
11829         /* if not MSIX, give the one vector only to the LAN VSI */
11830         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11831                 num_q_vectors = vsi->num_q_vectors;
11832         else if (vsi == pf->vsi[pf->lan_vsi])
11833                 num_q_vectors = 1;
11834         else
11835                 return -EINVAL;
11836
11837         for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
11838                 err = i40e_vsi_alloc_q_vector(vsi, v_idx);
11839                 if (err)
11840                         goto err_out;
11841         }
11842
11843         return 0;
11844
11845 err_out:
11846         while (v_idx--)
11847                 i40e_free_q_vector(vsi, v_idx);
11848
11849         return err;
11850 }
11851
11852 /**
11853  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
11854  * @pf: board private structure to initialize
11855  **/
11856 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
11857 {
11858         int vectors = 0;
11859         ssize_t size;
11860
11861         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11862                 vectors = i40e_init_msix(pf);
11863                 if (vectors < 0) {
11864                         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED   |
11865                                        I40E_FLAG_IWARP_ENABLED  |
11866                                        I40E_FLAG_RSS_ENABLED    |
11867                                        I40E_FLAG_DCB_CAPABLE    |
11868                                        I40E_FLAG_DCB_ENABLED    |
11869                                        I40E_FLAG_SRIOV_ENABLED  |
11870                                        I40E_FLAG_FD_SB_ENABLED  |
11871                                        I40E_FLAG_FD_ATR_ENABLED |
11872                                        I40E_FLAG_VMDQ_ENABLED);
11873                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11874
11875                         /* rework the queue expectations without MSIX */
11876                         i40e_determine_queue_usage(pf);
11877                 }
11878         }
11879
11880         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11881             (pf->flags & I40E_FLAG_MSI_ENABLED)) {
11882                 dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
11883                 vectors = pci_enable_msi(pf->pdev);
11884                 if (vectors < 0) {
11885                         dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
11886                                  vectors);
11887                         pf->flags &= ~I40E_FLAG_MSI_ENABLED;
11888                 }
11889                 vectors = 1;  /* one MSI or Legacy vector */
11890         }
11891
11892         if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
11893                 dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
11894
11895         /* set up vector assignment tracking */
11896         size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
11897         pf->irq_pile = kzalloc(size, GFP_KERNEL);
11898         if (!pf->irq_pile)
11899                 return -ENOMEM;
11900
11901         pf->irq_pile->num_entries = vectors;
11902
11903         /* track first vector for misc interrupts, ignore return */
11904         (void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
11905
11906         return 0;
11907 }
11908
11909 /**
11910  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
11911  * @pf: private board data structure
11912  *
11913  * Restore the interrupt scheme that was cleared when we suspended the
11914  * device. This should be called during resume to re-allocate the q_vectors
11915  * and reacquire IRQs.
11916  */
11917 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
11918 {
11919         int err, i;
11920
11921         /* We cleared the MSI and MSI-X flags when disabling the old interrupt
11922          * scheme. We need to re-enabled them here in order to attempt to
11923          * re-acquire the MSI or MSI-X vectors
11924          */
11925         pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
11926
11927         err = i40e_init_interrupt_scheme(pf);
11928         if (err)
11929                 return err;
11930
11931         /* Now that we've re-acquired IRQs, we need to remap the vectors and
11932          * rings together again.
11933          */
11934         for (i = 0; i < pf->num_alloc_vsi; i++) {
11935                 if (pf->vsi[i]) {
11936                         err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
11937                         if (err)
11938                                 goto err_unwind;
11939                         i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
11940                 }
11941         }
11942
11943         err = i40e_setup_misc_vector(pf);
11944         if (err)
11945                 goto err_unwind;
11946
11947         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
11948                 i40e_client_update_msix_info(pf);
11949
11950         return 0;
11951
11952 err_unwind:
11953         while (i--) {
11954                 if (pf->vsi[i])
11955                         i40e_vsi_free_q_vectors(pf->vsi[i]);
11956         }
11957
11958         return err;
11959 }
11960
11961 /**
11962  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
11963  * non queue events in recovery mode
11964  * @pf: board private structure
11965  *
11966  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
11967  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
11968  * This is handled differently than in recovery mode since no Tx/Rx resources
11969  * are being allocated.
11970  **/
11971 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
11972 {
11973         int err;
11974
11975         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11976                 err = i40e_setup_misc_vector(pf);
11977
11978                 if (err) {
11979                         dev_info(&pf->pdev->dev,
11980                                  "MSI-X misc vector request failed, error %d\n",
11981                                  err);
11982                         return err;
11983                 }
11984         } else {
11985                 u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
11986
11987                 err = request_irq(pf->pdev->irq, i40e_intr, flags,
11988                                   pf->int_name, pf);
11989
11990                 if (err) {
11991                         dev_info(&pf->pdev->dev,
11992                                  "MSI/legacy misc vector request failed, error %d\n",
11993                                  err);
11994                         return err;
11995                 }
11996                 i40e_enable_misc_int_causes(pf);
11997                 i40e_irq_dynamic_enable_icr0(pf);
11998         }
11999
12000         return 0;
12001 }
12002
12003 /**
12004  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
12005  * @pf: board private structure
12006  *
12007  * This sets up the handler for MSIX 0, which is used to manage the
12008  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
12009  * when in MSI or Legacy interrupt mode.
12010  **/
12011 static int i40e_setup_misc_vector(struct i40e_pf *pf)
12012 {
12013         struct i40e_hw *hw = &pf->hw;
12014         int err = 0;
12015
12016         /* Only request the IRQ once, the first time through. */
12017         if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
12018                 err = request_irq(pf->msix_entries[0].vector,
12019                                   i40e_intr, 0, pf->int_name, pf);
12020                 if (err) {
12021                         clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
12022                         dev_info(&pf->pdev->dev,
12023                                  "request_irq for %s failed: %d\n",
12024                                  pf->int_name, err);
12025                         return -EFAULT;
12026                 }
12027         }
12028
12029         i40e_enable_misc_int_causes(pf);
12030
12031         /* associate no queues to the misc vector */
12032         wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
12033         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
12034
12035         i40e_flush(hw);
12036
12037         i40e_irq_dynamic_enable_icr0(pf);
12038
12039         return err;
12040 }
12041
12042 /**
12043  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
12044  * @vsi: Pointer to vsi structure
12045  * @seed: Buffter to store the hash keys
12046  * @lut: Buffer to store the lookup table entries
12047  * @lut_size: Size of buffer to store the lookup table entries
12048  *
12049  * Return 0 on success, negative on failure
12050  */
12051 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
12052                            u8 *lut, u16 lut_size)
12053 {
12054         struct i40e_pf *pf = vsi->back;
12055         struct i40e_hw *hw = &pf->hw;
12056         int ret = 0;
12057
12058         if (seed) {
12059                 ret = i40e_aq_get_rss_key(hw, vsi->id,
12060                         (struct i40e_aqc_get_set_rss_key_data *)seed);
12061                 if (ret) {
12062                         dev_info(&pf->pdev->dev,
12063                                  "Cannot get RSS key, err %s aq_err %s\n",
12064                                  i40e_stat_str(&pf->hw, ret),
12065                                  i40e_aq_str(&pf->hw,
12066                                              pf->hw.aq.asq_last_status));
12067                         return ret;
12068                 }
12069         }
12070
12071         if (lut) {
12072                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
12073
12074                 ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
12075                 if (ret) {
12076                         dev_info(&pf->pdev->dev,
12077                                  "Cannot get RSS lut, err %s aq_err %s\n",
12078                                  i40e_stat_str(&pf->hw, ret),
12079                                  i40e_aq_str(&pf->hw,
12080                                              pf->hw.aq.asq_last_status));
12081                         return ret;
12082                 }
12083         }
12084
12085         return ret;
12086 }
12087
12088 /**
12089  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
12090  * @vsi: Pointer to vsi structure
12091  * @seed: RSS hash seed
12092  * @lut: Lookup table
12093  * @lut_size: Lookup table size
12094  *
12095  * Returns 0 on success, negative on failure
12096  **/
12097 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
12098                                const u8 *lut, u16 lut_size)
12099 {
12100         struct i40e_pf *pf = vsi->back;
12101         struct i40e_hw *hw = &pf->hw;
12102         u16 vf_id = vsi->vf_id;
12103         u8 i;
12104
12105         /* Fill out hash function seed */
12106         if (seed) {
12107                 u32 *seed_dw = (u32 *)seed;
12108
12109                 if (vsi->type == I40E_VSI_MAIN) {
12110                         for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12111                                 wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
12112                 } else if (vsi->type == I40E_VSI_SRIOV) {
12113                         for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
12114                                 wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
12115                 } else {
12116                         dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
12117                 }
12118         }
12119
12120         if (lut) {
12121                 u32 *lut_dw = (u32 *)lut;
12122
12123                 if (vsi->type == I40E_VSI_MAIN) {
12124                         if (lut_size != I40E_HLUT_ARRAY_SIZE)
12125                                 return -EINVAL;
12126                         for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12127                                 wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
12128                 } else if (vsi->type == I40E_VSI_SRIOV) {
12129                         if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
12130                                 return -EINVAL;
12131                         for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12132                                 wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
12133                 } else {
12134                         dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12135                 }
12136         }
12137         i40e_flush(hw);
12138
12139         return 0;
12140 }
12141
12142 /**
12143  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
12144  * @vsi: Pointer to VSI structure
12145  * @seed: Buffer to store the keys
12146  * @lut: Buffer to store the lookup table entries
12147  * @lut_size: Size of buffer to store the lookup table entries
12148  *
12149  * Returns 0 on success, negative on failure
12150  */
12151 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
12152                             u8 *lut, u16 lut_size)
12153 {
12154         struct i40e_pf *pf = vsi->back;
12155         struct i40e_hw *hw = &pf->hw;
12156         u16 i;
12157
12158         if (seed) {
12159                 u32 *seed_dw = (u32 *)seed;
12160
12161                 for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
12162                         seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
12163         }
12164         if (lut) {
12165                 u32 *lut_dw = (u32 *)lut;
12166
12167                 if (lut_size != I40E_HLUT_ARRAY_SIZE)
12168                         return -EINVAL;
12169                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12170                         lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
12171         }
12172
12173         return 0;
12174 }
12175
12176 /**
12177  * i40e_config_rss - Configure RSS keys and lut
12178  * @vsi: Pointer to VSI structure
12179  * @seed: RSS hash seed
12180  * @lut: Lookup table
12181  * @lut_size: Lookup table size
12182  *
12183  * Returns 0 on success, negative on failure
12184  */
12185 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12186 {
12187         struct i40e_pf *pf = vsi->back;
12188
12189         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12190                 return i40e_config_rss_aq(vsi, seed, lut, lut_size);
12191         else
12192                 return i40e_config_rss_reg(vsi, seed, lut, lut_size);
12193 }
12194
12195 /**
12196  * i40e_get_rss - Get RSS keys and lut
12197  * @vsi: Pointer to VSI structure
12198  * @seed: Buffer to store the keys
12199  * @lut: Buffer to store the lookup table entries
12200  * @lut_size: Size of buffer to store the lookup table entries
12201  *
12202  * Returns 0 on success, negative on failure
12203  */
12204 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12205 {
12206         struct i40e_pf *pf = vsi->back;
12207
12208         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12209                 return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12210         else
12211                 return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12212 }
12213
12214 /**
12215  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12216  * @pf: Pointer to board private structure
12217  * @lut: Lookup table
12218  * @rss_table_size: Lookup table size
12219  * @rss_size: Range of queue number for hashing
12220  */
12221 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12222                        u16 rss_table_size, u16 rss_size)
12223 {
12224         u16 i;
12225
12226         for (i = 0; i < rss_table_size; i++)
12227                 lut[i] = i % rss_size;
12228 }
12229
12230 /**
12231  * i40e_pf_config_rss - Prepare for RSS if used
12232  * @pf: board private structure
12233  **/
12234 static int i40e_pf_config_rss(struct i40e_pf *pf)
12235 {
12236         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12237         u8 seed[I40E_HKEY_ARRAY_SIZE];
12238         u8 *lut;
12239         struct i40e_hw *hw = &pf->hw;
12240         u32 reg_val;
12241         u64 hena;
12242         int ret;
12243
12244         /* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12245         hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12246                 ((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12247         hena |= i40e_pf_get_default_rss_hena(pf);
12248
12249         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12250         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12251
12252         /* Determine the RSS table size based on the hardware capabilities */
12253         reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12254         reg_val = (pf->rss_table_size == 512) ?
12255                         (reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12256                         (reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12257         i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12258
12259         /* Determine the RSS size of the VSI */
12260         if (!vsi->rss_size) {
12261                 u16 qcount;
12262                 /* If the firmware does something weird during VSI init, we
12263                  * could end up with zero TCs. Check for that to avoid
12264                  * divide-by-zero. It probably won't pass traffic, but it also
12265                  * won't panic.
12266                  */
12267                 qcount = vsi->num_queue_pairs /
12268                          (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12269                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12270         }
12271         if (!vsi->rss_size)
12272                 return -EINVAL;
12273
12274         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12275         if (!lut)
12276                 return -ENOMEM;
12277
12278         /* Use user configured lut if there is one, otherwise use default */
12279         if (vsi->rss_lut_user)
12280                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12281         else
12282                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12283
12284         /* Use user configured hash key if there is one, otherwise
12285          * use default.
12286          */
12287         if (vsi->rss_hkey_user)
12288                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12289         else
12290                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12291         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12292         kfree(lut);
12293
12294         return ret;
12295 }
12296
12297 /**
12298  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12299  * @pf: board private structure
12300  * @queue_count: the requested queue count for rss.
12301  *
12302  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12303  * count which may be different from the requested queue count.
12304  * Note: expects to be called while under rtnl_lock()
12305  **/
12306 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12307 {
12308         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12309         int new_rss_size;
12310
12311         if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12312                 return 0;
12313
12314         queue_count = min_t(int, queue_count, num_online_cpus());
12315         new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12316
12317         if (queue_count != vsi->num_queue_pairs) {
12318                 u16 qcount;
12319
12320                 vsi->req_queue_pairs = queue_count;
12321                 i40e_prep_for_reset(pf);
12322                 if (test_bit(__I40E_IN_REMOVE, pf->state))
12323                         return pf->alloc_rss_size;
12324
12325                 pf->alloc_rss_size = new_rss_size;
12326
12327                 i40e_reset_and_rebuild(pf, true, true);
12328
12329                 /* Discard the user configured hash keys and lut, if less
12330                  * queues are enabled.
12331                  */
12332                 if (queue_count < vsi->rss_size) {
12333                         i40e_clear_rss_config_user(vsi);
12334                         dev_dbg(&pf->pdev->dev,
12335                                 "discard user configured hash keys and lut\n");
12336                 }
12337
12338                 /* Reset vsi->rss_size, as number of enabled queues changed */
12339                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12340                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12341
12342                 i40e_pf_config_rss(pf);
12343         }
12344         dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12345                  vsi->req_queue_pairs, pf->rss_size_max);
12346         return pf->alloc_rss_size;
12347 }
12348
12349 /**
12350  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12351  * @pf: board private structure
12352  **/
12353 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
12354 {
12355         i40e_status status;
12356         bool min_valid, max_valid;
12357         u32 max_bw, min_bw;
12358
12359         status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12360                                            &min_valid, &max_valid);
12361
12362         if (!status) {
12363                 if (min_valid)
12364                         pf->min_bw = min_bw;
12365                 if (max_valid)
12366                         pf->max_bw = max_bw;
12367         }
12368
12369         return status;
12370 }
12371
12372 /**
12373  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12374  * @pf: board private structure
12375  **/
12376 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
12377 {
12378         struct i40e_aqc_configure_partition_bw_data bw_data;
12379         i40e_status status;
12380
12381         memset(&bw_data, 0, sizeof(bw_data));
12382
12383         /* Set the valid bit for this PF */
12384         bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12385         bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12386         bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12387
12388         /* Set the new bandwidths */
12389         status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12390
12391         return status;
12392 }
12393
12394 /**
12395  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12396  * @pf: board private structure
12397  **/
12398 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12399 {
12400         /* Commit temporary BW setting to permanent NVM image */
12401         enum i40e_admin_queue_err last_aq_status;
12402         i40e_status ret;
12403         u16 nvm_word;
12404
12405         if (pf->hw.partition_id != 1) {
12406                 dev_info(&pf->pdev->dev,
12407                          "Commit BW only works on partition 1! This is partition %d",
12408                          pf->hw.partition_id);
12409                 ret = I40E_NOT_SUPPORTED;
12410                 goto bw_commit_out;
12411         }
12412
12413         /* Acquire NVM for read access */
12414         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12415         last_aq_status = pf->hw.aq.asq_last_status;
12416         if (ret) {
12417                 dev_info(&pf->pdev->dev,
12418                          "Cannot acquire NVM for read access, err %s aq_err %s\n",
12419                          i40e_stat_str(&pf->hw, ret),
12420                          i40e_aq_str(&pf->hw, last_aq_status));
12421                 goto bw_commit_out;
12422         }
12423
12424         /* Read word 0x10 of NVM - SW compatibility word 1 */
12425         ret = i40e_aq_read_nvm(&pf->hw,
12426                                I40E_SR_NVM_CONTROL_WORD,
12427                                0x10, sizeof(nvm_word), &nvm_word,
12428                                false, NULL);
12429         /* Save off last admin queue command status before releasing
12430          * the NVM
12431          */
12432         last_aq_status = pf->hw.aq.asq_last_status;
12433         i40e_release_nvm(&pf->hw);
12434         if (ret) {
12435                 dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
12436                          i40e_stat_str(&pf->hw, ret),
12437                          i40e_aq_str(&pf->hw, last_aq_status));
12438                 goto bw_commit_out;
12439         }
12440
12441         /* Wait a bit for NVM release to complete */
12442         msleep(50);
12443
12444         /* Acquire NVM for write access */
12445         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12446         last_aq_status = pf->hw.aq.asq_last_status;
12447         if (ret) {
12448                 dev_info(&pf->pdev->dev,
12449                          "Cannot acquire NVM for write access, err %s aq_err %s\n",
12450                          i40e_stat_str(&pf->hw, ret),
12451                          i40e_aq_str(&pf->hw, last_aq_status));
12452                 goto bw_commit_out;
12453         }
12454         /* Write it back out unchanged to initiate update NVM,
12455          * which will force a write of the shadow (alt) RAM to
12456          * the NVM - thus storing the bandwidth values permanently.
12457          */
12458         ret = i40e_aq_update_nvm(&pf->hw,
12459                                  I40E_SR_NVM_CONTROL_WORD,
12460                                  0x10, sizeof(nvm_word),
12461                                  &nvm_word, true, 0, NULL);
12462         /* Save off last admin queue command status before releasing
12463          * the NVM
12464          */
12465         last_aq_status = pf->hw.aq.asq_last_status;
12466         i40e_release_nvm(&pf->hw);
12467         if (ret)
12468                 dev_info(&pf->pdev->dev,
12469                          "BW settings NOT SAVED, err %s aq_err %s\n",
12470                          i40e_stat_str(&pf->hw, ret),
12471                          i40e_aq_str(&pf->hw, last_aq_status));
12472 bw_commit_out:
12473
12474         return ret;
12475 }
12476
12477 /**
12478  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12479  * if total port shutdown feature is enabled for this PF
12480  * @pf: board private structure
12481  **/
12482 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12483 {
12484 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED        BIT(4)
12485 #define I40E_FEATURES_ENABLE_PTR                0x2A
12486 #define I40E_CURRENT_SETTING_PTR                0x2B
12487 #define I40E_LINK_BEHAVIOR_WORD_OFFSET          0x2D
12488 #define I40E_LINK_BEHAVIOR_WORD_LENGTH          0x1
12489 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED    BIT(0)
12490 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH      4
12491         i40e_status read_status = I40E_SUCCESS;
12492         u16 sr_emp_sr_settings_ptr = 0;
12493         u16 features_enable = 0;
12494         u16 link_behavior = 0;
12495         bool ret = false;
12496
12497         read_status = i40e_read_nvm_word(&pf->hw,
12498                                          I40E_SR_EMP_SR_SETTINGS_PTR,
12499                                          &sr_emp_sr_settings_ptr);
12500         if (read_status)
12501                 goto err_nvm;
12502         read_status = i40e_read_nvm_word(&pf->hw,
12503                                          sr_emp_sr_settings_ptr +
12504                                          I40E_FEATURES_ENABLE_PTR,
12505                                          &features_enable);
12506         if (read_status)
12507                 goto err_nvm;
12508         if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12509                 read_status = i40e_read_nvm_module_data(&pf->hw,
12510                                                         I40E_SR_EMP_SR_SETTINGS_PTR,
12511                                                         I40E_CURRENT_SETTING_PTR,
12512                                                         I40E_LINK_BEHAVIOR_WORD_OFFSET,
12513                                                         I40E_LINK_BEHAVIOR_WORD_LENGTH,
12514                                                         &link_behavior);
12515                 if (read_status)
12516                         goto err_nvm;
12517                 link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12518                 ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12519         }
12520         return ret;
12521
12522 err_nvm:
12523         dev_warn(&pf->pdev->dev,
12524                  "total-port-shutdown feature is off due to read nvm error: %s\n",
12525                  i40e_stat_str(&pf->hw, read_status));
12526         return ret;
12527 }
12528
12529 /**
12530  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12531  * @pf: board private structure to initialize
12532  *
12533  * i40e_sw_init initializes the Adapter private data structure.
12534  * Fields are initialized based on PCI device information and
12535  * OS network device settings (MTU size).
12536  **/
12537 static int i40e_sw_init(struct i40e_pf *pf)
12538 {
12539         int err = 0;
12540         int size;
12541         u16 pow;
12542
12543         /* Set default capability flags */
12544         pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12545                     I40E_FLAG_MSI_ENABLED     |
12546                     I40E_FLAG_MSIX_ENABLED;
12547
12548         /* Set default ITR */
12549         pf->rx_itr_default = I40E_ITR_RX_DEF;
12550         pf->tx_itr_default = I40E_ITR_TX_DEF;
12551
12552         /* Depending on PF configurations, it is possible that the RSS
12553          * maximum might end up larger than the available queues
12554          */
12555         pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12556         pf->alloc_rss_size = 1;
12557         pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12558         pf->rss_size_max = min_t(int, pf->rss_size_max,
12559                                  pf->hw.func_caps.num_tx_qp);
12560
12561         /* find the next higher power-of-2 of num cpus */
12562         pow = roundup_pow_of_two(num_online_cpus());
12563         pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12564
12565         if (pf->hw.func_caps.rss) {
12566                 pf->flags |= I40E_FLAG_RSS_ENABLED;
12567                 pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12568                                            num_online_cpus());
12569         }
12570
12571         /* MFP mode enabled */
12572         if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12573                 pf->flags |= I40E_FLAG_MFP_ENABLED;
12574                 dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12575                 if (i40e_get_partition_bw_setting(pf)) {
12576                         dev_warn(&pf->pdev->dev,
12577                                  "Could not get partition bw settings\n");
12578                 } else {
12579                         dev_info(&pf->pdev->dev,
12580                                  "Partition BW Min = %8.8x, Max = %8.8x\n",
12581                                  pf->min_bw, pf->max_bw);
12582
12583                         /* nudge the Tx scheduler */
12584                         i40e_set_partition_bw_setting(pf);
12585                 }
12586         }
12587
12588         if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12589             (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12590                 pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12591                 pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12592                 if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12593                     pf->hw.num_partitions > 1)
12594                         dev_info(&pf->pdev->dev,
12595                                  "Flow Director Sideband mode Disabled in MFP mode\n");
12596                 else
12597                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12598                 pf->fdir_pf_filter_count =
12599                                  pf->hw.func_caps.fd_filters_guaranteed;
12600                 pf->hw.fdir_shared_filter_count =
12601                                  pf->hw.func_caps.fd_filters_best_effort;
12602         }
12603
12604         if (pf->hw.mac.type == I40E_MAC_X722) {
12605                 pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12606                                     I40E_HW_128_QP_RSS_CAPABLE |
12607                                     I40E_HW_ATR_EVICT_CAPABLE |
12608                                     I40E_HW_WB_ON_ITR_CAPABLE |
12609                                     I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12610                                     I40E_HW_NO_PCI_LINK_CHECK |
12611                                     I40E_HW_USE_SET_LLDP_MIB |
12612                                     I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12613                                     I40E_HW_PTP_L4_CAPABLE |
12614                                     I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12615                                     I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12616
12617 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12618                 if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12619                     I40E_FDEVICT_PCTYPE_DEFAULT) {
12620                         dev_warn(&pf->pdev->dev,
12621                                  "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12622                         pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12623                 }
12624         } else if ((pf->hw.aq.api_maj_ver > 1) ||
12625                    ((pf->hw.aq.api_maj_ver == 1) &&
12626                     (pf->hw.aq.api_min_ver > 4))) {
12627                 /* Supported in FW API version higher than 1.4 */
12628                 pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12629         }
12630
12631         /* Enable HW ATR eviction if possible */
12632         if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12633                 pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12634
12635         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12636             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12637             (pf->hw.aq.fw_maj_ver < 4))) {
12638                 pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12639                 /* No DCB support  for FW < v4.33 */
12640                 pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12641         }
12642
12643         /* Disable FW LLDP if FW < v4.3 */
12644         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12645             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12646             (pf->hw.aq.fw_maj_ver < 4)))
12647                 pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12648
12649         /* Use the FW Set LLDP MIB API if FW > v4.40 */
12650         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12651             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12652             (pf->hw.aq.fw_maj_ver >= 5)))
12653                 pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12654
12655         /* Enable PTP L4 if FW > v6.0 */
12656         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12657             pf->hw.aq.fw_maj_ver >= 6)
12658                 pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12659
12660         if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12661                 pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12662                 pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12663                 pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12664         }
12665
12666         if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12667                 pf->flags |= I40E_FLAG_IWARP_ENABLED;
12668                 /* IWARP needs one extra vector for CQP just like MISC.*/
12669                 pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12670         }
12671         /* Stopping FW LLDP engine is supported on XL710 and X722
12672          * starting from FW versions determined in i40e_init_adminq.
12673          * Stopping the FW LLDP engine is not supported on XL710
12674          * if NPAR is functioning so unset this hw flag in this case.
12675          */
12676         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12677             pf->hw.func_caps.npar_enable &&
12678             (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12679                 pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12680
12681 #ifdef CONFIG_PCI_IOV
12682         if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12683                 pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12684                 pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12685                 pf->num_req_vfs = min_t(int,
12686                                         pf->hw.func_caps.num_vfs,
12687                                         I40E_MAX_VF_COUNT);
12688         }
12689 #endif /* CONFIG_PCI_IOV */
12690         pf->eeprom_version = 0xDEAD;
12691         pf->lan_veb = I40E_NO_VEB;
12692         pf->lan_vsi = I40E_NO_VSI;
12693
12694         /* By default FW has this off for performance reasons */
12695         pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12696
12697         /* set up queue assignment tracking */
12698         size = sizeof(struct i40e_lump_tracking)
12699                 + (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12700         pf->qp_pile = kzalloc(size, GFP_KERNEL);
12701         if (!pf->qp_pile) {
12702                 err = -ENOMEM;
12703                 goto sw_init_done;
12704         }
12705         pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12706
12707         pf->tx_timeout_recovery_level = 1;
12708
12709         if (pf->hw.mac.type != I40E_MAC_X722 &&
12710             i40e_is_total_port_shutdown_enabled(pf)) {
12711                 /* Link down on close must be on when total port shutdown
12712                  * is enabled for a given port
12713                  */
12714                 pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12715                               I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12716                 dev_info(&pf->pdev->dev,
12717                          "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12718         }
12719         mutex_init(&pf->switch_mutex);
12720
12721 sw_init_done:
12722         return err;
12723 }
12724
12725 /**
12726  * i40e_set_ntuple - set the ntuple feature flag and take action
12727  * @pf: board private structure to initialize
12728  * @features: the feature set that the stack is suggesting
12729  *
12730  * returns a bool to indicate if reset needs to happen
12731  **/
12732 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12733 {
12734         bool need_reset = false;
12735
12736         /* Check if Flow Director n-tuple support was enabled or disabled.  If
12737          * the state changed, we need to reset.
12738          */
12739         if (features & NETIF_F_NTUPLE) {
12740                 /* Enable filters and mark for reset */
12741                 if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12742                         need_reset = true;
12743                 /* enable FD_SB only if there is MSI-X vector and no cloud
12744                  * filters exist
12745                  */
12746                 if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12747                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12748                         pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12749                 }
12750         } else {
12751                 /* turn off filters, mark for reset and clear SW filter list */
12752                 if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12753                         need_reset = true;
12754                         i40e_fdir_filter_exit(pf);
12755                 }
12756                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12757                 clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12758                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12759
12760                 /* reset fd counters */
12761                 pf->fd_add_err = 0;
12762                 pf->fd_atr_cnt = 0;
12763                 /* if ATR was auto disabled it can be re-enabled. */
12764                 if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12765                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12766                             (I40E_DEBUG_FD & pf->hw.debug_mask))
12767                                 dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12768         }
12769         return need_reset;
12770 }
12771
12772 /**
12773  * i40e_clear_rss_lut - clear the rx hash lookup table
12774  * @vsi: the VSI being configured
12775  **/
12776 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12777 {
12778         struct i40e_pf *pf = vsi->back;
12779         struct i40e_hw *hw = &pf->hw;
12780         u16 vf_id = vsi->vf_id;
12781         u8 i;
12782
12783         if (vsi->type == I40E_VSI_MAIN) {
12784                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12785                         wr32(hw, I40E_PFQF_HLUT(i), 0);
12786         } else if (vsi->type == I40E_VSI_SRIOV) {
12787                 for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12788                         i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12789         } else {
12790                 dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12791         }
12792 }
12793
12794 /**
12795  * i40e_set_features - set the netdev feature flags
12796  * @netdev: ptr to the netdev being adjusted
12797  * @features: the feature set that the stack is suggesting
12798  * Note: expects to be called while under rtnl_lock()
12799  **/
12800 static int i40e_set_features(struct net_device *netdev,
12801                              netdev_features_t features)
12802 {
12803         struct i40e_netdev_priv *np = netdev_priv(netdev);
12804         struct i40e_vsi *vsi = np->vsi;
12805         struct i40e_pf *pf = vsi->back;
12806         bool need_reset;
12807
12808         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12809                 i40e_pf_config_rss(pf);
12810         else if (!(features & NETIF_F_RXHASH) &&
12811                  netdev->features & NETIF_F_RXHASH)
12812                 i40e_clear_rss_lut(vsi);
12813
12814         if (features & NETIF_F_HW_VLAN_CTAG_RX)
12815                 i40e_vlan_stripping_enable(vsi);
12816         else
12817                 i40e_vlan_stripping_disable(vsi);
12818
12819         if (!(features & NETIF_F_HW_TC) &&
12820             (netdev->features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12821                 dev_err(&pf->pdev->dev,
12822                         "Offloaded tc filters active, can't turn hw_tc_offload off");
12823                 return -EINVAL;
12824         }
12825
12826         if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12827                 i40e_del_all_macvlans(vsi);
12828
12829         need_reset = i40e_set_ntuple(pf, features);
12830
12831         if (need_reset)
12832                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12833
12834         return 0;
12835 }
12836
12837 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12838                                     unsigned int table, unsigned int idx,
12839                                     struct udp_tunnel_info *ti)
12840 {
12841         struct i40e_netdev_priv *np = netdev_priv(netdev);
12842         struct i40e_hw *hw = &np->vsi->back->hw;
12843         u8 type, filter_index;
12844         i40e_status ret;
12845
12846         type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
12847                                                    I40E_AQC_TUNNEL_TYPE_NGE;
12848
12849         ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
12850                                      NULL);
12851         if (ret) {
12852                 netdev_info(netdev, "add UDP port failed, err %s aq_err %s\n",
12853                             i40e_stat_str(hw, ret),
12854                             i40e_aq_str(hw, hw->aq.asq_last_status));
12855                 return -EIO;
12856         }
12857
12858         udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
12859         return 0;
12860 }
12861
12862 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
12863                                       unsigned int table, unsigned int idx,
12864                                       struct udp_tunnel_info *ti)
12865 {
12866         struct i40e_netdev_priv *np = netdev_priv(netdev);
12867         struct i40e_hw *hw = &np->vsi->back->hw;
12868         i40e_status ret;
12869
12870         ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
12871         if (ret) {
12872                 netdev_info(netdev, "delete UDP port failed, err %s aq_err %s\n",
12873                             i40e_stat_str(hw, ret),
12874                             i40e_aq_str(hw, hw->aq.asq_last_status));
12875                 return -EIO;
12876         }
12877
12878         return 0;
12879 }
12880
12881 static int i40e_get_phys_port_id(struct net_device *netdev,
12882                                  struct netdev_phys_item_id *ppid)
12883 {
12884         struct i40e_netdev_priv *np = netdev_priv(netdev);
12885         struct i40e_pf *pf = np->vsi->back;
12886         struct i40e_hw *hw = &pf->hw;
12887
12888         if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
12889                 return -EOPNOTSUPP;
12890
12891         ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
12892         memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
12893
12894         return 0;
12895 }
12896
12897 /**
12898  * i40e_ndo_fdb_add - add an entry to the hardware database
12899  * @ndm: the input from the stack
12900  * @tb: pointer to array of nladdr (unused)
12901  * @dev: the net device pointer
12902  * @addr: the MAC address entry being added
12903  * @vid: VLAN ID
12904  * @flags: instructions from stack about fdb operation
12905  * @extack: netlink extended ack, unused currently
12906  */
12907 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
12908                             struct net_device *dev,
12909                             const unsigned char *addr, u16 vid,
12910                             u16 flags,
12911                             struct netlink_ext_ack *extack)
12912 {
12913         struct i40e_netdev_priv *np = netdev_priv(dev);
12914         struct i40e_pf *pf = np->vsi->back;
12915         int err = 0;
12916
12917         if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
12918                 return -EOPNOTSUPP;
12919
12920         if (vid) {
12921                 pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
12922                 return -EINVAL;
12923         }
12924
12925         /* Hardware does not support aging addresses so if a
12926          * ndm_state is given only allow permanent addresses
12927          */
12928         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
12929                 netdev_info(dev, "FDB only supports static addresses\n");
12930                 return -EINVAL;
12931         }
12932
12933         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
12934                 err = dev_uc_add_excl(dev, addr);
12935         else if (is_multicast_ether_addr(addr))
12936                 err = dev_mc_add_excl(dev, addr);
12937         else
12938                 err = -EINVAL;
12939
12940         /* Only return duplicate errors if NLM_F_EXCL is set */
12941         if (err == -EEXIST && !(flags & NLM_F_EXCL))
12942                 err = 0;
12943
12944         return err;
12945 }
12946
12947 /**
12948  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
12949  * @dev: the netdev being configured
12950  * @nlh: RTNL message
12951  * @flags: bridge flags
12952  * @extack: netlink extended ack
12953  *
12954  * Inserts a new hardware bridge if not already created and
12955  * enables the bridging mode requested (VEB or VEPA). If the
12956  * hardware bridge has already been inserted and the request
12957  * is to change the mode then that requires a PF reset to
12958  * allow rebuild of the components with required hardware
12959  * bridge mode enabled.
12960  *
12961  * Note: expects to be called while under rtnl_lock()
12962  **/
12963 static int i40e_ndo_bridge_setlink(struct net_device *dev,
12964                                    struct nlmsghdr *nlh,
12965                                    u16 flags,
12966                                    struct netlink_ext_ack *extack)
12967 {
12968         struct i40e_netdev_priv *np = netdev_priv(dev);
12969         struct i40e_vsi *vsi = np->vsi;
12970         struct i40e_pf *pf = vsi->back;
12971         struct i40e_veb *veb = NULL;
12972         struct nlattr *attr, *br_spec;
12973         int i, rem;
12974
12975         /* Only for PF VSI for now */
12976         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
12977                 return -EOPNOTSUPP;
12978
12979         /* Find the HW bridge for PF VSI */
12980         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
12981                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
12982                         veb = pf->veb[i];
12983         }
12984
12985         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
12986
12987         nla_for_each_nested(attr, br_spec, rem) {
12988                 __u16 mode;
12989
12990                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
12991                         continue;
12992
12993                 mode = nla_get_u16(attr);
12994                 if ((mode != BRIDGE_MODE_VEPA) &&
12995                     (mode != BRIDGE_MODE_VEB))
12996                         return -EINVAL;
12997
12998                 /* Insert a new HW bridge */
12999                 if (!veb) {
13000                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13001                                              vsi->tc_config.enabled_tc);
13002                         if (veb) {
13003                                 veb->bridge_mode = mode;
13004                                 i40e_config_bridge_mode(veb);
13005                         } else {
13006                                 /* No Bridge HW offload available */
13007                                 return -ENOENT;
13008                         }
13009                         break;
13010                 } else if (mode != veb->bridge_mode) {
13011                         /* Existing HW bridge but different mode needs reset */
13012                         veb->bridge_mode = mode;
13013                         /* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
13014                         if (mode == BRIDGE_MODE_VEB)
13015                                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
13016                         else
13017                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13018                         i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
13019                         break;
13020                 }
13021         }
13022
13023         return 0;
13024 }
13025
13026 /**
13027  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
13028  * @skb: skb buff
13029  * @pid: process id
13030  * @seq: RTNL message seq #
13031  * @dev: the netdev being configured
13032  * @filter_mask: unused
13033  * @nlflags: netlink flags passed in
13034  *
13035  * Return the mode in which the hardware bridge is operating in
13036  * i.e VEB or VEPA.
13037  **/
13038 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
13039                                    struct net_device *dev,
13040                                    u32 __always_unused filter_mask,
13041                                    int nlflags)
13042 {
13043         struct i40e_netdev_priv *np = netdev_priv(dev);
13044         struct i40e_vsi *vsi = np->vsi;
13045         struct i40e_pf *pf = vsi->back;
13046         struct i40e_veb *veb = NULL;
13047         int i;
13048
13049         /* Only for PF VSI for now */
13050         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
13051                 return -EOPNOTSUPP;
13052
13053         /* Find the HW bridge for the PF VSI */
13054         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13055                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13056                         veb = pf->veb[i];
13057         }
13058
13059         if (!veb)
13060                 return 0;
13061
13062         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
13063                                        0, 0, nlflags, filter_mask, NULL);
13064 }
13065
13066 /**
13067  * i40e_features_check - Validate encapsulated packet conforms to limits
13068  * @skb: skb buff
13069  * @dev: This physical port's netdev
13070  * @features: Offload features that the stack believes apply
13071  **/
13072 static netdev_features_t i40e_features_check(struct sk_buff *skb,
13073                                              struct net_device *dev,
13074                                              netdev_features_t features)
13075 {
13076         size_t len;
13077
13078         /* No point in doing any of this if neither checksum nor GSO are
13079          * being requested for this frame.  We can rule out both by just
13080          * checking for CHECKSUM_PARTIAL
13081          */
13082         if (skb->ip_summed != CHECKSUM_PARTIAL)
13083                 return features;
13084
13085         /* We cannot support GSO if the MSS is going to be less than
13086          * 64 bytes.  If it is then we need to drop support for GSO.
13087          */
13088         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
13089                 features &= ~NETIF_F_GSO_MASK;
13090
13091         /* MACLEN can support at most 63 words */
13092         len = skb_network_header(skb) - skb->data;
13093         if (len & ~(63 * 2))
13094                 goto out_err;
13095
13096         /* IPLEN and EIPLEN can support at most 127 dwords */
13097         len = skb_transport_header(skb) - skb_network_header(skb);
13098         if (len & ~(127 * 4))
13099                 goto out_err;
13100
13101         if (skb->encapsulation) {
13102                 /* L4TUNLEN can support 127 words */
13103                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
13104                 if (len & ~(127 * 2))
13105                         goto out_err;
13106
13107                 /* IPLEN can support at most 127 dwords */
13108                 len = skb_inner_transport_header(skb) -
13109                       skb_inner_network_header(skb);
13110                 if (len & ~(127 * 4))
13111                         goto out_err;
13112         }
13113
13114         /* No need to validate L4LEN as TCP is the only protocol with a
13115          * a flexible value and we support all possible values supported
13116          * by TCP, which is at most 15 dwords
13117          */
13118
13119         return features;
13120 out_err:
13121         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
13122 }
13123
13124 /**
13125  * i40e_xdp_setup - add/remove an XDP program
13126  * @vsi: VSI to changed
13127  * @prog: XDP program
13128  * @extack: netlink extended ack
13129  **/
13130 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
13131                           struct netlink_ext_ack *extack)
13132 {
13133         int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
13134         struct i40e_pf *pf = vsi->back;
13135         struct bpf_prog *old_prog;
13136         bool need_reset;
13137         int i;
13138
13139         /* Don't allow frames that span over multiple buffers */
13140         if (frame_size > vsi->rx_buf_len) {
13141                 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
13142                 return -EINVAL;
13143         }
13144
13145         /* When turning XDP on->off/off->on we reset and rebuild the rings. */
13146         need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
13147
13148         if (need_reset)
13149                 i40e_prep_for_reset(pf);
13150
13151         /* VSI shall be deleted in a moment, just return EINVAL */
13152         if (test_bit(__I40E_IN_REMOVE, pf->state))
13153                 return -EINVAL;
13154
13155         old_prog = xchg(&vsi->xdp_prog, prog);
13156
13157         if (need_reset) {
13158                 if (!prog)
13159                         /* Wait until ndo_xsk_wakeup completes. */
13160                         synchronize_rcu();
13161                 i40e_reset_and_rebuild(pf, true, true);
13162         }
13163
13164         for (i = 0; i < vsi->num_queue_pairs; i++)
13165                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
13166
13167         if (old_prog)
13168                 bpf_prog_put(old_prog);
13169
13170         /* Kick start the NAPI context if there is an AF_XDP socket open
13171          * on that queue id. This so that receiving will start.
13172          */
13173         if (need_reset && prog)
13174                 for (i = 0; i < vsi->num_queue_pairs; i++)
13175                         if (vsi->xdp_rings[i]->xsk_pool)
13176                                 (void)i40e_xsk_wakeup(vsi->netdev, i,
13177                                                       XDP_WAKEUP_RX);
13178
13179         return 0;
13180 }
13181
13182 /**
13183  * i40e_enter_busy_conf - Enters busy config state
13184  * @vsi: vsi
13185  *
13186  * Returns 0 on success, <0 for failure.
13187  **/
13188 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
13189 {
13190         struct i40e_pf *pf = vsi->back;
13191         int timeout = 50;
13192
13193         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
13194                 timeout--;
13195                 if (!timeout)
13196                         return -EBUSY;
13197                 usleep_range(1000, 2000);
13198         }
13199
13200         return 0;
13201 }
13202
13203 /**
13204  * i40e_exit_busy_conf - Exits busy config state
13205  * @vsi: vsi
13206  **/
13207 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13208 {
13209         struct i40e_pf *pf = vsi->back;
13210
13211         clear_bit(__I40E_CONFIG_BUSY, pf->state);
13212 }
13213
13214 /**
13215  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13216  * @vsi: vsi
13217  * @queue_pair: queue pair
13218  **/
13219 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13220 {
13221         memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13222                sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13223         memset(&vsi->tx_rings[queue_pair]->stats, 0,
13224                sizeof(vsi->tx_rings[queue_pair]->stats));
13225         if (i40e_enabled_xdp_vsi(vsi)) {
13226                 memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13227                        sizeof(vsi->xdp_rings[queue_pair]->stats));
13228         }
13229 }
13230
13231 /**
13232  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13233  * @vsi: vsi
13234  * @queue_pair: queue pair
13235  **/
13236 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13237 {
13238         i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13239         if (i40e_enabled_xdp_vsi(vsi)) {
13240                 /* Make sure that in-progress ndo_xdp_xmit calls are
13241                  * completed.
13242                  */
13243                 synchronize_rcu();
13244                 i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13245         }
13246         i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13247 }
13248
13249 /**
13250  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13251  * @vsi: vsi
13252  * @queue_pair: queue pair
13253  * @enable: true for enable, false for disable
13254  **/
13255 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13256                                         bool enable)
13257 {
13258         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13259         struct i40e_q_vector *q_vector = rxr->q_vector;
13260
13261         if (!vsi->netdev)
13262                 return;
13263
13264         /* All rings in a qp belong to the same qvector. */
13265         if (q_vector->rx.ring || q_vector->tx.ring) {
13266                 if (enable)
13267                         napi_enable(&q_vector->napi);
13268                 else
13269                         napi_disable(&q_vector->napi);
13270         }
13271 }
13272
13273 /**
13274  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13275  * @vsi: vsi
13276  * @queue_pair: queue pair
13277  * @enable: true for enable, false for disable
13278  *
13279  * Returns 0 on success, <0 on failure.
13280  **/
13281 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13282                                         bool enable)
13283 {
13284         struct i40e_pf *pf = vsi->back;
13285         int pf_q, ret = 0;
13286
13287         pf_q = vsi->base_queue + queue_pair;
13288         ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13289                                      false /*is xdp*/, enable);
13290         if (ret) {
13291                 dev_info(&pf->pdev->dev,
13292                          "VSI seid %d Tx ring %d %sable timeout\n",
13293                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13294                 return ret;
13295         }
13296
13297         i40e_control_rx_q(pf, pf_q, enable);
13298         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13299         if (ret) {
13300                 dev_info(&pf->pdev->dev,
13301                          "VSI seid %d Rx ring %d %sable timeout\n",
13302                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13303                 return ret;
13304         }
13305
13306         /* Due to HW errata, on Rx disable only, the register can
13307          * indicate done before it really is. Needs 50ms to be sure
13308          */
13309         if (!enable)
13310                 mdelay(50);
13311
13312         if (!i40e_enabled_xdp_vsi(vsi))
13313                 return ret;
13314
13315         ret = i40e_control_wait_tx_q(vsi->seid, pf,
13316                                      pf_q + vsi->alloc_queue_pairs,
13317                                      true /*is xdp*/, enable);
13318         if (ret) {
13319                 dev_info(&pf->pdev->dev,
13320                          "VSI seid %d XDP Tx ring %d %sable timeout\n",
13321                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13322         }
13323
13324         return ret;
13325 }
13326
13327 /**
13328  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13329  * @vsi: vsi
13330  * @queue_pair: queue_pair
13331  **/
13332 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13333 {
13334         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13335         struct i40e_pf *pf = vsi->back;
13336         struct i40e_hw *hw = &pf->hw;
13337
13338         /* All rings in a qp belong to the same qvector. */
13339         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13340                 i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13341         else
13342                 i40e_irq_dynamic_enable_icr0(pf);
13343
13344         i40e_flush(hw);
13345 }
13346
13347 /**
13348  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13349  * @vsi: vsi
13350  * @queue_pair: queue_pair
13351  **/
13352 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13353 {
13354         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13355         struct i40e_pf *pf = vsi->back;
13356         struct i40e_hw *hw = &pf->hw;
13357
13358         /* For simplicity, instead of removing the qp interrupt causes
13359          * from the interrupt linked list, we simply disable the interrupt, and
13360          * leave the list intact.
13361          *
13362          * All rings in a qp belong to the same qvector.
13363          */
13364         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13365                 u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13366
13367                 wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13368                 i40e_flush(hw);
13369                 synchronize_irq(pf->msix_entries[intpf].vector);
13370         } else {
13371                 /* Legacy and MSI mode - this stops all interrupt handling */
13372                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13373                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13374                 i40e_flush(hw);
13375                 synchronize_irq(pf->pdev->irq);
13376         }
13377 }
13378
13379 /**
13380  * i40e_queue_pair_disable - Disables a queue pair
13381  * @vsi: vsi
13382  * @queue_pair: queue pair
13383  *
13384  * Returns 0 on success, <0 on failure.
13385  **/
13386 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13387 {
13388         int err;
13389
13390         err = i40e_enter_busy_conf(vsi);
13391         if (err)
13392                 return err;
13393
13394         i40e_queue_pair_disable_irq(vsi, queue_pair);
13395         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13396         i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13397         i40e_queue_pair_clean_rings(vsi, queue_pair);
13398         i40e_queue_pair_reset_stats(vsi, queue_pair);
13399
13400         return err;
13401 }
13402
13403 /**
13404  * i40e_queue_pair_enable - Enables a queue pair
13405  * @vsi: vsi
13406  * @queue_pair: queue pair
13407  *
13408  * Returns 0 on success, <0 on failure.
13409  **/
13410 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13411 {
13412         int err;
13413
13414         err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13415         if (err)
13416                 return err;
13417
13418         if (i40e_enabled_xdp_vsi(vsi)) {
13419                 err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13420                 if (err)
13421                         return err;
13422         }
13423
13424         err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13425         if (err)
13426                 return err;
13427
13428         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13429         i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13430         i40e_queue_pair_enable_irq(vsi, queue_pair);
13431
13432         i40e_exit_busy_conf(vsi);
13433
13434         return err;
13435 }
13436
13437 /**
13438  * i40e_xdp - implements ndo_bpf for i40e
13439  * @dev: netdevice
13440  * @xdp: XDP command
13441  **/
13442 static int i40e_xdp(struct net_device *dev,
13443                     struct netdev_bpf *xdp)
13444 {
13445         struct i40e_netdev_priv *np = netdev_priv(dev);
13446         struct i40e_vsi *vsi = np->vsi;
13447
13448         if (vsi->type != I40E_VSI_MAIN)
13449                 return -EINVAL;
13450
13451         switch (xdp->command) {
13452         case XDP_SETUP_PROG:
13453                 return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13454         case XDP_SETUP_XSK_POOL:
13455                 return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13456                                            xdp->xsk.queue_id);
13457         default:
13458                 return -EINVAL;
13459         }
13460 }
13461
13462 static const struct net_device_ops i40e_netdev_ops = {
13463         .ndo_open               = i40e_open,
13464         .ndo_stop               = i40e_close,
13465         .ndo_start_xmit         = i40e_lan_xmit_frame,
13466         .ndo_get_stats64        = i40e_get_netdev_stats_struct,
13467         .ndo_set_rx_mode        = i40e_set_rx_mode,
13468         .ndo_validate_addr      = eth_validate_addr,
13469         .ndo_set_mac_address    = i40e_set_mac,
13470         .ndo_change_mtu         = i40e_change_mtu,
13471         .ndo_eth_ioctl          = i40e_ioctl,
13472         .ndo_tx_timeout         = i40e_tx_timeout,
13473         .ndo_vlan_rx_add_vid    = i40e_vlan_rx_add_vid,
13474         .ndo_vlan_rx_kill_vid   = i40e_vlan_rx_kill_vid,
13475 #ifdef CONFIG_NET_POLL_CONTROLLER
13476         .ndo_poll_controller    = i40e_netpoll,
13477 #endif
13478         .ndo_setup_tc           = __i40e_setup_tc,
13479         .ndo_select_queue       = i40e_lan_select_queue,
13480         .ndo_set_features       = i40e_set_features,
13481         .ndo_set_vf_mac         = i40e_ndo_set_vf_mac,
13482         .ndo_set_vf_vlan        = i40e_ndo_set_vf_port_vlan,
13483         .ndo_get_vf_stats       = i40e_get_vf_stats,
13484         .ndo_set_vf_rate        = i40e_ndo_set_vf_bw,
13485         .ndo_get_vf_config      = i40e_ndo_get_vf_config,
13486         .ndo_set_vf_link_state  = i40e_ndo_set_vf_link_state,
13487         .ndo_set_vf_spoofchk    = i40e_ndo_set_vf_spoofchk,
13488         .ndo_set_vf_trust       = i40e_ndo_set_vf_trust,
13489         .ndo_get_phys_port_id   = i40e_get_phys_port_id,
13490         .ndo_fdb_add            = i40e_ndo_fdb_add,
13491         .ndo_features_check     = i40e_features_check,
13492         .ndo_bridge_getlink     = i40e_ndo_bridge_getlink,
13493         .ndo_bridge_setlink     = i40e_ndo_bridge_setlink,
13494         .ndo_bpf                = i40e_xdp,
13495         .ndo_xdp_xmit           = i40e_xdp_xmit,
13496         .ndo_xsk_wakeup         = i40e_xsk_wakeup,
13497         .ndo_dfwd_add_station   = i40e_fwd_add,
13498         .ndo_dfwd_del_station   = i40e_fwd_del,
13499 };
13500
13501 /**
13502  * i40e_config_netdev - Setup the netdev flags
13503  * @vsi: the VSI being configured
13504  *
13505  * Returns 0 on success, negative value on failure
13506  **/
13507 static int i40e_config_netdev(struct i40e_vsi *vsi)
13508 {
13509         struct i40e_pf *pf = vsi->back;
13510         struct i40e_hw *hw = &pf->hw;
13511         struct i40e_netdev_priv *np;
13512         struct net_device *netdev;
13513         u8 broadcast[ETH_ALEN];
13514         u8 mac_addr[ETH_ALEN];
13515         int etherdev_size;
13516         netdev_features_t hw_enc_features;
13517         netdev_features_t hw_features;
13518
13519         etherdev_size = sizeof(struct i40e_netdev_priv);
13520         netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13521         if (!netdev)
13522                 return -ENOMEM;
13523
13524         vsi->netdev = netdev;
13525         np = netdev_priv(netdev);
13526         np->vsi = vsi;
13527
13528         hw_enc_features = NETIF_F_SG                    |
13529                           NETIF_F_HW_CSUM               |
13530                           NETIF_F_HIGHDMA               |
13531                           NETIF_F_SOFT_FEATURES         |
13532                           NETIF_F_TSO                   |
13533                           NETIF_F_TSO_ECN               |
13534                           NETIF_F_TSO6                  |
13535                           NETIF_F_GSO_GRE               |
13536                           NETIF_F_GSO_GRE_CSUM          |
13537                           NETIF_F_GSO_PARTIAL           |
13538                           NETIF_F_GSO_IPXIP4            |
13539                           NETIF_F_GSO_IPXIP6            |
13540                           NETIF_F_GSO_UDP_TUNNEL        |
13541                           NETIF_F_GSO_UDP_TUNNEL_CSUM   |
13542                           NETIF_F_GSO_UDP_L4            |
13543                           NETIF_F_SCTP_CRC              |
13544                           NETIF_F_RXHASH                |
13545                           NETIF_F_RXCSUM                |
13546                           0;
13547
13548         if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13549                 netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13550
13551         netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13552
13553         netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13554
13555         netdev->hw_enc_features |= hw_enc_features;
13556
13557         /* record features VLANs can make use of */
13558         netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13559
13560 #define I40E_GSO_PARTIAL_FEATURES (NETIF_F_GSO_GRE |            \
13561                                    NETIF_F_GSO_GRE_CSUM |       \
13562                                    NETIF_F_GSO_IPXIP4 |         \
13563                                    NETIF_F_GSO_IPXIP6 |         \
13564                                    NETIF_F_GSO_UDP_TUNNEL |     \
13565                                    NETIF_F_GSO_UDP_TUNNEL_CSUM)
13566
13567         netdev->gso_partial_features = I40E_GSO_PARTIAL_FEATURES;
13568         netdev->features |= NETIF_F_GSO_PARTIAL |
13569                             I40E_GSO_PARTIAL_FEATURES;
13570
13571         netdev->mpls_features |= NETIF_F_SG;
13572         netdev->mpls_features |= NETIF_F_HW_CSUM;
13573         netdev->mpls_features |= NETIF_F_TSO;
13574         netdev->mpls_features |= NETIF_F_TSO6;
13575         netdev->mpls_features |= I40E_GSO_PARTIAL_FEATURES;
13576
13577         /* enable macvlan offloads */
13578         netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13579
13580         hw_features = hw_enc_features           |
13581                       NETIF_F_HW_VLAN_CTAG_TX   |
13582                       NETIF_F_HW_VLAN_CTAG_RX;
13583
13584         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13585                 hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13586
13587         netdev->hw_features |= hw_features;
13588
13589         netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13590         netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13591
13592         netdev->features &= ~NETIF_F_HW_TC;
13593
13594         if (vsi->type == I40E_VSI_MAIN) {
13595                 SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13596                 ether_addr_copy(mac_addr, hw->mac.perm_addr);
13597                 /* The following steps are necessary for two reasons. First,
13598                  * some older NVM configurations load a default MAC-VLAN
13599                  * filter that will accept any tagged packet, and we want to
13600                  * replace this with a normal filter. Additionally, it is
13601                  * possible our MAC address was provided by the platform using
13602                  * Open Firmware or similar.
13603                  *
13604                  * Thus, we need to remove the default filter and install one
13605                  * specific to the MAC address.
13606                  */
13607                 i40e_rm_default_mac_filter(vsi, mac_addr);
13608                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13609                 i40e_add_mac_filter(vsi, mac_addr);
13610                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13611         } else {
13612                 /* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13613                  * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13614                  * the end, which is 4 bytes long, so force truncation of the
13615                  * original name by IFNAMSIZ - 4
13616                  */
13617                 snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13618                          IFNAMSIZ - 4,
13619                          pf->vsi[pf->lan_vsi]->netdev->name);
13620                 eth_random_addr(mac_addr);
13621
13622                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13623                 i40e_add_mac_filter(vsi, mac_addr);
13624                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13625         }
13626
13627         /* Add the broadcast filter so that we initially will receive
13628          * broadcast packets. Note that when a new VLAN is first added the
13629          * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13630          * specific filters as part of transitioning into "vlan" operation.
13631          * When more VLANs are added, the driver will copy each existing MAC
13632          * filter and add it for the new VLAN.
13633          *
13634          * Broadcast filters are handled specially by
13635          * i40e_sync_filters_subtask, as the driver must to set the broadcast
13636          * promiscuous bit instead of adding this directly as a MAC/VLAN
13637          * filter. The subtask will update the correct broadcast promiscuous
13638          * bits as VLANs become active or inactive.
13639          */
13640         eth_broadcast_addr(broadcast);
13641         spin_lock_bh(&vsi->mac_filter_hash_lock);
13642         i40e_add_mac_filter(vsi, broadcast);
13643         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13644
13645         eth_hw_addr_set(netdev, mac_addr);
13646         ether_addr_copy(netdev->perm_addr, mac_addr);
13647
13648         /* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13649         netdev->neigh_priv_len = sizeof(u32) * 4;
13650
13651         netdev->priv_flags |= IFF_UNICAST_FLT;
13652         netdev->priv_flags |= IFF_SUPP_NOFCS;
13653         /* Setup netdev TC information */
13654         i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13655
13656         netdev->netdev_ops = &i40e_netdev_ops;
13657         netdev->watchdog_timeo = 5 * HZ;
13658         i40e_set_ethtool_ops(netdev);
13659
13660         /* MTU range: 68 - 9706 */
13661         netdev->min_mtu = ETH_MIN_MTU;
13662         netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13663
13664         return 0;
13665 }
13666
13667 /**
13668  * i40e_vsi_delete - Delete a VSI from the switch
13669  * @vsi: the VSI being removed
13670  *
13671  * Returns 0 on success, negative value on failure
13672  **/
13673 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13674 {
13675         /* remove default VSI is not allowed */
13676         if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13677                 return;
13678
13679         i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13680 }
13681
13682 /**
13683  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13684  * @vsi: the VSI being queried
13685  *
13686  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13687  **/
13688 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13689 {
13690         struct i40e_veb *veb;
13691         struct i40e_pf *pf = vsi->back;
13692
13693         /* Uplink is not a bridge so default to VEB */
13694         if (vsi->veb_idx >= I40E_MAX_VEB)
13695                 return 1;
13696
13697         veb = pf->veb[vsi->veb_idx];
13698         if (!veb) {
13699                 dev_info(&pf->pdev->dev,
13700                          "There is no veb associated with the bridge\n");
13701                 return -ENOENT;
13702         }
13703
13704         /* Uplink is a bridge in VEPA mode */
13705         if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13706                 return 0;
13707         } else {
13708                 /* Uplink is a bridge in VEB mode */
13709                 return 1;
13710         }
13711
13712         /* VEPA is now default bridge, so return 0 */
13713         return 0;
13714 }
13715
13716 /**
13717  * i40e_add_vsi - Add a VSI to the switch
13718  * @vsi: the VSI being configured
13719  *
13720  * This initializes a VSI context depending on the VSI type to be added and
13721  * passes it down to the add_vsi aq command.
13722  **/
13723 static int i40e_add_vsi(struct i40e_vsi *vsi)
13724 {
13725         int ret = -ENODEV;
13726         struct i40e_pf *pf = vsi->back;
13727         struct i40e_hw *hw = &pf->hw;
13728         struct i40e_vsi_context ctxt;
13729         struct i40e_mac_filter *f;
13730         struct hlist_node *h;
13731         int bkt;
13732
13733         u8 enabled_tc = 0x1; /* TC0 enabled */
13734         int f_count = 0;
13735
13736         memset(&ctxt, 0, sizeof(ctxt));
13737         switch (vsi->type) {
13738         case I40E_VSI_MAIN:
13739                 /* The PF's main VSI is already setup as part of the
13740                  * device initialization, so we'll not bother with
13741                  * the add_vsi call, but we will retrieve the current
13742                  * VSI context.
13743                  */
13744                 ctxt.seid = pf->main_vsi_seid;
13745                 ctxt.pf_num = pf->hw.pf_id;
13746                 ctxt.vf_num = 0;
13747                 ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13748                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13749                 if (ret) {
13750                         dev_info(&pf->pdev->dev,
13751                                  "couldn't get PF vsi config, err %s aq_err %s\n",
13752                                  i40e_stat_str(&pf->hw, ret),
13753                                  i40e_aq_str(&pf->hw,
13754                                              pf->hw.aq.asq_last_status));
13755                         return -ENOENT;
13756                 }
13757                 vsi->info = ctxt.info;
13758                 vsi->info.valid_sections = 0;
13759
13760                 vsi->seid = ctxt.seid;
13761                 vsi->id = ctxt.vsi_number;
13762
13763                 enabled_tc = i40e_pf_get_tc_map(pf);
13764
13765                 /* Source pruning is enabled by default, so the flag is
13766                  * negative logic - if it's set, we need to fiddle with
13767                  * the VSI to disable source pruning.
13768                  */
13769                 if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13770                         memset(&ctxt, 0, sizeof(ctxt));
13771                         ctxt.seid = pf->main_vsi_seid;
13772                         ctxt.pf_num = pf->hw.pf_id;
13773                         ctxt.vf_num = 0;
13774                         ctxt.info.valid_sections |=
13775                                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13776                         ctxt.info.switch_id =
13777                                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13778                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13779                         if (ret) {
13780                                 dev_info(&pf->pdev->dev,
13781                                          "update vsi failed, err %s aq_err %s\n",
13782                                          i40e_stat_str(&pf->hw, ret),
13783                                          i40e_aq_str(&pf->hw,
13784                                                      pf->hw.aq.asq_last_status));
13785                                 ret = -ENOENT;
13786                                 goto err;
13787                         }
13788                 }
13789
13790                 /* MFP mode setup queue map and update VSI */
13791                 if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
13792                     !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13793                         memset(&ctxt, 0, sizeof(ctxt));
13794                         ctxt.seid = pf->main_vsi_seid;
13795                         ctxt.pf_num = pf->hw.pf_id;
13796                         ctxt.vf_num = 0;
13797                         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13798                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13799                         if (ret) {
13800                                 dev_info(&pf->pdev->dev,
13801                                          "update vsi failed, err %s aq_err %s\n",
13802                                          i40e_stat_str(&pf->hw, ret),
13803                                          i40e_aq_str(&pf->hw,
13804                                                     pf->hw.aq.asq_last_status));
13805                                 ret = -ENOENT;
13806                                 goto err;
13807                         }
13808                         /* update the local VSI info queue map */
13809                         i40e_vsi_update_queue_map(vsi, &ctxt);
13810                         vsi->info.valid_sections = 0;
13811                 } else {
13812                         /* Default/Main VSI is only enabled for TC0
13813                          * reconfigure it to enable all TCs that are
13814                          * available on the port in SFP mode.
13815                          * For MFP case the iSCSI PF would use this
13816                          * flow to enable LAN+iSCSI TC.
13817                          */
13818                         ret = i40e_vsi_config_tc(vsi, enabled_tc);
13819                         if (ret) {
13820                                 /* Single TC condition is not fatal,
13821                                  * message and continue
13822                                  */
13823                                 dev_info(&pf->pdev->dev,
13824                                          "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
13825                                          enabled_tc,
13826                                          i40e_stat_str(&pf->hw, ret),
13827                                          i40e_aq_str(&pf->hw,
13828                                                     pf->hw.aq.asq_last_status));
13829                         }
13830                 }
13831                 break;
13832
13833         case I40E_VSI_FDIR:
13834                 ctxt.pf_num = hw->pf_id;
13835                 ctxt.vf_num = 0;
13836                 ctxt.uplink_seid = vsi->uplink_seid;
13837                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13838                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13839                 if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
13840                     (i40e_is_vsi_uplink_mode_veb(vsi))) {
13841                         ctxt.info.valid_sections |=
13842                              cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13843                         ctxt.info.switch_id =
13844                            cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13845                 }
13846                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13847                 break;
13848
13849         case I40E_VSI_VMDQ2:
13850                 ctxt.pf_num = hw->pf_id;
13851                 ctxt.vf_num = 0;
13852                 ctxt.uplink_seid = vsi->uplink_seid;
13853                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13854                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13855
13856                 /* This VSI is connected to VEB so the switch_id
13857                  * should be set to zero by default.
13858                  */
13859                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13860                         ctxt.info.valid_sections |=
13861                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13862                         ctxt.info.switch_id =
13863                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13864                 }
13865
13866                 /* Setup the VSI tx/rx queue map for TC0 only for now */
13867                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13868                 break;
13869
13870         case I40E_VSI_SRIOV:
13871                 ctxt.pf_num = hw->pf_id;
13872                 ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
13873                 ctxt.uplink_seid = vsi->uplink_seid;
13874                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13875                 ctxt.flags = I40E_AQ_VSI_TYPE_VF;
13876
13877                 /* This VSI is connected to VEB so the switch_id
13878                  * should be set to zero by default.
13879                  */
13880                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13881                         ctxt.info.valid_sections |=
13882                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13883                         ctxt.info.switch_id =
13884                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13885                 }
13886
13887                 if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
13888                         ctxt.info.valid_sections |=
13889                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
13890                         ctxt.info.queueing_opt_flags |=
13891                                 (I40E_AQ_VSI_QUE_OPT_TCP_ENA |
13892                                  I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
13893                 }
13894
13895                 ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
13896                 ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
13897                 if (pf->vf[vsi->vf_id].spoofchk) {
13898                         ctxt.info.valid_sections |=
13899                                 cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
13900                         ctxt.info.sec_flags |=
13901                                 (I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
13902                                  I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
13903                 }
13904                 /* Setup the VSI tx/rx queue map for TC0 only for now */
13905                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13906                 break;
13907
13908         case I40E_VSI_IWARP:
13909                 /* send down message to iWARP */
13910                 break;
13911
13912         default:
13913                 return -ENODEV;
13914         }
13915
13916         if (vsi->type != I40E_VSI_MAIN) {
13917                 ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
13918                 if (ret) {
13919                         dev_info(&vsi->back->pdev->dev,
13920                                  "add vsi failed, err %s aq_err %s\n",
13921                                  i40e_stat_str(&pf->hw, ret),
13922                                  i40e_aq_str(&pf->hw,
13923                                              pf->hw.aq.asq_last_status));
13924                         ret = -ENOENT;
13925                         goto err;
13926                 }
13927                 vsi->info = ctxt.info;
13928                 vsi->info.valid_sections = 0;
13929                 vsi->seid = ctxt.seid;
13930                 vsi->id = ctxt.vsi_number;
13931         }
13932
13933         vsi->active_filters = 0;
13934         clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
13935         spin_lock_bh(&vsi->mac_filter_hash_lock);
13936         /* If macvlan filters already exist, force them to get loaded */
13937         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
13938                 f->state = I40E_FILTER_NEW;
13939                 f_count++;
13940         }
13941         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13942
13943         if (f_count) {
13944                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
13945                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
13946         }
13947
13948         /* Update VSI BW information */
13949         ret = i40e_vsi_get_bw_info(vsi);
13950         if (ret) {
13951                 dev_info(&pf->pdev->dev,
13952                          "couldn't get vsi bw info, err %s aq_err %s\n",
13953                          i40e_stat_str(&pf->hw, ret),
13954                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13955                 /* VSI is already added so not tearing that up */
13956                 ret = 0;
13957         }
13958
13959 err:
13960         return ret;
13961 }
13962
13963 /**
13964  * i40e_vsi_release - Delete a VSI and free its resources
13965  * @vsi: the VSI being removed
13966  *
13967  * Returns 0 on success or < 0 on error
13968  **/
13969 int i40e_vsi_release(struct i40e_vsi *vsi)
13970 {
13971         struct i40e_mac_filter *f;
13972         struct hlist_node *h;
13973         struct i40e_veb *veb = NULL;
13974         struct i40e_pf *pf;
13975         u16 uplink_seid;
13976         int i, n, bkt;
13977
13978         pf = vsi->back;
13979
13980         /* release of a VEB-owner or last VSI is not allowed */
13981         if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
13982                 dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
13983                          vsi->seid, vsi->uplink_seid);
13984                 return -ENODEV;
13985         }
13986         if (vsi == pf->vsi[pf->lan_vsi] &&
13987             !test_bit(__I40E_DOWN, pf->state)) {
13988                 dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
13989                 return -ENODEV;
13990         }
13991         set_bit(__I40E_VSI_RELEASING, vsi->state);
13992         uplink_seid = vsi->uplink_seid;
13993         if (vsi->type != I40E_VSI_SRIOV) {
13994                 if (vsi->netdev_registered) {
13995                         vsi->netdev_registered = false;
13996                         if (vsi->netdev) {
13997                                 /* results in a call to i40e_close() */
13998                                 unregister_netdev(vsi->netdev);
13999                         }
14000                 } else {
14001                         i40e_vsi_close(vsi);
14002                 }
14003                 i40e_vsi_disable_irq(vsi);
14004         }
14005
14006         spin_lock_bh(&vsi->mac_filter_hash_lock);
14007
14008         /* clear the sync flag on all filters */
14009         if (vsi->netdev) {
14010                 __dev_uc_unsync(vsi->netdev, NULL);
14011                 __dev_mc_unsync(vsi->netdev, NULL);
14012         }
14013
14014         /* make sure any remaining filters are marked for deletion */
14015         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
14016                 __i40e_del_filter(vsi, f);
14017
14018         spin_unlock_bh(&vsi->mac_filter_hash_lock);
14019
14020         i40e_sync_vsi_filters(vsi);
14021
14022         i40e_vsi_delete(vsi);
14023         i40e_vsi_free_q_vectors(vsi);
14024         if (vsi->netdev) {
14025                 free_netdev(vsi->netdev);
14026                 vsi->netdev = NULL;
14027         }
14028         i40e_vsi_clear_rings(vsi);
14029         i40e_vsi_clear(vsi);
14030
14031         /* If this was the last thing on the VEB, except for the
14032          * controlling VSI, remove the VEB, which puts the controlling
14033          * VSI onto the next level down in the switch.
14034          *
14035          * Well, okay, there's one more exception here: don't remove
14036          * the orphan VEBs yet.  We'll wait for an explicit remove request
14037          * from up the network stack.
14038          */
14039         for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
14040                 if (pf->vsi[i] &&
14041                     pf->vsi[i]->uplink_seid == uplink_seid &&
14042                     (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14043                         n++;      /* count the VSIs */
14044                 }
14045         }
14046         for (i = 0; i < I40E_MAX_VEB; i++) {
14047                 if (!pf->veb[i])
14048                         continue;
14049                 if (pf->veb[i]->uplink_seid == uplink_seid)
14050                         n++;     /* count the VEBs */
14051                 if (pf->veb[i]->seid == uplink_seid)
14052                         veb = pf->veb[i];
14053         }
14054         if (n == 0 && veb && veb->uplink_seid != 0)
14055                 i40e_veb_release(veb);
14056
14057         return 0;
14058 }
14059
14060 /**
14061  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
14062  * @vsi: ptr to the VSI
14063  *
14064  * This should only be called after i40e_vsi_mem_alloc() which allocates the
14065  * corresponding SW VSI structure and initializes num_queue_pairs for the
14066  * newly allocated VSI.
14067  *
14068  * Returns 0 on success or negative on failure
14069  **/
14070 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
14071 {
14072         int ret = -ENOENT;
14073         struct i40e_pf *pf = vsi->back;
14074
14075         if (vsi->q_vectors[0]) {
14076                 dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
14077                          vsi->seid);
14078                 return -EEXIST;
14079         }
14080
14081         if (vsi->base_vector) {
14082                 dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
14083                          vsi->seid, vsi->base_vector);
14084                 return -EEXIST;
14085         }
14086
14087         ret = i40e_vsi_alloc_q_vectors(vsi);
14088         if (ret) {
14089                 dev_info(&pf->pdev->dev,
14090                          "failed to allocate %d q_vector for VSI %d, ret=%d\n",
14091                          vsi->num_q_vectors, vsi->seid, ret);
14092                 vsi->num_q_vectors = 0;
14093                 goto vector_setup_out;
14094         }
14095
14096         /* In Legacy mode, we do not have to get any other vector since we
14097          * piggyback on the misc/ICR0 for queue interrupts.
14098         */
14099         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
14100                 return ret;
14101         if (vsi->num_q_vectors)
14102                 vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
14103                                                  vsi->num_q_vectors, vsi->idx);
14104         if (vsi->base_vector < 0) {
14105                 dev_info(&pf->pdev->dev,
14106                          "failed to get tracking for %d vectors for VSI %d, err=%d\n",
14107                          vsi->num_q_vectors, vsi->seid, vsi->base_vector);
14108                 i40e_vsi_free_q_vectors(vsi);
14109                 ret = -ENOENT;
14110                 goto vector_setup_out;
14111         }
14112
14113 vector_setup_out:
14114         return ret;
14115 }
14116
14117 /**
14118  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
14119  * @vsi: pointer to the vsi.
14120  *
14121  * This re-allocates a vsi's queue resources.
14122  *
14123  * Returns pointer to the successfully allocated and configured VSI sw struct
14124  * on success, otherwise returns NULL on failure.
14125  **/
14126 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
14127 {
14128         u16 alloc_queue_pairs;
14129         struct i40e_pf *pf;
14130         u8 enabled_tc;
14131         int ret;
14132
14133         if (!vsi)
14134                 return NULL;
14135
14136         pf = vsi->back;
14137
14138         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
14139         i40e_vsi_clear_rings(vsi);
14140
14141         i40e_vsi_free_arrays(vsi, false);
14142         i40e_set_num_rings_in_vsi(vsi);
14143         ret = i40e_vsi_alloc_arrays(vsi, false);
14144         if (ret)
14145                 goto err_vsi;
14146
14147         alloc_queue_pairs = vsi->alloc_queue_pairs *
14148                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14149
14150         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14151         if (ret < 0) {
14152                 dev_info(&pf->pdev->dev,
14153                          "failed to get tracking for %d queues for VSI %d err %d\n",
14154                          alloc_queue_pairs, vsi->seid, ret);
14155                 goto err_vsi;
14156         }
14157         vsi->base_queue = ret;
14158
14159         /* Update the FW view of the VSI. Force a reset of TC and queue
14160          * layout configurations.
14161          */
14162         enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14163         pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14164         pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14165         i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14166         if (vsi->type == I40E_VSI_MAIN)
14167                 i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
14168
14169         /* assign it some queues */
14170         ret = i40e_alloc_rings(vsi);
14171         if (ret)
14172                 goto err_rings;
14173
14174         /* map all of the rings to the q_vectors */
14175         i40e_vsi_map_rings_to_vectors(vsi);
14176         return vsi;
14177
14178 err_rings:
14179         i40e_vsi_free_q_vectors(vsi);
14180         if (vsi->netdev_registered) {
14181                 vsi->netdev_registered = false;
14182                 unregister_netdev(vsi->netdev);
14183                 free_netdev(vsi->netdev);
14184                 vsi->netdev = NULL;
14185         }
14186         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14187 err_vsi:
14188         i40e_vsi_clear(vsi);
14189         return NULL;
14190 }
14191
14192 /**
14193  * i40e_vsi_setup - Set up a VSI by a given type
14194  * @pf: board private structure
14195  * @type: VSI type
14196  * @uplink_seid: the switch element to link to
14197  * @param1: usage depends upon VSI type. For VF types, indicates VF id
14198  *
14199  * This allocates the sw VSI structure and its queue resources, then add a VSI
14200  * to the identified VEB.
14201  *
14202  * Returns pointer to the successfully allocated and configure VSI sw struct on
14203  * success, otherwise returns NULL on failure.
14204  **/
14205 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
14206                                 u16 uplink_seid, u32 param1)
14207 {
14208         struct i40e_vsi *vsi = NULL;
14209         struct i40e_veb *veb = NULL;
14210         u16 alloc_queue_pairs;
14211         int ret, i;
14212         int v_idx;
14213
14214         /* The requested uplink_seid must be either
14215          *     - the PF's port seid
14216          *              no VEB is needed because this is the PF
14217          *              or this is a Flow Director special case VSI
14218          *     - seid of an existing VEB
14219          *     - seid of a VSI that owns an existing VEB
14220          *     - seid of a VSI that doesn't own a VEB
14221          *              a new VEB is created and the VSI becomes the owner
14222          *     - seid of the PF VSI, which is what creates the first VEB
14223          *              this is a special case of the previous
14224          *
14225          * Find which uplink_seid we were given and create a new VEB if needed
14226          */
14227         for (i = 0; i < I40E_MAX_VEB; i++) {
14228                 if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14229                         veb = pf->veb[i];
14230                         break;
14231                 }
14232         }
14233
14234         if (!veb && uplink_seid != pf->mac_seid) {
14235
14236                 for (i = 0; i < pf->num_alloc_vsi; i++) {
14237                         if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14238                                 vsi = pf->vsi[i];
14239                                 break;
14240                         }
14241                 }
14242                 if (!vsi) {
14243                         dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14244                                  uplink_seid);
14245                         return NULL;
14246                 }
14247
14248                 if (vsi->uplink_seid == pf->mac_seid)
14249                         veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14250                                              vsi->tc_config.enabled_tc);
14251                 else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14252                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14253                                              vsi->tc_config.enabled_tc);
14254                 if (veb) {
14255                         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14256                                 dev_info(&vsi->back->pdev->dev,
14257                                          "New VSI creation error, uplink seid of LAN VSI expected.\n");
14258                                 return NULL;
14259                         }
14260                         /* We come up by default in VEPA mode if SRIOV is not
14261                          * already enabled, in which case we can't force VEPA
14262                          * mode.
14263                          */
14264                         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14265                                 veb->bridge_mode = BRIDGE_MODE_VEPA;
14266                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14267                         }
14268                         i40e_config_bridge_mode(veb);
14269                 }
14270                 for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14271                         if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14272                                 veb = pf->veb[i];
14273                 }
14274                 if (!veb) {
14275                         dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14276                         return NULL;
14277                 }
14278
14279                 vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14280                 uplink_seid = veb->seid;
14281         }
14282
14283         /* get vsi sw struct */
14284         v_idx = i40e_vsi_mem_alloc(pf, type);
14285         if (v_idx < 0)
14286                 goto err_alloc;
14287         vsi = pf->vsi[v_idx];
14288         if (!vsi)
14289                 goto err_alloc;
14290         vsi->type = type;
14291         vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14292
14293         if (type == I40E_VSI_MAIN)
14294                 pf->lan_vsi = v_idx;
14295         else if (type == I40E_VSI_SRIOV)
14296                 vsi->vf_id = param1;
14297         /* assign it some queues */
14298         alloc_queue_pairs = vsi->alloc_queue_pairs *
14299                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14300
14301         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14302         if (ret < 0) {
14303                 dev_info(&pf->pdev->dev,
14304                          "failed to get tracking for %d queues for VSI %d err=%d\n",
14305                          alloc_queue_pairs, vsi->seid, ret);
14306                 goto err_vsi;
14307         }
14308         vsi->base_queue = ret;
14309
14310         /* get a VSI from the hardware */
14311         vsi->uplink_seid = uplink_seid;
14312         ret = i40e_add_vsi(vsi);
14313         if (ret)
14314                 goto err_vsi;
14315
14316         switch (vsi->type) {
14317         /* setup the netdev if needed */
14318         case I40E_VSI_MAIN:
14319         case I40E_VSI_VMDQ2:
14320                 ret = i40e_config_netdev(vsi);
14321                 if (ret)
14322                         goto err_netdev;
14323                 ret = i40e_netif_set_realnum_tx_rx_queues(vsi);
14324                 if (ret)
14325                         goto err_netdev;
14326                 ret = register_netdev(vsi->netdev);
14327                 if (ret)
14328                         goto err_netdev;
14329                 vsi->netdev_registered = true;
14330                 netif_carrier_off(vsi->netdev);
14331 #ifdef CONFIG_I40E_DCB
14332                 /* Setup DCB netlink interface */
14333                 i40e_dcbnl_setup(vsi);
14334 #endif /* CONFIG_I40E_DCB */
14335                 fallthrough;
14336         case I40E_VSI_FDIR:
14337                 /* set up vectors and rings if needed */
14338                 ret = i40e_vsi_setup_vectors(vsi);
14339                 if (ret)
14340                         goto err_msix;
14341
14342                 ret = i40e_alloc_rings(vsi);
14343                 if (ret)
14344                         goto err_rings;
14345
14346                 /* map all of the rings to the q_vectors */
14347                 i40e_vsi_map_rings_to_vectors(vsi);
14348
14349                 i40e_vsi_reset_stats(vsi);
14350                 break;
14351         default:
14352                 /* no netdev or rings for the other VSI types */
14353                 break;
14354         }
14355
14356         if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14357             (vsi->type == I40E_VSI_VMDQ2)) {
14358                 ret = i40e_vsi_config_rss(vsi);
14359         }
14360         return vsi;
14361
14362 err_rings:
14363         i40e_vsi_free_q_vectors(vsi);
14364 err_msix:
14365         if (vsi->netdev_registered) {
14366                 vsi->netdev_registered = false;
14367                 unregister_netdev(vsi->netdev);
14368                 free_netdev(vsi->netdev);
14369                 vsi->netdev = NULL;
14370         }
14371 err_netdev:
14372         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14373 err_vsi:
14374         i40e_vsi_clear(vsi);
14375 err_alloc:
14376         return NULL;
14377 }
14378
14379 /**
14380  * i40e_veb_get_bw_info - Query VEB BW information
14381  * @veb: the veb to query
14382  *
14383  * Query the Tx scheduler BW configuration data for given VEB
14384  **/
14385 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14386 {
14387         struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14388         struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14389         struct i40e_pf *pf = veb->pf;
14390         struct i40e_hw *hw = &pf->hw;
14391         u32 tc_bw_max;
14392         int ret = 0;
14393         int i;
14394
14395         ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14396                                                   &bw_data, NULL);
14397         if (ret) {
14398                 dev_info(&pf->pdev->dev,
14399                          "query veb bw config failed, err %s aq_err %s\n",
14400                          i40e_stat_str(&pf->hw, ret),
14401                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14402                 goto out;
14403         }
14404
14405         ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14406                                                    &ets_data, NULL);
14407         if (ret) {
14408                 dev_info(&pf->pdev->dev,
14409                          "query veb bw ets config failed, err %s aq_err %s\n",
14410                          i40e_stat_str(&pf->hw, ret),
14411                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14412                 goto out;
14413         }
14414
14415         veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14416         veb->bw_max_quanta = ets_data.tc_bw_max;
14417         veb->is_abs_credits = bw_data.absolute_credits_enable;
14418         veb->enabled_tc = ets_data.tc_valid_bits;
14419         tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14420                     (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14421         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14422                 veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14423                 veb->bw_tc_limit_credits[i] =
14424                                         le16_to_cpu(bw_data.tc_bw_limits[i]);
14425                 veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14426         }
14427
14428 out:
14429         return ret;
14430 }
14431
14432 /**
14433  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14434  * @pf: board private structure
14435  *
14436  * On error: returns error code (negative)
14437  * On success: returns vsi index in PF (positive)
14438  **/
14439 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14440 {
14441         int ret = -ENOENT;
14442         struct i40e_veb *veb;
14443         int i;
14444
14445         /* Need to protect the allocation of switch elements at the PF level */
14446         mutex_lock(&pf->switch_mutex);
14447
14448         /* VEB list may be fragmented if VEB creation/destruction has
14449          * been happening.  We can afford to do a quick scan to look
14450          * for any free slots in the list.
14451          *
14452          * find next empty veb slot, looping back around if necessary
14453          */
14454         i = 0;
14455         while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14456                 i++;
14457         if (i >= I40E_MAX_VEB) {
14458                 ret = -ENOMEM;
14459                 goto err_alloc_veb;  /* out of VEB slots! */
14460         }
14461
14462         veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14463         if (!veb) {
14464                 ret = -ENOMEM;
14465                 goto err_alloc_veb;
14466         }
14467         veb->pf = pf;
14468         veb->idx = i;
14469         veb->enabled_tc = 1;
14470
14471         pf->veb[i] = veb;
14472         ret = i;
14473 err_alloc_veb:
14474         mutex_unlock(&pf->switch_mutex);
14475         return ret;
14476 }
14477
14478 /**
14479  * i40e_switch_branch_release - Delete a branch of the switch tree
14480  * @branch: where to start deleting
14481  *
14482  * This uses recursion to find the tips of the branch to be
14483  * removed, deleting until we get back to and can delete this VEB.
14484  **/
14485 static void i40e_switch_branch_release(struct i40e_veb *branch)
14486 {
14487         struct i40e_pf *pf = branch->pf;
14488         u16 branch_seid = branch->seid;
14489         u16 veb_idx = branch->idx;
14490         int i;
14491
14492         /* release any VEBs on this VEB - RECURSION */
14493         for (i = 0; i < I40E_MAX_VEB; i++) {
14494                 if (!pf->veb[i])
14495                         continue;
14496                 if (pf->veb[i]->uplink_seid == branch->seid)
14497                         i40e_switch_branch_release(pf->veb[i]);
14498         }
14499
14500         /* Release the VSIs on this VEB, but not the owner VSI.
14501          *
14502          * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14503          *       the VEB itself, so don't use (*branch) after this loop.
14504          */
14505         for (i = 0; i < pf->num_alloc_vsi; i++) {
14506                 if (!pf->vsi[i])
14507                         continue;
14508                 if (pf->vsi[i]->uplink_seid == branch_seid &&
14509                    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14510                         i40e_vsi_release(pf->vsi[i]);
14511                 }
14512         }
14513
14514         /* There's one corner case where the VEB might not have been
14515          * removed, so double check it here and remove it if needed.
14516          * This case happens if the veb was created from the debugfs
14517          * commands and no VSIs were added to it.
14518          */
14519         if (pf->veb[veb_idx])
14520                 i40e_veb_release(pf->veb[veb_idx]);
14521 }
14522
14523 /**
14524  * i40e_veb_clear - remove veb struct
14525  * @veb: the veb to remove
14526  **/
14527 static void i40e_veb_clear(struct i40e_veb *veb)
14528 {
14529         if (!veb)
14530                 return;
14531
14532         if (veb->pf) {
14533                 struct i40e_pf *pf = veb->pf;
14534
14535                 mutex_lock(&pf->switch_mutex);
14536                 if (pf->veb[veb->idx] == veb)
14537                         pf->veb[veb->idx] = NULL;
14538                 mutex_unlock(&pf->switch_mutex);
14539         }
14540
14541         kfree(veb);
14542 }
14543
14544 /**
14545  * i40e_veb_release - Delete a VEB and free its resources
14546  * @veb: the VEB being removed
14547  **/
14548 void i40e_veb_release(struct i40e_veb *veb)
14549 {
14550         struct i40e_vsi *vsi = NULL;
14551         struct i40e_pf *pf;
14552         int i, n = 0;
14553
14554         pf = veb->pf;
14555
14556         /* find the remaining VSI and check for extras */
14557         for (i = 0; i < pf->num_alloc_vsi; i++) {
14558                 if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14559                         n++;
14560                         vsi = pf->vsi[i];
14561                 }
14562         }
14563         if (n != 1) {
14564                 dev_info(&pf->pdev->dev,
14565                          "can't remove VEB %d with %d VSIs left\n",
14566                          veb->seid, n);
14567                 return;
14568         }
14569
14570         /* move the remaining VSI to uplink veb */
14571         vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14572         if (veb->uplink_seid) {
14573                 vsi->uplink_seid = veb->uplink_seid;
14574                 if (veb->uplink_seid == pf->mac_seid)
14575                         vsi->veb_idx = I40E_NO_VEB;
14576                 else
14577                         vsi->veb_idx = veb->veb_idx;
14578         } else {
14579                 /* floating VEB */
14580                 vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14581                 vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14582         }
14583
14584         i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14585         i40e_veb_clear(veb);
14586 }
14587
14588 /**
14589  * i40e_add_veb - create the VEB in the switch
14590  * @veb: the VEB to be instantiated
14591  * @vsi: the controlling VSI
14592  **/
14593 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14594 {
14595         struct i40e_pf *pf = veb->pf;
14596         bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14597         int ret;
14598
14599         ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14600                               veb->enabled_tc, false,
14601                               &veb->seid, enable_stats, NULL);
14602
14603         /* get a VEB from the hardware */
14604         if (ret) {
14605                 dev_info(&pf->pdev->dev,
14606                          "couldn't add VEB, err %s aq_err %s\n",
14607                          i40e_stat_str(&pf->hw, ret),
14608                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14609                 return -EPERM;
14610         }
14611
14612         /* get statistics counter */
14613         ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14614                                          &veb->stats_idx, NULL, NULL, NULL);
14615         if (ret) {
14616                 dev_info(&pf->pdev->dev,
14617                          "couldn't get VEB statistics idx, err %s aq_err %s\n",
14618                          i40e_stat_str(&pf->hw, ret),
14619                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14620                 return -EPERM;
14621         }
14622         ret = i40e_veb_get_bw_info(veb);
14623         if (ret) {
14624                 dev_info(&pf->pdev->dev,
14625                          "couldn't get VEB bw info, err %s aq_err %s\n",
14626                          i40e_stat_str(&pf->hw, ret),
14627                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14628                 i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14629                 return -ENOENT;
14630         }
14631
14632         vsi->uplink_seid = veb->seid;
14633         vsi->veb_idx = veb->idx;
14634         vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14635
14636         return 0;
14637 }
14638
14639 /**
14640  * i40e_veb_setup - Set up a VEB
14641  * @pf: board private structure
14642  * @flags: VEB setup flags
14643  * @uplink_seid: the switch element to link to
14644  * @vsi_seid: the initial VSI seid
14645  * @enabled_tc: Enabled TC bit-map
14646  *
14647  * This allocates the sw VEB structure and links it into the switch
14648  * It is possible and legal for this to be a duplicate of an already
14649  * existing VEB.  It is also possible for both uplink and vsi seids
14650  * to be zero, in order to create a floating VEB.
14651  *
14652  * Returns pointer to the successfully allocated VEB sw struct on
14653  * success, otherwise returns NULL on failure.
14654  **/
14655 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14656                                 u16 uplink_seid, u16 vsi_seid,
14657                                 u8 enabled_tc)
14658 {
14659         struct i40e_veb *veb, *uplink_veb = NULL;
14660         int vsi_idx, veb_idx;
14661         int ret;
14662
14663         /* if one seid is 0, the other must be 0 to create a floating relay */
14664         if ((uplink_seid == 0 || vsi_seid == 0) &&
14665             (uplink_seid + vsi_seid != 0)) {
14666                 dev_info(&pf->pdev->dev,
14667                          "one, not both seid's are 0: uplink=%d vsi=%d\n",
14668                          uplink_seid, vsi_seid);
14669                 return NULL;
14670         }
14671
14672         /* make sure there is such a vsi and uplink */
14673         for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14674                 if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14675                         break;
14676         if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14677                 dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14678                          vsi_seid);
14679                 return NULL;
14680         }
14681
14682         if (uplink_seid && uplink_seid != pf->mac_seid) {
14683                 for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14684                         if (pf->veb[veb_idx] &&
14685                             pf->veb[veb_idx]->seid == uplink_seid) {
14686                                 uplink_veb = pf->veb[veb_idx];
14687                                 break;
14688                         }
14689                 }
14690                 if (!uplink_veb) {
14691                         dev_info(&pf->pdev->dev,
14692                                  "uplink seid %d not found\n", uplink_seid);
14693                         return NULL;
14694                 }
14695         }
14696
14697         /* get veb sw struct */
14698         veb_idx = i40e_veb_mem_alloc(pf);
14699         if (veb_idx < 0)
14700                 goto err_alloc;
14701         veb = pf->veb[veb_idx];
14702         veb->flags = flags;
14703         veb->uplink_seid = uplink_seid;
14704         veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14705         veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14706
14707         /* create the VEB in the switch */
14708         ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14709         if (ret)
14710                 goto err_veb;
14711         if (vsi_idx == pf->lan_vsi)
14712                 pf->lan_veb = veb->idx;
14713
14714         return veb;
14715
14716 err_veb:
14717         i40e_veb_clear(veb);
14718 err_alloc:
14719         return NULL;
14720 }
14721
14722 /**
14723  * i40e_setup_pf_switch_element - set PF vars based on switch type
14724  * @pf: board private structure
14725  * @ele: element we are building info from
14726  * @num_reported: total number of elements
14727  * @printconfig: should we print the contents
14728  *
14729  * helper function to assist in extracting a few useful SEID values.
14730  **/
14731 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14732                                 struct i40e_aqc_switch_config_element_resp *ele,
14733                                 u16 num_reported, bool printconfig)
14734 {
14735         u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14736         u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14737         u8 element_type = ele->element_type;
14738         u16 seid = le16_to_cpu(ele->seid);
14739
14740         if (printconfig)
14741                 dev_info(&pf->pdev->dev,
14742                          "type=%d seid=%d uplink=%d downlink=%d\n",
14743                          element_type, seid, uplink_seid, downlink_seid);
14744
14745         switch (element_type) {
14746         case I40E_SWITCH_ELEMENT_TYPE_MAC:
14747                 pf->mac_seid = seid;
14748                 break;
14749         case I40E_SWITCH_ELEMENT_TYPE_VEB:
14750                 /* Main VEB? */
14751                 if (uplink_seid != pf->mac_seid)
14752                         break;
14753                 if (pf->lan_veb >= I40E_MAX_VEB) {
14754                         int v;
14755
14756                         /* find existing or else empty VEB */
14757                         for (v = 0; v < I40E_MAX_VEB; v++) {
14758                                 if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14759                                         pf->lan_veb = v;
14760                                         break;
14761                                 }
14762                         }
14763                         if (pf->lan_veb >= I40E_MAX_VEB) {
14764                                 v = i40e_veb_mem_alloc(pf);
14765                                 if (v < 0)
14766                                         break;
14767                                 pf->lan_veb = v;
14768                         }
14769                 }
14770                 if (pf->lan_veb >= I40E_MAX_VEB)
14771                         break;
14772
14773                 pf->veb[pf->lan_veb]->seid = seid;
14774                 pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14775                 pf->veb[pf->lan_veb]->pf = pf;
14776                 pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14777                 break;
14778         case I40E_SWITCH_ELEMENT_TYPE_VSI:
14779                 if (num_reported != 1)
14780                         break;
14781                 /* This is immediately after a reset so we can assume this is
14782                  * the PF's VSI
14783                  */
14784                 pf->mac_seid = uplink_seid;
14785                 pf->pf_seid = downlink_seid;
14786                 pf->main_vsi_seid = seid;
14787                 if (printconfig)
14788                         dev_info(&pf->pdev->dev,
14789                                  "pf_seid=%d main_vsi_seid=%d\n",
14790                                  pf->pf_seid, pf->main_vsi_seid);
14791                 break;
14792         case I40E_SWITCH_ELEMENT_TYPE_PF:
14793         case I40E_SWITCH_ELEMENT_TYPE_VF:
14794         case I40E_SWITCH_ELEMENT_TYPE_EMP:
14795         case I40E_SWITCH_ELEMENT_TYPE_BMC:
14796         case I40E_SWITCH_ELEMENT_TYPE_PE:
14797         case I40E_SWITCH_ELEMENT_TYPE_PA:
14798                 /* ignore these for now */
14799                 break;
14800         default:
14801                 dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14802                          element_type, seid);
14803                 break;
14804         }
14805 }
14806
14807 /**
14808  * i40e_fetch_switch_configuration - Get switch config from firmware
14809  * @pf: board private structure
14810  * @printconfig: should we print the contents
14811  *
14812  * Get the current switch configuration from the device and
14813  * extract a few useful SEID values.
14814  **/
14815 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14816 {
14817         struct i40e_aqc_get_switch_config_resp *sw_config;
14818         u16 next_seid = 0;
14819         int ret = 0;
14820         u8 *aq_buf;
14821         int i;
14822
14823         aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14824         if (!aq_buf)
14825                 return -ENOMEM;
14826
14827         sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14828         do {
14829                 u16 num_reported, num_total;
14830
14831                 ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14832                                                 I40E_AQ_LARGE_BUF,
14833                                                 &next_seid, NULL);
14834                 if (ret) {
14835                         dev_info(&pf->pdev->dev,
14836                                  "get switch config failed err %s aq_err %s\n",
14837                                  i40e_stat_str(&pf->hw, ret),
14838                                  i40e_aq_str(&pf->hw,
14839                                              pf->hw.aq.asq_last_status));
14840                         kfree(aq_buf);
14841                         return -ENOENT;
14842                 }
14843
14844                 num_reported = le16_to_cpu(sw_config->header.num_reported);
14845                 num_total = le16_to_cpu(sw_config->header.num_total);
14846
14847                 if (printconfig)
14848                         dev_info(&pf->pdev->dev,
14849                                  "header: %d reported %d total\n",
14850                                  num_reported, num_total);
14851
14852                 for (i = 0; i < num_reported; i++) {
14853                         struct i40e_aqc_switch_config_element_resp *ele =
14854                                 &sw_config->element[i];
14855
14856                         i40e_setup_pf_switch_element(pf, ele, num_reported,
14857                                                      printconfig);
14858                 }
14859         } while (next_seid != 0);
14860
14861         kfree(aq_buf);
14862         return ret;
14863 }
14864
14865 /**
14866  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14867  * @pf: board private structure
14868  * @reinit: if the Main VSI needs to re-initialized.
14869  * @lock_acquired: indicates whether or not the lock has been acquired
14870  *
14871  * Returns 0 on success, negative value on failure
14872  **/
14873 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
14874 {
14875         u16 flags = 0;
14876         int ret;
14877
14878         /* find out what's out there already */
14879         ret = i40e_fetch_switch_configuration(pf, false);
14880         if (ret) {
14881                 dev_info(&pf->pdev->dev,
14882                          "couldn't fetch switch config, err %s aq_err %s\n",
14883                          i40e_stat_str(&pf->hw, ret),
14884                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14885                 return ret;
14886         }
14887         i40e_pf_reset_stats(pf);
14888
14889         /* set the switch config bit for the whole device to
14890          * support limited promisc or true promisc
14891          * when user requests promisc. The default is limited
14892          * promisc.
14893         */
14894
14895         if ((pf->hw.pf_id == 0) &&
14896             !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
14897                 flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14898                 pf->last_sw_conf_flags = flags;
14899         }
14900
14901         if (pf->hw.pf_id == 0) {
14902                 u16 valid_flags;
14903
14904                 valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14905                 ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
14906                                                 NULL);
14907                 if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
14908                         dev_info(&pf->pdev->dev,
14909                                  "couldn't set switch config bits, err %s aq_err %s\n",
14910                                  i40e_stat_str(&pf->hw, ret),
14911                                  i40e_aq_str(&pf->hw,
14912                                              pf->hw.aq.asq_last_status));
14913                         /* not a fatal problem, just keep going */
14914                 }
14915                 pf->last_sw_conf_valid_flags = valid_flags;
14916         }
14917
14918         /* first time setup */
14919         if (pf->lan_vsi == I40E_NO_VSI || reinit) {
14920                 struct i40e_vsi *vsi = NULL;
14921                 u16 uplink_seid;
14922
14923                 /* Set up the PF VSI associated with the PF's main VSI
14924                  * that is already in the HW switch
14925                  */
14926                 if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
14927                         uplink_seid = pf->veb[pf->lan_veb]->seid;
14928                 else
14929                         uplink_seid = pf->mac_seid;
14930                 if (pf->lan_vsi == I40E_NO_VSI)
14931                         vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
14932                 else if (reinit)
14933                         vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
14934                 if (!vsi) {
14935                         dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
14936                         i40e_cloud_filter_exit(pf);
14937                         i40e_fdir_teardown(pf);
14938                         return -EAGAIN;
14939                 }
14940         } else {
14941                 /* force a reset of TC and queue layout configurations */
14942                 u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14943
14944                 pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14945                 pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14946                 i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14947         }
14948         i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
14949
14950         i40e_fdir_sb_setup(pf);
14951
14952         /* Setup static PF queue filter control settings */
14953         ret = i40e_setup_pf_filter_control(pf);
14954         if (ret) {
14955                 dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
14956                          ret);
14957                 /* Failure here should not stop continuing other steps */
14958         }
14959
14960         /* enable RSS in the HW, even for only one queue, as the stack can use
14961          * the hash
14962          */
14963         if ((pf->flags & I40E_FLAG_RSS_ENABLED))
14964                 i40e_pf_config_rss(pf);
14965
14966         /* fill in link information and enable LSE reporting */
14967         i40e_link_event(pf);
14968
14969         /* Initialize user-specific link properties */
14970         pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
14971                                   I40E_AQ_AN_COMPLETED) ? true : false);
14972
14973         i40e_ptp_init(pf);
14974
14975         if (!lock_acquired)
14976                 rtnl_lock();
14977
14978         /* repopulate tunnel port filters */
14979         udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
14980
14981         if (!lock_acquired)
14982                 rtnl_unlock();
14983
14984         return ret;
14985 }
14986
14987 /**
14988  * i40e_determine_queue_usage - Work out queue distribution
14989  * @pf: board private structure
14990  **/
14991 static void i40e_determine_queue_usage(struct i40e_pf *pf)
14992 {
14993         int queues_left;
14994         int q_max;
14995
14996         pf->num_lan_qps = 0;
14997
14998         /* Find the max queues to be put into basic use.  We'll always be
14999          * using TC0, whether or not DCB is running, and TC0 will get the
15000          * big RSS set.
15001          */
15002         queues_left = pf->hw.func_caps.num_tx_qp;
15003
15004         if ((queues_left == 1) ||
15005             !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
15006                 /* one qp for PF, no queues for anything else */
15007                 queues_left = 0;
15008                 pf->alloc_rss_size = pf->num_lan_qps = 1;
15009
15010                 /* make sure all the fancies are disabled */
15011                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
15012                                I40E_FLAG_IWARP_ENABLED  |
15013                                I40E_FLAG_FD_SB_ENABLED  |
15014                                I40E_FLAG_FD_ATR_ENABLED |
15015                                I40E_FLAG_DCB_CAPABLE    |
15016                                I40E_FLAG_DCB_ENABLED    |
15017                                I40E_FLAG_SRIOV_ENABLED  |
15018                                I40E_FLAG_VMDQ_ENABLED);
15019                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15020         } else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
15021                                   I40E_FLAG_FD_SB_ENABLED |
15022                                   I40E_FLAG_FD_ATR_ENABLED |
15023                                   I40E_FLAG_DCB_CAPABLE))) {
15024                 /* one qp for PF */
15025                 pf->alloc_rss_size = pf->num_lan_qps = 1;
15026                 queues_left -= pf->num_lan_qps;
15027
15028                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
15029                                I40E_FLAG_IWARP_ENABLED  |
15030                                I40E_FLAG_FD_SB_ENABLED  |
15031                                I40E_FLAG_FD_ATR_ENABLED |
15032                                I40E_FLAG_DCB_ENABLED    |
15033                                I40E_FLAG_VMDQ_ENABLED);
15034                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15035         } else {
15036                 /* Not enough queues for all TCs */
15037                 if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
15038                     (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
15039                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
15040                                         I40E_FLAG_DCB_ENABLED);
15041                         dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
15042                 }
15043
15044                 /* limit lan qps to the smaller of qps, cpus or msix */
15045                 q_max = max_t(int, pf->rss_size_max, num_online_cpus());
15046                 q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
15047                 q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
15048                 pf->num_lan_qps = q_max;
15049
15050                 queues_left -= pf->num_lan_qps;
15051         }
15052
15053         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15054                 if (queues_left > 1) {
15055                         queues_left -= 1; /* save 1 queue for FD */
15056                 } else {
15057                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
15058                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
15059                         dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
15060                 }
15061         }
15062
15063         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15064             pf->num_vf_qps && pf->num_req_vfs && queues_left) {
15065                 pf->num_req_vfs = min_t(int, pf->num_req_vfs,
15066                                         (queues_left / pf->num_vf_qps));
15067                 queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
15068         }
15069
15070         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
15071             pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
15072                 pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
15073                                           (queues_left / pf->num_vmdq_qps));
15074                 queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
15075         }
15076
15077         pf->queues_left = queues_left;
15078         dev_dbg(&pf->pdev->dev,
15079                 "qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
15080                 pf->hw.func_caps.num_tx_qp,
15081                 !!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
15082                 pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
15083                 pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
15084                 queues_left);
15085 }
15086
15087 /**
15088  * i40e_setup_pf_filter_control - Setup PF static filter control
15089  * @pf: PF to be setup
15090  *
15091  * i40e_setup_pf_filter_control sets up a PF's initial filter control
15092  * settings. If PE/FCoE are enabled then it will also set the per PF
15093  * based filter sizes required for them. It also enables Flow director,
15094  * ethertype and macvlan type filter settings for the pf.
15095  *
15096  * Returns 0 on success, negative on failure
15097  **/
15098 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
15099 {
15100         struct i40e_filter_control_settings *settings = &pf->filter_settings;
15101
15102         settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
15103
15104         /* Flow Director is enabled */
15105         if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
15106                 settings->enable_fdir = true;
15107
15108         /* Ethtype and MACVLAN filters enabled for PF */
15109         settings->enable_ethtype = true;
15110         settings->enable_macvlan = true;
15111
15112         if (i40e_set_filter_control(&pf->hw, settings))
15113                 return -ENOENT;
15114
15115         return 0;
15116 }
15117
15118 #define INFO_STRING_LEN 255
15119 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
15120 static void i40e_print_features(struct i40e_pf *pf)
15121 {
15122         struct i40e_hw *hw = &pf->hw;
15123         char *buf;
15124         int i;
15125
15126         buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
15127         if (!buf)
15128                 return;
15129
15130         i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
15131 #ifdef CONFIG_PCI_IOV
15132         i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
15133 #endif
15134         i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
15135                       pf->hw.func_caps.num_vsis,
15136                       pf->vsi[pf->lan_vsi]->num_queue_pairs);
15137         if (pf->flags & I40E_FLAG_RSS_ENABLED)
15138                 i += scnprintf(&buf[i], REMAIN(i), " RSS");
15139         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
15140                 i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
15141         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
15142                 i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
15143                 i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
15144         }
15145         if (pf->flags & I40E_FLAG_DCB_CAPABLE)
15146                 i += scnprintf(&buf[i], REMAIN(i), " DCB");
15147         i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
15148         i += scnprintf(&buf[i], REMAIN(i), " Geneve");
15149         if (pf->flags & I40E_FLAG_PTP)
15150                 i += scnprintf(&buf[i], REMAIN(i), " PTP");
15151         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
15152                 i += scnprintf(&buf[i], REMAIN(i), " VEB");
15153         else
15154                 i += scnprintf(&buf[i], REMAIN(i), " VEPA");
15155
15156         dev_info(&pf->pdev->dev, "%s\n", buf);
15157         kfree(buf);
15158         WARN_ON(i > INFO_STRING_LEN);
15159 }
15160
15161 /**
15162  * i40e_get_platform_mac_addr - get platform-specific MAC address
15163  * @pdev: PCI device information struct
15164  * @pf: board private structure
15165  *
15166  * Look up the MAC address for the device. First we'll try
15167  * eth_platform_get_mac_address, which will check Open Firmware, or arch
15168  * specific fallback. Otherwise, we'll default to the stored value in
15169  * firmware.
15170  **/
15171 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
15172 {
15173         if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
15174                 i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
15175 }
15176
15177 /**
15178  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
15179  * @fec_cfg: FEC option to set in flags
15180  * @flags: ptr to flags in which we set FEC option
15181  **/
15182 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
15183 {
15184         if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
15185                 *flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
15186         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
15187             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
15188                 *flags |= I40E_FLAG_RS_FEC;
15189                 *flags &= ~I40E_FLAG_BASE_R_FEC;
15190         }
15191         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
15192             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
15193                 *flags |= I40E_FLAG_BASE_R_FEC;
15194                 *flags &= ~I40E_FLAG_RS_FEC;
15195         }
15196         if (fec_cfg == 0)
15197                 *flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
15198 }
15199
15200 /**
15201  * i40e_check_recovery_mode - check if we are running transition firmware
15202  * @pf: board private structure
15203  *
15204  * Check registers indicating the firmware runs in recovery mode. Sets the
15205  * appropriate driver state.
15206  *
15207  * Returns true if the recovery mode was detected, false otherwise
15208  **/
15209 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
15210 {
15211         u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
15212
15213         if (val & I40E_GL_FWSTS_FWS1B_MASK) {
15214                 dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
15215                 dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
15216                 set_bit(__I40E_RECOVERY_MODE, pf->state);
15217
15218                 return true;
15219         }
15220         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15221                 dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15222
15223         return false;
15224 }
15225
15226 /**
15227  * i40e_pf_loop_reset - perform reset in a loop.
15228  * @pf: board private structure
15229  *
15230  * This function is useful when a NIC is about to enter recovery mode.
15231  * When a NIC's internal data structures are corrupted the NIC's
15232  * firmware is going to enter recovery mode.
15233  * Right after a POR it takes about 7 minutes for firmware to enter
15234  * recovery mode. Until that time a NIC is in some kind of intermediate
15235  * state. After that time period the NIC almost surely enters
15236  * recovery mode. The only way for a driver to detect intermediate
15237  * state is to issue a series of pf-resets and check a return value.
15238  * If a PF reset returns success then the firmware could be in recovery
15239  * mode so the caller of this code needs to check for recovery mode
15240  * if this function returns success. There is a little chance that
15241  * firmware will hang in intermediate state forever.
15242  * Since waiting 7 minutes is quite a lot of time this function waits
15243  * 10 seconds and then gives up by returning an error.
15244  *
15245  * Return 0 on success, negative on failure.
15246  **/
15247 static i40e_status i40e_pf_loop_reset(struct i40e_pf *pf)
15248 {
15249         /* wait max 10 seconds for PF reset to succeed */
15250         const unsigned long time_end = jiffies + 10 * HZ;
15251
15252         struct i40e_hw *hw = &pf->hw;
15253         i40e_status ret;
15254
15255         ret = i40e_pf_reset(hw);
15256         while (ret != I40E_SUCCESS && time_before(jiffies, time_end)) {
15257                 usleep_range(10000, 20000);
15258                 ret = i40e_pf_reset(hw);
15259         }
15260
15261         if (ret == I40E_SUCCESS)
15262                 pf->pfr_count++;
15263         else
15264                 dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15265
15266         return ret;
15267 }
15268
15269 /**
15270  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15271  * @pf: board private structure
15272  *
15273  * Check FW registers to determine if FW issued unexpected EMP Reset.
15274  * Every time when unexpected EMP Reset occurs the FW increments
15275  * a counter of unexpected EMP Resets. When the counter reaches 10
15276  * the FW should enter the Recovery mode
15277  *
15278  * Returns true if FW issued unexpected EMP Reset
15279  **/
15280 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15281 {
15282         const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15283                            I40E_GL_FWSTS_FWS1B_MASK;
15284         return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15285                (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15286 }
15287
15288 /**
15289  * i40e_handle_resets - handle EMP resets and PF resets
15290  * @pf: board private structure
15291  *
15292  * Handle both EMP resets and PF resets and conclude whether there are
15293  * any issues regarding these resets. If there are any issues then
15294  * generate log entry.
15295  *
15296  * Return 0 if NIC is healthy or negative value when there are issues
15297  * with resets
15298  **/
15299 static i40e_status i40e_handle_resets(struct i40e_pf *pf)
15300 {
15301         const i40e_status pfr = i40e_pf_loop_reset(pf);
15302         const bool is_empr = i40e_check_fw_empr(pf);
15303
15304         if (is_empr || pfr != I40E_SUCCESS)
15305                 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");
15306
15307         return is_empr ? I40E_ERR_RESET_FAILED : pfr;
15308 }
15309
15310 /**
15311  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15312  * @pf: board private structure
15313  * @hw: ptr to the hardware info
15314  *
15315  * This function does a minimal setup of all subsystems needed for running
15316  * recovery mode.
15317  *
15318  * Returns 0 on success, negative on failure
15319  **/
15320 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15321 {
15322         struct i40e_vsi *vsi;
15323         int err;
15324         int v_idx;
15325
15326         pci_save_state(pf->pdev);
15327
15328         /* set up periodic task facility */
15329         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15330         pf->service_timer_period = HZ;
15331
15332         INIT_WORK(&pf->service_task, i40e_service_task);
15333         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15334
15335         err = i40e_init_interrupt_scheme(pf);
15336         if (err)
15337                 goto err_switch_setup;
15338
15339         /* The number of VSIs reported by the FW is the minimum guaranteed
15340          * to us; HW supports far more and we share the remaining pool with
15341          * the other PFs. We allocate space for more than the guarantee with
15342          * the understanding that we might not get them all later.
15343          */
15344         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15345                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15346         else
15347                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15348
15349         /* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15350         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15351                           GFP_KERNEL);
15352         if (!pf->vsi) {
15353                 err = -ENOMEM;
15354                 goto err_switch_setup;
15355         }
15356
15357         /* We allocate one VSI which is needed as absolute minimum
15358          * in order to register the netdev
15359          */
15360         v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15361         if (v_idx < 0) {
15362                 err = v_idx;
15363                 goto err_switch_setup;
15364         }
15365         pf->lan_vsi = v_idx;
15366         vsi = pf->vsi[v_idx];
15367         if (!vsi) {
15368                 err = -EFAULT;
15369                 goto err_switch_setup;
15370         }
15371         vsi->alloc_queue_pairs = 1;
15372         err = i40e_config_netdev(vsi);
15373         if (err)
15374                 goto err_switch_setup;
15375         err = register_netdev(vsi->netdev);
15376         if (err)
15377                 goto err_switch_setup;
15378         vsi->netdev_registered = true;
15379         i40e_dbg_pf_init(pf);
15380
15381         err = i40e_setup_misc_vector_for_recovery_mode(pf);
15382         if (err)
15383                 goto err_switch_setup;
15384
15385         /* tell the firmware that we're starting */
15386         i40e_send_version(pf);
15387
15388         /* since everything's happy, start the service_task timer */
15389         mod_timer(&pf->service_timer,
15390                   round_jiffies(jiffies + pf->service_timer_period));
15391
15392         return 0;
15393
15394 err_switch_setup:
15395         i40e_reset_interrupt_capability(pf);
15396         del_timer_sync(&pf->service_timer);
15397         i40e_shutdown_adminq(hw);
15398         iounmap(hw->hw_addr);
15399         pci_disable_pcie_error_reporting(pf->pdev);
15400         pci_release_mem_regions(pf->pdev);
15401         pci_disable_device(pf->pdev);
15402         kfree(pf);
15403
15404         return err;
15405 }
15406
15407 /**
15408  * i40e_set_subsystem_device_id - set subsystem device id
15409  * @hw: pointer to the hardware info
15410  *
15411  * Set PCI subsystem device id either from a pci_dev structure or
15412  * a specific FW register.
15413  **/
15414 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15415 {
15416         struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15417
15418         hw->subsystem_device_id = pdev->subsystem_device ?
15419                 pdev->subsystem_device :
15420                 (ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15421 }
15422
15423 /**
15424  * i40e_probe - Device initialization routine
15425  * @pdev: PCI device information struct
15426  * @ent: entry in i40e_pci_tbl
15427  *
15428  * i40e_probe initializes a PF identified by a pci_dev structure.
15429  * The OS initialization, configuring of the PF private structure,
15430  * and a hardware reset occur.
15431  *
15432  * Returns 0 on success, negative on failure
15433  **/
15434 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15435 {
15436         struct i40e_aq_get_phy_abilities_resp abilities;
15437 #ifdef CONFIG_I40E_DCB
15438         enum i40e_get_fw_lldp_status_resp lldp_status;
15439         i40e_status status;
15440 #endif /* CONFIG_I40E_DCB */
15441         struct i40e_pf *pf;
15442         struct i40e_hw *hw;
15443         static u16 pfs_found;
15444         u16 wol_nvm_bits;
15445         u16 link_status;
15446         int err;
15447         u32 val;
15448         u32 i;
15449
15450         err = pci_enable_device_mem(pdev);
15451         if (err)
15452                 return err;
15453
15454         /* set up for high or low dma */
15455         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15456         if (err) {
15457                 dev_err(&pdev->dev,
15458                         "DMA configuration failed: 0x%x\n", err);
15459                 goto err_dma;
15460         }
15461
15462         /* set up pci connections */
15463         err = pci_request_mem_regions(pdev, i40e_driver_name);
15464         if (err) {
15465                 dev_info(&pdev->dev,
15466                          "pci_request_selected_regions failed %d\n", err);
15467                 goto err_pci_reg;
15468         }
15469
15470         pci_enable_pcie_error_reporting(pdev);
15471         pci_set_master(pdev);
15472
15473         /* Now that we have a PCI connection, we need to do the
15474          * low level device setup.  This is primarily setting up
15475          * the Admin Queue structures and then querying for the
15476          * device's current profile information.
15477          */
15478         pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15479         if (!pf) {
15480                 err = -ENOMEM;
15481                 goto err_pf_alloc;
15482         }
15483         pf->next_vsi = 0;
15484         pf->pdev = pdev;
15485         set_bit(__I40E_DOWN, pf->state);
15486
15487         hw = &pf->hw;
15488         hw->back = pf;
15489
15490         pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15491                                 I40E_MAX_CSR_SPACE);
15492         /* We believe that the highest register to read is
15493          * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15494          * is not less than that before mapping to prevent a
15495          * kernel panic.
15496          */
15497         if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15498                 dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15499                         pf->ioremap_len);
15500                 err = -ENOMEM;
15501                 goto err_ioremap;
15502         }
15503         hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15504         if (!hw->hw_addr) {
15505                 err = -EIO;
15506                 dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15507                          (unsigned int)pci_resource_start(pdev, 0),
15508                          pf->ioremap_len, err);
15509                 goto err_ioremap;
15510         }
15511         hw->vendor_id = pdev->vendor;
15512         hw->device_id = pdev->device;
15513         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15514         hw->subsystem_vendor_id = pdev->subsystem_vendor;
15515         i40e_set_subsystem_device_id(hw);
15516         hw->bus.device = PCI_SLOT(pdev->devfn);
15517         hw->bus.func = PCI_FUNC(pdev->devfn);
15518         hw->bus.bus_id = pdev->bus->number;
15519         pf->instance = pfs_found;
15520
15521         /* Select something other than the 802.1ad ethertype for the
15522          * switch to use internally and drop on ingress.
15523          */
15524         hw->switch_tag = 0xffff;
15525         hw->first_tag = ETH_P_8021AD;
15526         hw->second_tag = ETH_P_8021Q;
15527
15528         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15529         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15530         INIT_LIST_HEAD(&pf->ddp_old_prof);
15531
15532         /* set up the locks for the AQ, do this only once in probe
15533          * and destroy them only once in remove
15534          */
15535         mutex_init(&hw->aq.asq_mutex);
15536         mutex_init(&hw->aq.arq_mutex);
15537
15538         pf->msg_enable = netif_msg_init(debug,
15539                                         NETIF_MSG_DRV |
15540                                         NETIF_MSG_PROBE |
15541                                         NETIF_MSG_LINK);
15542         if (debug < -1)
15543                 pf->hw.debug_mask = debug;
15544
15545         /* do a special CORER for clearing PXE mode once at init */
15546         if (hw->revision_id == 0 &&
15547             (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15548                 wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15549                 i40e_flush(hw);
15550                 msleep(200);
15551                 pf->corer_count++;
15552
15553                 i40e_clear_pxe_mode(hw);
15554         }
15555
15556         /* Reset here to make sure all is clean and to define PF 'n' */
15557         i40e_clear_hw(hw);
15558
15559         err = i40e_set_mac_type(hw);
15560         if (err) {
15561                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15562                          err);
15563                 goto err_pf_reset;
15564         }
15565
15566         err = i40e_handle_resets(pf);
15567         if (err)
15568                 goto err_pf_reset;
15569
15570         i40e_check_recovery_mode(pf);
15571
15572         if (is_kdump_kernel()) {
15573                 hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15574                 hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15575         } else {
15576                 hw->aq.num_arq_entries = I40E_AQ_LEN;
15577                 hw->aq.num_asq_entries = I40E_AQ_LEN;
15578         }
15579         hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15580         hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15581         pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15582
15583         snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15584                  "%s-%s:misc",
15585                  dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15586
15587         err = i40e_init_shared_code(hw);
15588         if (err) {
15589                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15590                          err);
15591                 goto err_pf_reset;
15592         }
15593
15594         /* set up a default setting for link flow control */
15595         pf->hw.fc.requested_mode = I40E_FC_NONE;
15596
15597         err = i40e_init_adminq(hw);
15598         if (err) {
15599                 if (err == I40E_ERR_FIRMWARE_API_VERSION)
15600                         dev_info(&pdev->dev,
15601                                  "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",
15602                                  hw->aq.api_maj_ver,
15603                                  hw->aq.api_min_ver,
15604                                  I40E_FW_API_VERSION_MAJOR,
15605                                  I40E_FW_MINOR_VERSION(hw));
15606                 else
15607                         dev_info(&pdev->dev,
15608                                  "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15609
15610                 goto err_pf_reset;
15611         }
15612         i40e_get_oem_version(hw);
15613
15614         /* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15615         dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15616                  hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15617                  hw->aq.api_maj_ver, hw->aq.api_min_ver,
15618                  i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15619                  hw->subsystem_vendor_id, hw->subsystem_device_id);
15620
15621         if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15622             hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15623                 dev_dbg(&pdev->dev,
15624                         "The driver for the device detected a newer version of the NVM image v%u.%u than v%u.%u.\n",
15625                          hw->aq.api_maj_ver,
15626                          hw->aq.api_min_ver,
15627                          I40E_FW_API_VERSION_MAJOR,
15628                          I40E_FW_MINOR_VERSION(hw));
15629         else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15630                 dev_info(&pdev->dev,
15631                          "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",
15632                          hw->aq.api_maj_ver,
15633                          hw->aq.api_min_ver,
15634                          I40E_FW_API_VERSION_MAJOR,
15635                          I40E_FW_MINOR_VERSION(hw));
15636
15637         i40e_verify_eeprom(pf);
15638
15639         /* Rev 0 hardware was never productized */
15640         if (hw->revision_id < 1)
15641                 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");
15642
15643         i40e_clear_pxe_mode(hw);
15644
15645         err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15646         if (err)
15647                 goto err_adminq_setup;
15648
15649         err = i40e_sw_init(pf);
15650         if (err) {
15651                 dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15652                 goto err_sw_init;
15653         }
15654
15655         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15656                 return i40e_init_recovery_mode(pf, hw);
15657
15658         err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15659                                 hw->func_caps.num_rx_qp, 0, 0);
15660         if (err) {
15661                 dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15662                 goto err_init_lan_hmc;
15663         }
15664
15665         err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15666         if (err) {
15667                 dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15668                 err = -ENOENT;
15669                 goto err_configure_lan_hmc;
15670         }
15671
15672         /* Disable LLDP for NICs that have firmware versions lower than v4.3.
15673          * Ignore error return codes because if it was already disabled via
15674          * hardware settings this will fail
15675          */
15676         if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15677                 dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15678                 i40e_aq_stop_lldp(hw, true, false, NULL);
15679         }
15680
15681         /* allow a platform config to override the HW addr */
15682         i40e_get_platform_mac_addr(pdev, pf);
15683
15684         if (!is_valid_ether_addr(hw->mac.addr)) {
15685                 dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15686                 err = -EIO;
15687                 goto err_mac_addr;
15688         }
15689         dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15690         ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15691         i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15692         if (is_valid_ether_addr(hw->mac.port_addr))
15693                 pf->hw_features |= I40E_HW_PORT_ID_VALID;
15694
15695         i40e_ptp_alloc_pins(pf);
15696         pci_set_drvdata(pdev, pf);
15697         pci_save_state(pdev);
15698
15699 #ifdef CONFIG_I40E_DCB
15700         status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15701         (!status &&
15702          lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15703                 (pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15704                 (pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15705         dev_info(&pdev->dev,
15706                  (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15707                         "FW LLDP is disabled\n" :
15708                         "FW LLDP is enabled\n");
15709
15710         /* Enable FW to write default DCB config on link-up */
15711         i40e_aq_set_dcb_parameters(hw, true, NULL);
15712
15713         err = i40e_init_pf_dcb(pf);
15714         if (err) {
15715                 dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15716                 pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15717                 /* Continue without DCB enabled */
15718         }
15719 #endif /* CONFIG_I40E_DCB */
15720
15721         /* set up periodic task facility */
15722         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15723         pf->service_timer_period = HZ;
15724
15725         INIT_WORK(&pf->service_task, i40e_service_task);
15726         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15727
15728         /* NVM bit on means WoL disabled for the port */
15729         i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15730         if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15731                 pf->wol_en = false;
15732         else
15733                 pf->wol_en = true;
15734         device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15735
15736         /* set up the main switch operations */
15737         i40e_determine_queue_usage(pf);
15738         err = i40e_init_interrupt_scheme(pf);
15739         if (err)
15740                 goto err_switch_setup;
15741
15742         /* Reduce Tx and Rx pairs for kdump
15743          * When MSI-X is enabled, it's not allowed to use more TC queue
15744          * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15745          * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15746          */
15747         if (is_kdump_kernel())
15748                 pf->num_lan_msix = 1;
15749
15750         pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15751         pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15752         pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15753         pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15754         pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15755         pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15756                                                     UDP_TUNNEL_TYPE_GENEVE;
15757
15758         /* The number of VSIs reported by the FW is the minimum guaranteed
15759          * to us; HW supports far more and we share the remaining pool with
15760          * the other PFs. We allocate space for more than the guarantee with
15761          * the understanding that we might not get them all later.
15762          */
15763         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15764                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15765         else
15766                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15767         if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15768                 dev_warn(&pf->pdev->dev,
15769                          "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15770                          pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15771                 pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15772         }
15773
15774         /* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15775         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15776                           GFP_KERNEL);
15777         if (!pf->vsi) {
15778                 err = -ENOMEM;
15779                 goto err_switch_setup;
15780         }
15781
15782 #ifdef CONFIG_PCI_IOV
15783         /* prep for VF support */
15784         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15785             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15786             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15787                 if (pci_num_vf(pdev))
15788                         pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
15789         }
15790 #endif
15791         err = i40e_setup_pf_switch(pf, false, false);
15792         if (err) {
15793                 dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15794                 goto err_vsis;
15795         }
15796         INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
15797
15798         /* if FDIR VSI was set up, start it now */
15799         for (i = 0; i < pf->num_alloc_vsi; i++) {
15800                 if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
15801                         i40e_vsi_open(pf->vsi[i]);
15802                         break;
15803                 }
15804         }
15805
15806         /* The driver only wants link up/down and module qualification
15807          * reports from firmware.  Note the negative logic.
15808          */
15809         err = i40e_aq_set_phy_int_mask(&pf->hw,
15810                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
15811                                          I40E_AQ_EVENT_MEDIA_NA |
15812                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15813         if (err)
15814                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
15815                          i40e_stat_str(&pf->hw, err),
15816                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15817
15818         /* Reconfigure hardware for allowing smaller MSS in the case
15819          * of TSO, so that we avoid the MDD being fired and causing
15820          * a reset in the case of small MSS+TSO.
15821          */
15822         val = rd32(hw, I40E_REG_MSS);
15823         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15824                 val &= ~I40E_REG_MSS_MIN_MASK;
15825                 val |= I40E_64BYTE_MSS;
15826                 wr32(hw, I40E_REG_MSS, val);
15827         }
15828
15829         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
15830                 msleep(75);
15831                 err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15832                 if (err)
15833                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
15834                                  i40e_stat_str(&pf->hw, err),
15835                                  i40e_aq_str(&pf->hw,
15836                                              pf->hw.aq.asq_last_status));
15837         }
15838         /* The main driver is (mostly) up and happy. We need to set this state
15839          * before setting up the misc vector or we get a race and the vector
15840          * ends up disabled forever.
15841          */
15842         clear_bit(__I40E_DOWN, pf->state);
15843
15844         /* In case of MSIX we are going to setup the misc vector right here
15845          * to handle admin queue events etc. In case of legacy and MSI
15846          * the misc functionality and queue processing is combined in
15847          * the same vector and that gets setup at open.
15848          */
15849         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
15850                 err = i40e_setup_misc_vector(pf);
15851                 if (err) {
15852                         dev_info(&pdev->dev,
15853                                  "setup of misc vector failed: %d\n", err);
15854                         i40e_cloud_filter_exit(pf);
15855                         i40e_fdir_teardown(pf);
15856                         goto err_vsis;
15857                 }
15858         }
15859
15860 #ifdef CONFIG_PCI_IOV
15861         /* prep for VF support */
15862         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15863             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15864             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15865                 /* disable link interrupts for VFs */
15866                 val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15867                 val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15868                 wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15869                 i40e_flush(hw);
15870
15871                 if (pci_num_vf(pdev)) {
15872                         dev_info(&pdev->dev,
15873                                  "Active VFs found, allocating resources.\n");
15874                         err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15875                         if (err)
15876                                 dev_info(&pdev->dev,
15877                                          "Error %d allocating resources for existing VFs\n",
15878                                          err);
15879                 }
15880         }
15881 #endif /* CONFIG_PCI_IOV */
15882
15883         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15884                 pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
15885                                                       pf->num_iwarp_msix,
15886                                                       I40E_IWARP_IRQ_PILE_ID);
15887                 if (pf->iwarp_base_vector < 0) {
15888                         dev_info(&pdev->dev,
15889                                  "failed to get tracking for %d vectors for IWARP err=%d\n",
15890                                  pf->num_iwarp_msix, pf->iwarp_base_vector);
15891                         pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
15892                 }
15893         }
15894
15895         i40e_dbg_pf_init(pf);
15896
15897         /* tell the firmware that we're starting */
15898         i40e_send_version(pf);
15899
15900         /* since everything's happy, start the service_task timer */
15901         mod_timer(&pf->service_timer,
15902                   round_jiffies(jiffies + pf->service_timer_period));
15903
15904         /* add this PF to client device list and launch a client service task */
15905         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15906                 err = i40e_lan_add_device(pf);
15907                 if (err)
15908                         dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
15909                                  err);
15910         }
15911
15912 #define PCI_SPEED_SIZE 8
15913 #define PCI_WIDTH_SIZE 8
15914         /* Devices on the IOSF bus do not have this information
15915          * and will report PCI Gen 1 x 1 by default so don't bother
15916          * checking them.
15917          */
15918         if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
15919                 char speed[PCI_SPEED_SIZE] = "Unknown";
15920                 char width[PCI_WIDTH_SIZE] = "Unknown";
15921
15922                 /* Get the negotiated link width and speed from PCI config
15923                  * space
15924                  */
15925                 pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
15926                                           &link_status);
15927
15928                 i40e_set_pci_config_data(hw, link_status);
15929
15930                 switch (hw->bus.speed) {
15931                 case i40e_bus_speed_8000:
15932                         strlcpy(speed, "8.0", PCI_SPEED_SIZE); break;
15933                 case i40e_bus_speed_5000:
15934                         strlcpy(speed, "5.0", PCI_SPEED_SIZE); break;
15935                 case i40e_bus_speed_2500:
15936                         strlcpy(speed, "2.5", PCI_SPEED_SIZE); break;
15937                 default:
15938                         break;
15939                 }
15940                 switch (hw->bus.width) {
15941                 case i40e_bus_width_pcie_x8:
15942                         strlcpy(width, "8", PCI_WIDTH_SIZE); break;
15943                 case i40e_bus_width_pcie_x4:
15944                         strlcpy(width, "4", PCI_WIDTH_SIZE); break;
15945                 case i40e_bus_width_pcie_x2:
15946                         strlcpy(width, "2", PCI_WIDTH_SIZE); break;
15947                 case i40e_bus_width_pcie_x1:
15948                         strlcpy(width, "1", PCI_WIDTH_SIZE); break;
15949                 default:
15950                         break;
15951                 }
15952
15953                 dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
15954                          speed, width);
15955
15956                 if (hw->bus.width < i40e_bus_width_pcie_x8 ||
15957                     hw->bus.speed < i40e_bus_speed_8000) {
15958                         dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
15959                         dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
15960                 }
15961         }
15962
15963         /* get the requested speeds from the fw */
15964         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
15965         if (err)
15966                 dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
15967                         i40e_stat_str(&pf->hw, err),
15968                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15969         pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
15970
15971         /* set the FEC config due to the board capabilities */
15972         i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
15973
15974         /* get the supported phy types from the fw */
15975         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
15976         if (err)
15977                 dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
15978                         i40e_stat_str(&pf->hw, err),
15979                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15980
15981         /* make sure the MFS hasn't been set lower than the default */
15982 #define MAX_FRAME_SIZE_DEFAULT 0x2600
15983         val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
15984                I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
15985         if (val < MAX_FRAME_SIZE_DEFAULT)
15986                 dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
15987                          i, val);
15988
15989         /* Add a filter to drop all Flow control frames from any VSI from being
15990          * transmitted. By doing so we stop a malicious VF from sending out
15991          * PAUSE or PFC frames and potentially controlling traffic for other
15992          * PF/VF VSIs.
15993          * The FW can still send Flow control frames if enabled.
15994          */
15995         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
15996                                                        pf->main_vsi_seid);
15997
15998         if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
15999                 (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
16000                 pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
16001         if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
16002                 pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
16003         /* print a string summarizing features */
16004         i40e_print_features(pf);
16005
16006         return 0;
16007
16008         /* Unwind what we've done if something failed in the setup */
16009 err_vsis:
16010         set_bit(__I40E_DOWN, pf->state);
16011         i40e_clear_interrupt_scheme(pf);
16012         kfree(pf->vsi);
16013 err_switch_setup:
16014         i40e_reset_interrupt_capability(pf);
16015         del_timer_sync(&pf->service_timer);
16016 err_mac_addr:
16017 err_configure_lan_hmc:
16018         (void)i40e_shutdown_lan_hmc(hw);
16019 err_init_lan_hmc:
16020         kfree(pf->qp_pile);
16021 err_sw_init:
16022 err_adminq_setup:
16023 err_pf_reset:
16024         iounmap(hw->hw_addr);
16025 err_ioremap:
16026         kfree(pf);
16027 err_pf_alloc:
16028         pci_disable_pcie_error_reporting(pdev);
16029         pci_release_mem_regions(pdev);
16030 err_pci_reg:
16031 err_dma:
16032         pci_disable_device(pdev);
16033         return err;
16034 }
16035
16036 /**
16037  * i40e_remove - Device removal routine
16038  * @pdev: PCI device information struct
16039  *
16040  * i40e_remove is called by the PCI subsystem to alert the driver
16041  * that is should release a PCI device.  This could be caused by a
16042  * Hot-Plug event, or because the driver is going to be removed from
16043  * memory.
16044  **/
16045 static void i40e_remove(struct pci_dev *pdev)
16046 {
16047         struct i40e_pf *pf = pci_get_drvdata(pdev);
16048         struct i40e_hw *hw = &pf->hw;
16049         i40e_status ret_code;
16050         int i;
16051
16052         i40e_dbg_pf_exit(pf);
16053
16054         i40e_ptp_stop(pf);
16055
16056         /* Disable RSS in hw */
16057         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
16058         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
16059
16060         /* Grab __I40E_RESET_RECOVERY_PENDING and set __I40E_IN_REMOVE
16061          * flags, once they are set, i40e_rebuild should not be called as
16062          * i40e_prep_for_reset always returns early.
16063          */
16064         while (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
16065                 usleep_range(1000, 2000);
16066         set_bit(__I40E_IN_REMOVE, pf->state);
16067
16068         if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
16069                 set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
16070                 i40e_free_vfs(pf);
16071                 pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
16072         }
16073         /* no more scheduling of any task */
16074         set_bit(__I40E_SUSPENDED, pf->state);
16075         set_bit(__I40E_DOWN, pf->state);
16076         if (pf->service_timer.function)
16077                 del_timer_sync(&pf->service_timer);
16078         if (pf->service_task.func)
16079                 cancel_work_sync(&pf->service_task);
16080
16081         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
16082                 struct i40e_vsi *vsi = pf->vsi[0];
16083
16084                 /* We know that we have allocated only one vsi for this PF,
16085                  * it was just for registering netdevice, so the interface
16086                  * could be visible in the 'ifconfig' output
16087                  */
16088                 unregister_netdev(vsi->netdev);
16089                 free_netdev(vsi->netdev);
16090
16091                 goto unmap;
16092         }
16093
16094         /* Client close must be called explicitly here because the timer
16095          * has been stopped.
16096          */
16097         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16098
16099         i40e_fdir_teardown(pf);
16100
16101         /* If there is a switch structure or any orphans, remove them.
16102          * This will leave only the PF's VSI remaining.
16103          */
16104         for (i = 0; i < I40E_MAX_VEB; i++) {
16105                 if (!pf->veb[i])
16106                         continue;
16107
16108                 if (pf->veb[i]->uplink_seid == pf->mac_seid ||
16109                     pf->veb[i]->uplink_seid == 0)
16110                         i40e_switch_branch_release(pf->veb[i]);
16111         }
16112
16113         /* Now we can shutdown the PF's VSI, just before we kill
16114          * adminq and hmc.
16115          */
16116         if (pf->vsi[pf->lan_vsi])
16117                 i40e_vsi_release(pf->vsi[pf->lan_vsi]);
16118
16119         i40e_cloud_filter_exit(pf);
16120
16121         /* remove attached clients */
16122         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
16123                 ret_code = i40e_lan_del_device(pf);
16124                 if (ret_code)
16125                         dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
16126                                  ret_code);
16127         }
16128
16129         /* shutdown and destroy the HMC */
16130         if (hw->hmc.hmc_obj) {
16131                 ret_code = i40e_shutdown_lan_hmc(hw);
16132                 if (ret_code)
16133                         dev_warn(&pdev->dev,
16134                                  "Failed to destroy the HMC resources: %d\n",
16135                                  ret_code);
16136         }
16137
16138 unmap:
16139         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16140         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16141             !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16142                 free_irq(pf->pdev->irq, pf);
16143
16144         /* shutdown the adminq */
16145         i40e_shutdown_adminq(hw);
16146
16147         /* destroy the locks only once, here */
16148         mutex_destroy(&hw->aq.arq_mutex);
16149         mutex_destroy(&hw->aq.asq_mutex);
16150
16151         /* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
16152         rtnl_lock();
16153         i40e_clear_interrupt_scheme(pf);
16154         for (i = 0; i < pf->num_alloc_vsi; i++) {
16155                 if (pf->vsi[i]) {
16156                         if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
16157                                 i40e_vsi_clear_rings(pf->vsi[i]);
16158                         i40e_vsi_clear(pf->vsi[i]);
16159                         pf->vsi[i] = NULL;
16160                 }
16161         }
16162         rtnl_unlock();
16163
16164         for (i = 0; i < I40E_MAX_VEB; i++) {
16165                 kfree(pf->veb[i]);
16166                 pf->veb[i] = NULL;
16167         }
16168
16169         kfree(pf->qp_pile);
16170         kfree(pf->vsi);
16171
16172         iounmap(hw->hw_addr);
16173         kfree(pf);
16174         pci_release_mem_regions(pdev);
16175
16176         pci_disable_pcie_error_reporting(pdev);
16177         pci_disable_device(pdev);
16178 }
16179
16180 /**
16181  * i40e_pci_error_detected - warning that something funky happened in PCI land
16182  * @pdev: PCI device information struct
16183  * @error: the type of PCI error
16184  *
16185  * Called to warn that something happened and the error handling steps
16186  * are in progress.  Allows the driver to quiesce things, be ready for
16187  * remediation.
16188  **/
16189 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
16190                                                 pci_channel_state_t error)
16191 {
16192         struct i40e_pf *pf = pci_get_drvdata(pdev);
16193
16194         dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
16195
16196         if (!pf) {
16197                 dev_info(&pdev->dev,
16198                          "Cannot recover - error happened during device probe\n");
16199                 return PCI_ERS_RESULT_DISCONNECT;
16200         }
16201
16202         /* shutdown all operations */
16203         if (!test_bit(__I40E_SUSPENDED, pf->state))
16204                 i40e_prep_for_reset(pf);
16205
16206         /* Request a slot reset */
16207         return PCI_ERS_RESULT_NEED_RESET;
16208 }
16209
16210 /**
16211  * i40e_pci_error_slot_reset - a PCI slot reset just happened
16212  * @pdev: PCI device information struct
16213  *
16214  * Called to find if the driver can work with the device now that
16215  * the pci slot has been reset.  If a basic connection seems good
16216  * (registers are readable and have sane content) then return a
16217  * happy little PCI_ERS_RESULT_xxx.
16218  **/
16219 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
16220 {
16221         struct i40e_pf *pf = pci_get_drvdata(pdev);
16222         pci_ers_result_t result;
16223         u32 reg;
16224
16225         dev_dbg(&pdev->dev, "%s\n", __func__);
16226         if (pci_enable_device_mem(pdev)) {
16227                 dev_info(&pdev->dev,
16228                          "Cannot re-enable PCI device after reset.\n");
16229                 result = PCI_ERS_RESULT_DISCONNECT;
16230         } else {
16231                 pci_set_master(pdev);
16232                 pci_restore_state(pdev);
16233                 pci_save_state(pdev);
16234                 pci_wake_from_d3(pdev, false);
16235
16236                 reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16237                 if (reg == 0)
16238                         result = PCI_ERS_RESULT_RECOVERED;
16239                 else
16240                         result = PCI_ERS_RESULT_DISCONNECT;
16241         }
16242
16243         return result;
16244 }
16245
16246 /**
16247  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16248  * @pdev: PCI device information struct
16249  */
16250 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16251 {
16252         struct i40e_pf *pf = pci_get_drvdata(pdev);
16253
16254         i40e_prep_for_reset(pf);
16255 }
16256
16257 /**
16258  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16259  * @pdev: PCI device information struct
16260  */
16261 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16262 {
16263         struct i40e_pf *pf = pci_get_drvdata(pdev);
16264
16265         if (test_bit(__I40E_IN_REMOVE, pf->state))
16266                 return;
16267
16268         i40e_reset_and_rebuild(pf, false, false);
16269 }
16270
16271 /**
16272  * i40e_pci_error_resume - restart operations after PCI error recovery
16273  * @pdev: PCI device information struct
16274  *
16275  * Called to allow the driver to bring things back up after PCI error
16276  * and/or reset recovery has finished.
16277  **/
16278 static void i40e_pci_error_resume(struct pci_dev *pdev)
16279 {
16280         struct i40e_pf *pf = pci_get_drvdata(pdev);
16281
16282         dev_dbg(&pdev->dev, "%s\n", __func__);
16283         if (test_bit(__I40E_SUSPENDED, pf->state))
16284                 return;
16285
16286         i40e_handle_reset_warning(pf, false);
16287 }
16288
16289 /**
16290  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16291  * using the mac_address_write admin q function
16292  * @pf: pointer to i40e_pf struct
16293  **/
16294 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16295 {
16296         struct i40e_hw *hw = &pf->hw;
16297         i40e_status ret;
16298         u8 mac_addr[6];
16299         u16 flags = 0;
16300
16301         /* Get current MAC address in case it's an LAA */
16302         if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16303                 ether_addr_copy(mac_addr,
16304                                 pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16305         } else {
16306                 dev_err(&pf->pdev->dev,
16307                         "Failed to retrieve MAC address; using default\n");
16308                 ether_addr_copy(mac_addr, hw->mac.addr);
16309         }
16310
16311         /* The FW expects the mac address write cmd to first be called with
16312          * one of these flags before calling it again with the multicast
16313          * enable flags.
16314          */
16315         flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16316
16317         if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16318                 flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16319
16320         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16321         if (ret) {
16322                 dev_err(&pf->pdev->dev,
16323                         "Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16324                 return;
16325         }
16326
16327         flags = I40E_AQC_MC_MAG_EN
16328                         | I40E_AQC_WOL_PRESERVE_ON_PFR
16329                         | I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16330         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16331         if (ret)
16332                 dev_err(&pf->pdev->dev,
16333                         "Failed to enable Multicast Magic Packet wake up\n");
16334 }
16335
16336 /**
16337  * i40e_shutdown - PCI callback for shutting down
16338  * @pdev: PCI device information struct
16339  **/
16340 static void i40e_shutdown(struct pci_dev *pdev)
16341 {
16342         struct i40e_pf *pf = pci_get_drvdata(pdev);
16343         struct i40e_hw *hw = &pf->hw;
16344
16345         set_bit(__I40E_SUSPENDED, pf->state);
16346         set_bit(__I40E_DOWN, pf->state);
16347
16348         del_timer_sync(&pf->service_timer);
16349         cancel_work_sync(&pf->service_task);
16350         i40e_cloud_filter_exit(pf);
16351         i40e_fdir_teardown(pf);
16352
16353         /* Client close must be called explicitly here because the timer
16354          * has been stopped.
16355          */
16356         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16357
16358         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16359                 i40e_enable_mc_magic_wake(pf);
16360
16361         i40e_prep_for_reset(pf);
16362
16363         wr32(hw, I40E_PFPM_APM,
16364              (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16365         wr32(hw, I40E_PFPM_WUFC,
16366              (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16367
16368         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16369         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16370             !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16371                 free_irq(pf->pdev->irq, pf);
16372
16373         /* Since we're going to destroy queues during the
16374          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16375          * whole section
16376          */
16377         rtnl_lock();
16378         i40e_clear_interrupt_scheme(pf);
16379         rtnl_unlock();
16380
16381         if (system_state == SYSTEM_POWER_OFF) {
16382                 pci_wake_from_d3(pdev, pf->wol_en);
16383                 pci_set_power_state(pdev, PCI_D3hot);
16384         }
16385 }
16386
16387 /**
16388  * i40e_suspend - PM callback for moving to D3
16389  * @dev: generic device information structure
16390  **/
16391 static int __maybe_unused i40e_suspend(struct device *dev)
16392 {
16393         struct i40e_pf *pf = dev_get_drvdata(dev);
16394         struct i40e_hw *hw = &pf->hw;
16395
16396         /* If we're already suspended, then there is nothing to do */
16397         if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16398                 return 0;
16399
16400         set_bit(__I40E_DOWN, pf->state);
16401
16402         /* Ensure service task will not be running */
16403         del_timer_sync(&pf->service_timer);
16404         cancel_work_sync(&pf->service_task);
16405
16406         /* Client close must be called explicitly here because the timer
16407          * has been stopped.
16408          */
16409         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16410
16411         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16412                 i40e_enable_mc_magic_wake(pf);
16413
16414         /* Since we're going to destroy queues during the
16415          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16416          * whole section
16417          */
16418         rtnl_lock();
16419
16420         i40e_prep_for_reset(pf);
16421
16422         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16423         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16424
16425         /* Clear the interrupt scheme and release our IRQs so that the system
16426          * can safely hibernate even when there are a large number of CPUs.
16427          * Otherwise hibernation might fail when mapping all the vectors back
16428          * to CPU0.
16429          */
16430         i40e_clear_interrupt_scheme(pf);
16431
16432         rtnl_unlock();
16433
16434         return 0;
16435 }
16436
16437 /**
16438  * i40e_resume - PM callback for waking up from D3
16439  * @dev: generic device information structure
16440  **/
16441 static int __maybe_unused i40e_resume(struct device *dev)
16442 {
16443         struct i40e_pf *pf = dev_get_drvdata(dev);
16444         int err;
16445
16446         /* If we're not suspended, then there is nothing to do */
16447         if (!test_bit(__I40E_SUSPENDED, pf->state))
16448                 return 0;
16449
16450         /* We need to hold the RTNL lock prior to restoring interrupt schemes,
16451          * since we're going to be restoring queues
16452          */
16453         rtnl_lock();
16454
16455         /* We cleared the interrupt scheme when we suspended, so we need to
16456          * restore it now to resume device functionality.
16457          */
16458         err = i40e_restore_interrupt_scheme(pf);
16459         if (err) {
16460                 dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16461                         err);
16462         }
16463
16464         clear_bit(__I40E_DOWN, pf->state);
16465         i40e_reset_and_rebuild(pf, false, true);
16466
16467         rtnl_unlock();
16468
16469         /* Clear suspended state last after everything is recovered */
16470         clear_bit(__I40E_SUSPENDED, pf->state);
16471
16472         /* Restart the service task */
16473         mod_timer(&pf->service_timer,
16474                   round_jiffies(jiffies + pf->service_timer_period));
16475
16476         return 0;
16477 }
16478
16479 static const struct pci_error_handlers i40e_err_handler = {
16480         .error_detected = i40e_pci_error_detected,
16481         .slot_reset = i40e_pci_error_slot_reset,
16482         .reset_prepare = i40e_pci_error_reset_prepare,
16483         .reset_done = i40e_pci_error_reset_done,
16484         .resume = i40e_pci_error_resume,
16485 };
16486
16487 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16488
16489 static struct pci_driver i40e_driver = {
16490         .name     = i40e_driver_name,
16491         .id_table = i40e_pci_tbl,
16492         .probe    = i40e_probe,
16493         .remove   = i40e_remove,
16494         .driver   = {
16495                 .pm = &i40e_pm_ops,
16496         },
16497         .shutdown = i40e_shutdown,
16498         .err_handler = &i40e_err_handler,
16499         .sriov_configure = i40e_pci_sriov_configure,
16500 };
16501
16502 /**
16503  * i40e_init_module - Driver registration routine
16504  *
16505  * i40e_init_module is the first routine called when the driver is
16506  * loaded. All it does is register with the PCI subsystem.
16507  **/
16508 static int __init i40e_init_module(void)
16509 {
16510         pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16511         pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16512
16513         /* There is no need to throttle the number of active tasks because
16514          * each device limits its own task using a state bit for scheduling
16515          * the service task, and the device tasks do not interfere with each
16516          * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16517          * since we need to be able to guarantee forward progress even under
16518          * memory pressure.
16519          */
16520         i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16521         if (!i40e_wq) {
16522                 pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16523                 return -ENOMEM;
16524         }
16525
16526         i40e_dbg_init();
16527         return pci_register_driver(&i40e_driver);
16528 }
16529 module_init(i40e_init_module);
16530
16531 /**
16532  * i40e_exit_module - Driver exit cleanup routine
16533  *
16534  * i40e_exit_module is called just before the driver is removed
16535  * from memory.
16536  **/
16537 static void __exit i40e_exit_module(void)
16538 {
16539         pci_unregister_driver(&i40e_driver);
16540         destroy_workqueue(i40e_wq);
16541         ida_destroy(&i40e_client_ida);
16542         i40e_dbg_exit();
16543 }
16544 module_exit(i40e_exit_module);