b5b984754ec92f524508cde0a28bd497e8289c59
[sfrench/cifs-2.6.git] / drivers / net / ethernet / intel / i40e / i40e_main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2021 Intel Corporation. */
3
4 #include <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_20G_KR2), 0},
81         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
82         {PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
83         {PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
84         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
85         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
86         /* required last entry */
87         {0, }
88 };
89 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
90
91 #define I40E_MAX_VF_COUNT 128
92 static int debug = -1;
93 module_param(debug, uint, 0);
94 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
95
96 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
97 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
98 MODULE_LICENSE("GPL v2");
99
100 static struct workqueue_struct *i40e_wq;
101
102 /**
103  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
104  * @hw:   pointer to the HW structure
105  * @mem:  ptr to mem struct to fill out
106  * @size: size of memory requested
107  * @alignment: what to align the allocation to
108  **/
109 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
110                             u64 size, u32 alignment)
111 {
112         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
113
114         mem->size = ALIGN(size, alignment);
115         mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
116                                      GFP_KERNEL);
117         if (!mem->va)
118                 return -ENOMEM;
119
120         return 0;
121 }
122
123 /**
124  * i40e_free_dma_mem_d - OS specific memory free for shared code
125  * @hw:   pointer to the HW structure
126  * @mem:  ptr to mem struct to free
127  **/
128 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
129 {
130         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
131
132         dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
133         mem->va = NULL;
134         mem->pa = 0;
135         mem->size = 0;
136
137         return 0;
138 }
139
140 /**
141  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
142  * @hw:   pointer to the HW structure
143  * @mem:  ptr to mem struct to fill out
144  * @size: size of memory requested
145  **/
146 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
147                              u32 size)
148 {
149         mem->size = size;
150         mem->va = kzalloc(size, GFP_KERNEL);
151
152         if (!mem->va)
153                 return -ENOMEM;
154
155         return 0;
156 }
157
158 /**
159  * i40e_free_virt_mem_d - OS specific memory free for shared code
160  * @hw:   pointer to the HW structure
161  * @mem:  ptr to mem struct to free
162  **/
163 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
164 {
165         /* it's ok to kfree a NULL pointer */
166         kfree(mem->va);
167         mem->va = NULL;
168         mem->size = 0;
169
170         return 0;
171 }
172
173 /**
174  * i40e_get_lump - find a lump of free generic resource
175  * @pf: board private structure
176  * @pile: the pile of resource to search
177  * @needed: the number of items needed
178  * @id: an owner id to stick on the items assigned
179  *
180  * Returns the base item index of the lump, or negative for error
181  *
182  * The search_hint trick and lack of advanced fit-finding only work
183  * because we're highly likely to have all the same size lump requests.
184  * Linear search time and any fragmentation should be minimal.
185  **/
186 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
187                          u16 needed, u16 id)
188 {
189         int ret = -ENOMEM;
190         int i, j;
191
192         if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
193                 dev_info(&pf->pdev->dev,
194                          "param err: pile=%s needed=%d id=0x%04x\n",
195                          pile ? "<valid>" : "<null>", needed, id);
196                 return -EINVAL;
197         }
198
199         /* start the linear search with an imperfect hint */
200         i = pile->search_hint;
201         while (i < pile->num_entries) {
202                 /* skip already allocated entries */
203                 if (pile->list[i] & I40E_PILE_VALID_BIT) {
204                         i++;
205                         continue;
206                 }
207
208                 /* do we have enough in this lump? */
209                 for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
210                         if (pile->list[i+j] & I40E_PILE_VALID_BIT)
211                                 break;
212                 }
213
214                 if (j == needed) {
215                         /* there was enough, so assign it to the requestor */
216                         for (j = 0; j < needed; j++)
217                                 pile->list[i+j] = id | I40E_PILE_VALID_BIT;
218                         ret = i;
219                         pile->search_hint = i + j;
220                         break;
221                 }
222
223                 /* not enough, so skip over it and continue looking */
224                 i += j;
225         }
226
227         return ret;
228 }
229
230 /**
231  * i40e_put_lump - return a lump of generic resource
232  * @pile: the pile of resource to search
233  * @index: the base item index
234  * @id: the owner id of the items assigned
235  *
236  * Returns the count of items in the lump
237  **/
238 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
239 {
240         int valid_id = (id | I40E_PILE_VALID_BIT);
241         int count = 0;
242         int i;
243
244         if (!pile || index >= pile->num_entries)
245                 return -EINVAL;
246
247         for (i = index;
248              i < pile->num_entries && pile->list[i] == valid_id;
249              i++) {
250                 pile->list[i] = 0;
251                 count++;
252         }
253
254         if (count && index < pile->search_hint)
255                 pile->search_hint = index;
256
257         return count;
258 }
259
260 /**
261  * i40e_find_vsi_from_id - searches for the vsi with the given id
262  * @pf: the pf structure to search for the vsi
263  * @id: id of the vsi it is searching for
264  **/
265 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
266 {
267         int i;
268
269         for (i = 0; i < pf->num_alloc_vsi; i++)
270                 if (pf->vsi[i] && (pf->vsi[i]->id == id))
271                         return pf->vsi[i];
272
273         return NULL;
274 }
275
276 /**
277  * i40e_service_event_schedule - Schedule the service task to wake up
278  * @pf: board private structure
279  *
280  * If not already scheduled, this puts the task into the work queue
281  **/
282 void i40e_service_event_schedule(struct i40e_pf *pf)
283 {
284         if ((!test_bit(__I40E_DOWN, pf->state) &&
285              !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
286               test_bit(__I40E_RECOVERY_MODE, pf->state))
287                 queue_work(i40e_wq, &pf->service_task);
288 }
289
290 /**
291  * i40e_tx_timeout - Respond to a Tx Hang
292  * @netdev: network interface device structure
293  * @txqueue: queue number timing out
294  *
295  * If any port has noticed a Tx timeout, it is likely that the whole
296  * device is munged, not just the one netdev port, so go for the full
297  * reset.
298  **/
299 static void i40e_tx_timeout(struct net_device *netdev, unsigned int txqueue)
300 {
301         struct i40e_netdev_priv *np = netdev_priv(netdev);
302         struct i40e_vsi *vsi = np->vsi;
303         struct i40e_pf *pf = vsi->back;
304         struct i40e_ring *tx_ring = NULL;
305         unsigned int i;
306         u32 head, val;
307
308         pf->tx_timeout_count++;
309
310         /* with txqueue index, find the tx_ring struct */
311         for (i = 0; i < vsi->num_queue_pairs; i++) {
312                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
313                         if (txqueue ==
314                             vsi->tx_rings[i]->queue_index) {
315                                 tx_ring = vsi->tx_rings[i];
316                                 break;
317                         }
318                 }
319         }
320
321         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
322                 pf->tx_timeout_recovery_level = 1;  /* reset after some time */
323         else if (time_before(jiffies,
324                       (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
325                 return;   /* don't do any new action before the next timeout */
326
327         /* don't kick off another recovery if one is already pending */
328         if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
329                 return;
330
331         if (tx_ring) {
332                 head = i40e_get_head(tx_ring);
333                 /* Read interrupt register */
334                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
335                         val = rd32(&pf->hw,
336                              I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
337                                                 tx_ring->vsi->base_vector - 1));
338                 else
339                         val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
340
341                 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",
342                             vsi->seid, txqueue, tx_ring->next_to_clean,
343                             head, tx_ring->next_to_use,
344                             readl(tx_ring->tail), val);
345         }
346
347         pf->tx_timeout_last_recovery = jiffies;
348         netdev_info(netdev, "tx_timeout recovery level %d, txqueue %d\n",
349                     pf->tx_timeout_recovery_level, txqueue);
350
351         switch (pf->tx_timeout_recovery_level) {
352         case 1:
353                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
354                 break;
355         case 2:
356                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
357                 break;
358         case 3:
359                 set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
360                 break;
361         default:
362                 netdev_err(netdev, "tx_timeout recovery unsuccessful\n");
363                 break;
364         }
365
366         i40e_service_event_schedule(pf);
367         pf->tx_timeout_recovery_level++;
368 }
369
370 /**
371  * i40e_get_vsi_stats_struct - Get System Network Statistics
372  * @vsi: the VSI we care about
373  *
374  * Returns the address of the device statistics structure.
375  * The statistics are actually updated from the service task.
376  **/
377 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
378 {
379         return &vsi->net_stats;
380 }
381
382 /**
383  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
384  * @ring: Tx ring to get statistics from
385  * @stats: statistics entry to be updated
386  **/
387 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
388                                             struct rtnl_link_stats64 *stats)
389 {
390         u64 bytes, packets;
391         unsigned int start;
392
393         do {
394                 start = u64_stats_fetch_begin_irq(&ring->syncp);
395                 packets = ring->stats.packets;
396                 bytes   = ring->stats.bytes;
397         } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
398
399         stats->tx_packets += packets;
400         stats->tx_bytes   += bytes;
401 }
402
403 /**
404  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
405  * @netdev: network interface device structure
406  * @stats: data structure to store statistics
407  *
408  * Returns the address of the device statistics structure.
409  * The statistics are actually updated from the service task.
410  **/
411 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
412                                   struct rtnl_link_stats64 *stats)
413 {
414         struct i40e_netdev_priv *np = netdev_priv(netdev);
415         struct i40e_vsi *vsi = np->vsi;
416         struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
417         struct i40e_ring *ring;
418         int i;
419
420         if (test_bit(__I40E_VSI_DOWN, vsi->state))
421                 return;
422
423         if (!vsi->tx_rings)
424                 return;
425
426         rcu_read_lock();
427         for (i = 0; i < vsi->num_queue_pairs; i++) {
428                 u64 bytes, packets;
429                 unsigned int start;
430
431                 ring = READ_ONCE(vsi->tx_rings[i]);
432                 if (!ring)
433                         continue;
434                 i40e_get_netdev_stats_struct_tx(ring, stats);
435
436                 if (i40e_enabled_xdp_vsi(vsi)) {
437                         ring = READ_ONCE(vsi->xdp_rings[i]);
438                         if (!ring)
439                                 continue;
440                         i40e_get_netdev_stats_struct_tx(ring, stats);
441                 }
442
443                 ring = READ_ONCE(vsi->rx_rings[i]);
444                 if (!ring)
445                         continue;
446                 do {
447                         start   = u64_stats_fetch_begin_irq(&ring->syncp);
448                         packets = ring->stats.packets;
449                         bytes   = ring->stats.bytes;
450                 } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
451
452                 stats->rx_packets += packets;
453                 stats->rx_bytes   += bytes;
454
455         }
456         rcu_read_unlock();
457
458         /* following stats updated by i40e_watchdog_subtask() */
459         stats->multicast        = vsi_stats->multicast;
460         stats->tx_errors        = vsi_stats->tx_errors;
461         stats->tx_dropped       = vsi_stats->tx_dropped;
462         stats->rx_errors        = vsi_stats->rx_errors;
463         stats->rx_dropped       = vsi_stats->rx_dropped;
464         stats->rx_crc_errors    = vsi_stats->rx_crc_errors;
465         stats->rx_length_errors = vsi_stats->rx_length_errors;
466 }
467
468 /**
469  * i40e_vsi_reset_stats - Resets all stats of the given vsi
470  * @vsi: the VSI to have its stats reset
471  **/
472 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
473 {
474         struct rtnl_link_stats64 *ns;
475         int i;
476
477         if (!vsi)
478                 return;
479
480         ns = i40e_get_vsi_stats_struct(vsi);
481         memset(ns, 0, sizeof(*ns));
482         memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
483         memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
484         memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
485         if (vsi->rx_rings && vsi->rx_rings[0]) {
486                 for (i = 0; i < vsi->num_queue_pairs; i++) {
487                         memset(&vsi->rx_rings[i]->stats, 0,
488                                sizeof(vsi->rx_rings[i]->stats));
489                         memset(&vsi->rx_rings[i]->rx_stats, 0,
490                                sizeof(vsi->rx_rings[i]->rx_stats));
491                         memset(&vsi->tx_rings[i]->stats, 0,
492                                sizeof(vsi->tx_rings[i]->stats));
493                         memset(&vsi->tx_rings[i]->tx_stats, 0,
494                                sizeof(vsi->tx_rings[i]->tx_stats));
495                 }
496         }
497         vsi->stat_offsets_loaded = false;
498 }
499
500 /**
501  * i40e_pf_reset_stats - Reset all of the stats for the given PF
502  * @pf: the PF to be reset
503  **/
504 void i40e_pf_reset_stats(struct i40e_pf *pf)
505 {
506         int i;
507
508         memset(&pf->stats, 0, sizeof(pf->stats));
509         memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
510         pf->stat_offsets_loaded = false;
511
512         for (i = 0; i < I40E_MAX_VEB; i++) {
513                 if (pf->veb[i]) {
514                         memset(&pf->veb[i]->stats, 0,
515                                sizeof(pf->veb[i]->stats));
516                         memset(&pf->veb[i]->stats_offsets, 0,
517                                sizeof(pf->veb[i]->stats_offsets));
518                         memset(&pf->veb[i]->tc_stats, 0,
519                                sizeof(pf->veb[i]->tc_stats));
520                         memset(&pf->veb[i]->tc_stats_offsets, 0,
521                                sizeof(pf->veb[i]->tc_stats_offsets));
522                         pf->veb[i]->stat_offsets_loaded = false;
523                 }
524         }
525         pf->hw_csum_rx_error = 0;
526 }
527
528 /**
529  * i40e_stat_update48 - read and update a 48 bit stat from the chip
530  * @hw: ptr to the hardware info
531  * @hireg: the high 32 bit reg to read
532  * @loreg: the low 32 bit reg to read
533  * @offset_loaded: has the initial offset been loaded yet
534  * @offset: ptr to current offset value
535  * @stat: ptr to the stat
536  *
537  * Since the device stats are not reset at PFReset, they likely will not
538  * be zeroed when the driver starts.  We'll save the first values read
539  * and use them as offsets to be subtracted from the raw values in order
540  * to report stats that count from zero.  In the process, we also manage
541  * the potential roll-over.
542  **/
543 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
544                                bool offset_loaded, u64 *offset, u64 *stat)
545 {
546         u64 new_data;
547
548         if (hw->device_id == I40E_DEV_ID_QEMU) {
549                 new_data = rd32(hw, loreg);
550                 new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
551         } else {
552                 new_data = rd64(hw, loreg);
553         }
554         if (!offset_loaded)
555                 *offset = new_data;
556         if (likely(new_data >= *offset))
557                 *stat = new_data - *offset;
558         else
559                 *stat = (new_data + BIT_ULL(48)) - *offset;
560         *stat &= 0xFFFFFFFFFFFFULL;
561 }
562
563 /**
564  * i40e_stat_update32 - read and update a 32 bit stat from the chip
565  * @hw: ptr to the hardware info
566  * @reg: the hw reg to read
567  * @offset_loaded: has the initial offset been loaded yet
568  * @offset: ptr to current offset value
569  * @stat: ptr to the stat
570  **/
571 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
572                                bool offset_loaded, u64 *offset, u64 *stat)
573 {
574         u32 new_data;
575
576         new_data = rd32(hw, reg);
577         if (!offset_loaded)
578                 *offset = new_data;
579         if (likely(new_data >= *offset))
580                 *stat = (u32)(new_data - *offset);
581         else
582                 *stat = (u32)((new_data + BIT_ULL(32)) - *offset);
583 }
584
585 /**
586  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
587  * @hw: ptr to the hardware info
588  * @reg: the hw reg to read and clear
589  * @stat: ptr to the stat
590  **/
591 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
592 {
593         u32 new_data = rd32(hw, reg);
594
595         wr32(hw, reg, 1); /* must write a nonzero value to clear register */
596         *stat += new_data;
597 }
598
599 /**
600  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
601  * @vsi: the VSI to be updated
602  **/
603 void i40e_update_eth_stats(struct i40e_vsi *vsi)
604 {
605         int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
606         struct i40e_pf *pf = vsi->back;
607         struct i40e_hw *hw = &pf->hw;
608         struct i40e_eth_stats *oes;
609         struct i40e_eth_stats *es;     /* device's eth stats */
610
611         es = &vsi->eth_stats;
612         oes = &vsi->eth_stats_offsets;
613
614         /* Gather up the stats that the hw collects */
615         i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
616                            vsi->stat_offsets_loaded,
617                            &oes->tx_errors, &es->tx_errors);
618         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
619                            vsi->stat_offsets_loaded,
620                            &oes->rx_discards, &es->rx_discards);
621         i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
622                            vsi->stat_offsets_loaded,
623                            &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
624
625         i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
626                            I40E_GLV_GORCL(stat_idx),
627                            vsi->stat_offsets_loaded,
628                            &oes->rx_bytes, &es->rx_bytes);
629         i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
630                            I40E_GLV_UPRCL(stat_idx),
631                            vsi->stat_offsets_loaded,
632                            &oes->rx_unicast, &es->rx_unicast);
633         i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
634                            I40E_GLV_MPRCL(stat_idx),
635                            vsi->stat_offsets_loaded,
636                            &oes->rx_multicast, &es->rx_multicast);
637         i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
638                            I40E_GLV_BPRCL(stat_idx),
639                            vsi->stat_offsets_loaded,
640                            &oes->rx_broadcast, &es->rx_broadcast);
641
642         i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
643                            I40E_GLV_GOTCL(stat_idx),
644                            vsi->stat_offsets_loaded,
645                            &oes->tx_bytes, &es->tx_bytes);
646         i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
647                            I40E_GLV_UPTCL(stat_idx),
648                            vsi->stat_offsets_loaded,
649                            &oes->tx_unicast, &es->tx_unicast);
650         i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
651                            I40E_GLV_MPTCL(stat_idx),
652                            vsi->stat_offsets_loaded,
653                            &oes->tx_multicast, &es->tx_multicast);
654         i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
655                            I40E_GLV_BPTCL(stat_idx),
656                            vsi->stat_offsets_loaded,
657                            &oes->tx_broadcast, &es->tx_broadcast);
658         vsi->stat_offsets_loaded = true;
659 }
660
661 /**
662  * i40e_update_veb_stats - Update Switch component statistics
663  * @veb: the VEB being updated
664  **/
665 void i40e_update_veb_stats(struct i40e_veb *veb)
666 {
667         struct i40e_pf *pf = veb->pf;
668         struct i40e_hw *hw = &pf->hw;
669         struct i40e_eth_stats *oes;
670         struct i40e_eth_stats *es;     /* device's eth stats */
671         struct i40e_veb_tc_stats *veb_oes;
672         struct i40e_veb_tc_stats *veb_es;
673         int i, idx = 0;
674
675         idx = veb->stats_idx;
676         es = &veb->stats;
677         oes = &veb->stats_offsets;
678         veb_es = &veb->tc_stats;
679         veb_oes = &veb->tc_stats_offsets;
680
681         /* Gather up the stats that the hw collects */
682         i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
683                            veb->stat_offsets_loaded,
684                            &oes->tx_discards, &es->tx_discards);
685         if (hw->revision_id > 0)
686                 i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
687                                    veb->stat_offsets_loaded,
688                                    &oes->rx_unknown_protocol,
689                                    &es->rx_unknown_protocol);
690         i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
691                            veb->stat_offsets_loaded,
692                            &oes->rx_bytes, &es->rx_bytes);
693         i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
694                            veb->stat_offsets_loaded,
695                            &oes->rx_unicast, &es->rx_unicast);
696         i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
697                            veb->stat_offsets_loaded,
698                            &oes->rx_multicast, &es->rx_multicast);
699         i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
700                            veb->stat_offsets_loaded,
701                            &oes->rx_broadcast, &es->rx_broadcast);
702
703         i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
704                            veb->stat_offsets_loaded,
705                            &oes->tx_bytes, &es->tx_bytes);
706         i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
707                            veb->stat_offsets_loaded,
708                            &oes->tx_unicast, &es->tx_unicast);
709         i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
710                            veb->stat_offsets_loaded,
711                            &oes->tx_multicast, &es->tx_multicast);
712         i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
713                            veb->stat_offsets_loaded,
714                            &oes->tx_broadcast, &es->tx_broadcast);
715         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
716                 i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
717                                    I40E_GLVEBTC_RPCL(i, idx),
718                                    veb->stat_offsets_loaded,
719                                    &veb_oes->tc_rx_packets[i],
720                                    &veb_es->tc_rx_packets[i]);
721                 i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
722                                    I40E_GLVEBTC_RBCL(i, idx),
723                                    veb->stat_offsets_loaded,
724                                    &veb_oes->tc_rx_bytes[i],
725                                    &veb_es->tc_rx_bytes[i]);
726                 i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
727                                    I40E_GLVEBTC_TPCL(i, idx),
728                                    veb->stat_offsets_loaded,
729                                    &veb_oes->tc_tx_packets[i],
730                                    &veb_es->tc_tx_packets[i]);
731                 i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
732                                    I40E_GLVEBTC_TBCL(i, idx),
733                                    veb->stat_offsets_loaded,
734                                    &veb_oes->tc_tx_bytes[i],
735                                    &veb_es->tc_tx_bytes[i]);
736         }
737         veb->stat_offsets_loaded = true;
738 }
739
740 /**
741  * i40e_update_vsi_stats - Update the vsi statistics counters.
742  * @vsi: the VSI to be updated
743  *
744  * There are a few instances where we store the same stat in a
745  * couple of different structs.  This is partly because we have
746  * the netdev stats that need to be filled out, which is slightly
747  * different from the "eth_stats" defined by the chip and used in
748  * VF communications.  We sort it out here.
749  **/
750 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
751 {
752         struct i40e_pf *pf = vsi->back;
753         struct rtnl_link_stats64 *ons;
754         struct rtnl_link_stats64 *ns;   /* netdev stats */
755         struct i40e_eth_stats *oes;
756         struct i40e_eth_stats *es;     /* device's eth stats */
757         u32 tx_restart, tx_busy;
758         struct i40e_ring *p;
759         u32 rx_page, rx_buf;
760         u64 bytes, packets;
761         unsigned int start;
762         u64 tx_linearize;
763         u64 tx_force_wb;
764         u64 rx_p, rx_b;
765         u64 tx_p, tx_b;
766         u16 q;
767
768         if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
769             test_bit(__I40E_CONFIG_BUSY, pf->state))
770                 return;
771
772         ns = i40e_get_vsi_stats_struct(vsi);
773         ons = &vsi->net_stats_offsets;
774         es = &vsi->eth_stats;
775         oes = &vsi->eth_stats_offsets;
776
777         /* Gather up the netdev and vsi stats that the driver collects
778          * on the fly during packet processing
779          */
780         rx_b = rx_p = 0;
781         tx_b = tx_p = 0;
782         tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
783         rx_page = 0;
784         rx_buf = 0;
785         rcu_read_lock();
786         for (q = 0; q < vsi->num_queue_pairs; q++) {
787                 /* locate Tx ring */
788                 p = READ_ONCE(vsi->tx_rings[q]);
789                 if (!p)
790                         continue;
791
792                 do {
793                         start = u64_stats_fetch_begin_irq(&p->syncp);
794                         packets = p->stats.packets;
795                         bytes = p->stats.bytes;
796                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
797                 tx_b += bytes;
798                 tx_p += packets;
799                 tx_restart += p->tx_stats.restart_queue;
800                 tx_busy += p->tx_stats.tx_busy;
801                 tx_linearize += p->tx_stats.tx_linearize;
802                 tx_force_wb += p->tx_stats.tx_force_wb;
803
804                 /* locate Rx ring */
805                 p = READ_ONCE(vsi->rx_rings[q]);
806                 if (!p)
807                         continue;
808
809                 do {
810                         start = u64_stats_fetch_begin_irq(&p->syncp);
811                         packets = p->stats.packets;
812                         bytes = p->stats.bytes;
813                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
814                 rx_b += bytes;
815                 rx_p += packets;
816                 rx_buf += p->rx_stats.alloc_buff_failed;
817                 rx_page += p->rx_stats.alloc_page_failed;
818
819                 if (i40e_enabled_xdp_vsi(vsi)) {
820                         /* locate XDP ring */
821                         p = READ_ONCE(vsi->xdp_rings[q]);
822                         if (!p)
823                                 continue;
824
825                         do {
826                                 start = u64_stats_fetch_begin_irq(&p->syncp);
827                                 packets = p->stats.packets;
828                                 bytes = p->stats.bytes;
829                         } while (u64_stats_fetch_retry_irq(&p->syncp, start));
830                         tx_b += bytes;
831                         tx_p += packets;
832                         tx_restart += p->tx_stats.restart_queue;
833                         tx_busy += p->tx_stats.tx_busy;
834                         tx_linearize += p->tx_stats.tx_linearize;
835                         tx_force_wb += p->tx_stats.tx_force_wb;
836                 }
837         }
838         rcu_read_unlock();
839         vsi->tx_restart = tx_restart;
840         vsi->tx_busy = tx_busy;
841         vsi->tx_linearize = tx_linearize;
842         vsi->tx_force_wb = tx_force_wb;
843         vsi->rx_page_failed = rx_page;
844         vsi->rx_buf_failed = rx_buf;
845
846         ns->rx_packets = rx_p;
847         ns->rx_bytes = rx_b;
848         ns->tx_packets = tx_p;
849         ns->tx_bytes = tx_b;
850
851         /* update netdev stats from eth stats */
852         i40e_update_eth_stats(vsi);
853         ons->tx_errors = oes->tx_errors;
854         ns->tx_errors = es->tx_errors;
855         ons->multicast = oes->rx_multicast;
856         ns->multicast = es->rx_multicast;
857         ons->rx_dropped = oes->rx_discards;
858         ns->rx_dropped = es->rx_discards;
859         ons->tx_dropped = oes->tx_discards;
860         ns->tx_dropped = es->tx_discards;
861
862         /* pull in a couple PF stats if this is the main vsi */
863         if (vsi == pf->vsi[pf->lan_vsi]) {
864                 ns->rx_crc_errors = pf->stats.crc_errors;
865                 ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
866                 ns->rx_length_errors = pf->stats.rx_length_errors;
867         }
868 }
869
870 /**
871  * i40e_update_pf_stats - Update the PF statistics counters.
872  * @pf: the PF to be updated
873  **/
874 static void i40e_update_pf_stats(struct i40e_pf *pf)
875 {
876         struct i40e_hw_port_stats *osd = &pf->stats_offsets;
877         struct i40e_hw_port_stats *nsd = &pf->stats;
878         struct i40e_hw *hw = &pf->hw;
879         u32 val;
880         int i;
881
882         i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
883                            I40E_GLPRT_GORCL(hw->port),
884                            pf->stat_offsets_loaded,
885                            &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
886         i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
887                            I40E_GLPRT_GOTCL(hw->port),
888                            pf->stat_offsets_loaded,
889                            &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
890         i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
891                            pf->stat_offsets_loaded,
892                            &osd->eth.rx_discards,
893                            &nsd->eth.rx_discards);
894         i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
895                            I40E_GLPRT_UPRCL(hw->port),
896                            pf->stat_offsets_loaded,
897                            &osd->eth.rx_unicast,
898                            &nsd->eth.rx_unicast);
899         i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
900                            I40E_GLPRT_MPRCL(hw->port),
901                            pf->stat_offsets_loaded,
902                            &osd->eth.rx_multicast,
903                            &nsd->eth.rx_multicast);
904         i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
905                            I40E_GLPRT_BPRCL(hw->port),
906                            pf->stat_offsets_loaded,
907                            &osd->eth.rx_broadcast,
908                            &nsd->eth.rx_broadcast);
909         i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
910                            I40E_GLPRT_UPTCL(hw->port),
911                            pf->stat_offsets_loaded,
912                            &osd->eth.tx_unicast,
913                            &nsd->eth.tx_unicast);
914         i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
915                            I40E_GLPRT_MPTCL(hw->port),
916                            pf->stat_offsets_loaded,
917                            &osd->eth.tx_multicast,
918                            &nsd->eth.tx_multicast);
919         i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
920                            I40E_GLPRT_BPTCL(hw->port),
921                            pf->stat_offsets_loaded,
922                            &osd->eth.tx_broadcast,
923                            &nsd->eth.tx_broadcast);
924
925         i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
926                            pf->stat_offsets_loaded,
927                            &osd->tx_dropped_link_down,
928                            &nsd->tx_dropped_link_down);
929
930         i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
931                            pf->stat_offsets_loaded,
932                            &osd->crc_errors, &nsd->crc_errors);
933
934         i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
935                            pf->stat_offsets_loaded,
936                            &osd->illegal_bytes, &nsd->illegal_bytes);
937
938         i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
939                            pf->stat_offsets_loaded,
940                            &osd->mac_local_faults,
941                            &nsd->mac_local_faults);
942         i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
943                            pf->stat_offsets_loaded,
944                            &osd->mac_remote_faults,
945                            &nsd->mac_remote_faults);
946
947         i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
948                            pf->stat_offsets_loaded,
949                            &osd->rx_length_errors,
950                            &nsd->rx_length_errors);
951
952         i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
953                            pf->stat_offsets_loaded,
954                            &osd->link_xon_rx, &nsd->link_xon_rx);
955         i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
956                            pf->stat_offsets_loaded,
957                            &osd->link_xon_tx, &nsd->link_xon_tx);
958         i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
959                            pf->stat_offsets_loaded,
960                            &osd->link_xoff_rx, &nsd->link_xoff_rx);
961         i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
962                            pf->stat_offsets_loaded,
963                            &osd->link_xoff_tx, &nsd->link_xoff_tx);
964
965         for (i = 0; i < 8; i++) {
966                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
967                                    pf->stat_offsets_loaded,
968                                    &osd->priority_xoff_rx[i],
969                                    &nsd->priority_xoff_rx[i]);
970                 i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
971                                    pf->stat_offsets_loaded,
972                                    &osd->priority_xon_rx[i],
973                                    &nsd->priority_xon_rx[i]);
974                 i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
975                                    pf->stat_offsets_loaded,
976                                    &osd->priority_xon_tx[i],
977                                    &nsd->priority_xon_tx[i]);
978                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
979                                    pf->stat_offsets_loaded,
980                                    &osd->priority_xoff_tx[i],
981                                    &nsd->priority_xoff_tx[i]);
982                 i40e_stat_update32(hw,
983                                    I40E_GLPRT_RXON2OFFCNT(hw->port, i),
984                                    pf->stat_offsets_loaded,
985                                    &osd->priority_xon_2_xoff[i],
986                                    &nsd->priority_xon_2_xoff[i]);
987         }
988
989         i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
990                            I40E_GLPRT_PRC64L(hw->port),
991                            pf->stat_offsets_loaded,
992                            &osd->rx_size_64, &nsd->rx_size_64);
993         i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
994                            I40E_GLPRT_PRC127L(hw->port),
995                            pf->stat_offsets_loaded,
996                            &osd->rx_size_127, &nsd->rx_size_127);
997         i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
998                            I40E_GLPRT_PRC255L(hw->port),
999                            pf->stat_offsets_loaded,
1000                            &osd->rx_size_255, &nsd->rx_size_255);
1001         i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
1002                            I40E_GLPRT_PRC511L(hw->port),
1003                            pf->stat_offsets_loaded,
1004                            &osd->rx_size_511, &nsd->rx_size_511);
1005         i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1006                            I40E_GLPRT_PRC1023L(hw->port),
1007                            pf->stat_offsets_loaded,
1008                            &osd->rx_size_1023, &nsd->rx_size_1023);
1009         i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1010                            I40E_GLPRT_PRC1522L(hw->port),
1011                            pf->stat_offsets_loaded,
1012                            &osd->rx_size_1522, &nsd->rx_size_1522);
1013         i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1014                            I40E_GLPRT_PRC9522L(hw->port),
1015                            pf->stat_offsets_loaded,
1016                            &osd->rx_size_big, &nsd->rx_size_big);
1017
1018         i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1019                            I40E_GLPRT_PTC64L(hw->port),
1020                            pf->stat_offsets_loaded,
1021                            &osd->tx_size_64, &nsd->tx_size_64);
1022         i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1023                            I40E_GLPRT_PTC127L(hw->port),
1024                            pf->stat_offsets_loaded,
1025                            &osd->tx_size_127, &nsd->tx_size_127);
1026         i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1027                            I40E_GLPRT_PTC255L(hw->port),
1028                            pf->stat_offsets_loaded,
1029                            &osd->tx_size_255, &nsd->tx_size_255);
1030         i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1031                            I40E_GLPRT_PTC511L(hw->port),
1032                            pf->stat_offsets_loaded,
1033                            &osd->tx_size_511, &nsd->tx_size_511);
1034         i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1035                            I40E_GLPRT_PTC1023L(hw->port),
1036                            pf->stat_offsets_loaded,
1037                            &osd->tx_size_1023, &nsd->tx_size_1023);
1038         i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1039                            I40E_GLPRT_PTC1522L(hw->port),
1040                            pf->stat_offsets_loaded,
1041                            &osd->tx_size_1522, &nsd->tx_size_1522);
1042         i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1043                            I40E_GLPRT_PTC9522L(hw->port),
1044                            pf->stat_offsets_loaded,
1045                            &osd->tx_size_big, &nsd->tx_size_big);
1046
1047         i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1048                            pf->stat_offsets_loaded,
1049                            &osd->rx_undersize, &nsd->rx_undersize);
1050         i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1051                            pf->stat_offsets_loaded,
1052                            &osd->rx_fragments, &nsd->rx_fragments);
1053         i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1054                            pf->stat_offsets_loaded,
1055                            &osd->rx_oversize, &nsd->rx_oversize);
1056         i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1057                            pf->stat_offsets_loaded,
1058                            &osd->rx_jabber, &nsd->rx_jabber);
1059
1060         /* FDIR stats */
1061         i40e_stat_update_and_clear32(hw,
1062                         I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1063                         &nsd->fd_atr_match);
1064         i40e_stat_update_and_clear32(hw,
1065                         I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1066                         &nsd->fd_sb_match);
1067         i40e_stat_update_and_clear32(hw,
1068                         I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1069                         &nsd->fd_atr_tunnel_match);
1070
1071         val = rd32(hw, I40E_PRTPM_EEE_STAT);
1072         nsd->tx_lpi_status =
1073                        (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1074                         I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1075         nsd->rx_lpi_status =
1076                        (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1077                         I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1078         i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1079                            pf->stat_offsets_loaded,
1080                            &osd->tx_lpi_count, &nsd->tx_lpi_count);
1081         i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1082                            pf->stat_offsets_loaded,
1083                            &osd->rx_lpi_count, &nsd->rx_lpi_count);
1084
1085         if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1086             !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1087                 nsd->fd_sb_status = true;
1088         else
1089                 nsd->fd_sb_status = false;
1090
1091         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1092             !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1093                 nsd->fd_atr_status = true;
1094         else
1095                 nsd->fd_atr_status = false;
1096
1097         pf->stat_offsets_loaded = true;
1098 }
1099
1100 /**
1101  * i40e_update_stats - Update the various statistics counters.
1102  * @vsi: the VSI to be updated
1103  *
1104  * Update the various stats for this VSI and its related entities.
1105  **/
1106 void i40e_update_stats(struct i40e_vsi *vsi)
1107 {
1108         struct i40e_pf *pf = vsi->back;
1109
1110         if (vsi == pf->vsi[pf->lan_vsi])
1111                 i40e_update_pf_stats(pf);
1112
1113         i40e_update_vsi_stats(vsi);
1114 }
1115
1116 /**
1117  * i40e_count_filters - counts VSI mac filters
1118  * @vsi: the VSI to be searched
1119  *
1120  * Returns count of mac filters
1121  **/
1122 int i40e_count_filters(struct i40e_vsi *vsi)
1123 {
1124         struct i40e_mac_filter *f;
1125         struct hlist_node *h;
1126         int bkt;
1127         int cnt = 0;
1128
1129         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
1130                 ++cnt;
1131
1132         return cnt;
1133 }
1134
1135 /**
1136  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1137  * @vsi: the VSI to be searched
1138  * @macaddr: the MAC address
1139  * @vlan: the vlan
1140  *
1141  * Returns ptr to the filter object or NULL
1142  **/
1143 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1144                                                 const u8 *macaddr, s16 vlan)
1145 {
1146         struct i40e_mac_filter *f;
1147         u64 key;
1148
1149         if (!vsi || !macaddr)
1150                 return NULL;
1151
1152         key = i40e_addr_to_hkey(macaddr);
1153         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1154                 if ((ether_addr_equal(macaddr, f->macaddr)) &&
1155                     (vlan == f->vlan))
1156                         return f;
1157         }
1158         return NULL;
1159 }
1160
1161 /**
1162  * i40e_find_mac - Find a mac addr in the macvlan filters list
1163  * @vsi: the VSI to be searched
1164  * @macaddr: the MAC address we are searching for
1165  *
1166  * Returns the first filter with the provided MAC address or NULL if
1167  * MAC address was not found
1168  **/
1169 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1170 {
1171         struct i40e_mac_filter *f;
1172         u64 key;
1173
1174         if (!vsi || !macaddr)
1175                 return NULL;
1176
1177         key = i40e_addr_to_hkey(macaddr);
1178         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1179                 if ((ether_addr_equal(macaddr, f->macaddr)))
1180                         return f;
1181         }
1182         return NULL;
1183 }
1184
1185 /**
1186  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1187  * @vsi: the VSI to be searched
1188  *
1189  * Returns true if VSI is in vlan mode or false otherwise
1190  **/
1191 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1192 {
1193         /* If we have a PVID, always operate in VLAN mode */
1194         if (vsi->info.pvid)
1195                 return true;
1196
1197         /* We need to operate in VLAN mode whenever we have any filters with
1198          * a VLAN other than I40E_VLAN_ALL. We could check the table each
1199          * time, incurring search cost repeatedly. However, we can notice two
1200          * things:
1201          *
1202          * 1) the only place where we can gain a VLAN filter is in
1203          *    i40e_add_filter.
1204          *
1205          * 2) the only place where filters are actually removed is in
1206          *    i40e_sync_filters_subtask.
1207          *
1208          * Thus, we can simply use a boolean value, has_vlan_filters which we
1209          * will set to true when we add a VLAN filter in i40e_add_filter. Then
1210          * we have to perform the full search after deleting filters in
1211          * i40e_sync_filters_subtask, but we already have to search
1212          * filters here and can perform the check at the same time. This
1213          * results in avoiding embedding a loop for VLAN mode inside another
1214          * loop over all the filters, and should maintain correctness as noted
1215          * above.
1216          */
1217         return vsi->has_vlan_filter;
1218 }
1219
1220 /**
1221  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1222  * @vsi: the VSI to configure
1223  * @tmp_add_list: list of filters ready to be added
1224  * @tmp_del_list: list of filters ready to be deleted
1225  * @vlan_filters: the number of active VLAN filters
1226  *
1227  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1228  * behave as expected. If we have any active VLAN filters remaining or about
1229  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1230  * so that they only match against untagged traffic. If we no longer have any
1231  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1232  * so that they match against both tagged and untagged traffic. In this way,
1233  * we ensure that we correctly receive the desired traffic. This ensures that
1234  * when we have an active VLAN we will receive only untagged traffic and
1235  * traffic matching active VLANs. If we have no active VLANs then we will
1236  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1237  *
1238  * Finally, in a similar fashion, this function also corrects filters when
1239  * there is an active PVID assigned to this VSI.
1240  *
1241  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1242  *
1243  * This function is only expected to be called from within
1244  * i40e_sync_vsi_filters.
1245  *
1246  * NOTE: This function expects to be called while under the
1247  * mac_filter_hash_lock
1248  */
1249 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1250                                          struct hlist_head *tmp_add_list,
1251                                          struct hlist_head *tmp_del_list,
1252                                          int vlan_filters)
1253 {
1254         s16 pvid = le16_to_cpu(vsi->info.pvid);
1255         struct i40e_mac_filter *f, *add_head;
1256         struct i40e_new_mac_filter *new;
1257         struct hlist_node *h;
1258         int bkt, new_vlan;
1259
1260         /* To determine if a particular filter needs to be replaced we
1261          * have the three following conditions:
1262          *
1263          * a) if we have a PVID assigned, then all filters which are
1264          *    not marked as VLAN=PVID must be replaced with filters that
1265          *    are.
1266          * b) otherwise, if we have any active VLANS, all filters
1267          *    which are marked as VLAN=-1 must be replaced with
1268          *    filters marked as VLAN=0
1269          * c) finally, if we do not have any active VLANS, all filters
1270          *    which are marked as VLAN=0 must be replaced with filters
1271          *    marked as VLAN=-1
1272          */
1273
1274         /* Update the filters about to be added in place */
1275         hlist_for_each_entry(new, tmp_add_list, hlist) {
1276                 if (pvid && new->f->vlan != pvid)
1277                         new->f->vlan = pvid;
1278                 else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1279                         new->f->vlan = 0;
1280                 else if (!vlan_filters && new->f->vlan == 0)
1281                         new->f->vlan = I40E_VLAN_ANY;
1282         }
1283
1284         /* Update the remaining active filters */
1285         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1286                 /* Combine the checks for whether a filter needs to be changed
1287                  * and then determine the new VLAN inside the if block, in
1288                  * order to avoid duplicating code for adding the new filter
1289                  * then deleting the old filter.
1290                  */
1291                 if ((pvid && f->vlan != pvid) ||
1292                     (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1293                     (!vlan_filters && f->vlan == 0)) {
1294                         /* Determine the new vlan we will be adding */
1295                         if (pvid)
1296                                 new_vlan = pvid;
1297                         else if (vlan_filters)
1298                                 new_vlan = 0;
1299                         else
1300                                 new_vlan = I40E_VLAN_ANY;
1301
1302                         /* Create the new filter */
1303                         add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1304                         if (!add_head)
1305                                 return -ENOMEM;
1306
1307                         /* Create a temporary i40e_new_mac_filter */
1308                         new = kzalloc(sizeof(*new), GFP_ATOMIC);
1309                         if (!new)
1310                                 return -ENOMEM;
1311
1312                         new->f = add_head;
1313                         new->state = add_head->state;
1314
1315                         /* Add the new filter to the tmp list */
1316                         hlist_add_head(&new->hlist, tmp_add_list);
1317
1318                         /* Put the original filter into the delete list */
1319                         f->state = I40E_FILTER_REMOVE;
1320                         hash_del(&f->hlist);
1321                         hlist_add_head(&f->hlist, tmp_del_list);
1322                 }
1323         }
1324
1325         vsi->has_vlan_filter = !!vlan_filters;
1326
1327         return 0;
1328 }
1329
1330 /**
1331  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1332  * @vsi: the PF Main VSI - inappropriate for any other VSI
1333  * @macaddr: the MAC address
1334  *
1335  * Remove whatever filter the firmware set up so the driver can manage
1336  * its own filtering intelligently.
1337  **/
1338 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1339 {
1340         struct i40e_aqc_remove_macvlan_element_data element;
1341         struct i40e_pf *pf = vsi->back;
1342
1343         /* Only appropriate for the PF main VSI */
1344         if (vsi->type != I40E_VSI_MAIN)
1345                 return;
1346
1347         memset(&element, 0, sizeof(element));
1348         ether_addr_copy(element.mac_addr, macaddr);
1349         element.vlan_tag = 0;
1350         /* Ignore error returns, some firmware does it this way... */
1351         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1352         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1353
1354         memset(&element, 0, sizeof(element));
1355         ether_addr_copy(element.mac_addr, macaddr);
1356         element.vlan_tag = 0;
1357         /* ...and some firmware does it this way. */
1358         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1359                         I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1360         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1361 }
1362
1363 /**
1364  * i40e_add_filter - Add a mac/vlan filter to the VSI
1365  * @vsi: the VSI to be searched
1366  * @macaddr: the MAC address
1367  * @vlan: the vlan
1368  *
1369  * Returns ptr to the filter object or NULL when no memory available.
1370  *
1371  * NOTE: This function is expected to be called with mac_filter_hash_lock
1372  * being held.
1373  **/
1374 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1375                                         const u8 *macaddr, s16 vlan)
1376 {
1377         struct i40e_mac_filter *f;
1378         u64 key;
1379
1380         if (!vsi || !macaddr)
1381                 return NULL;
1382
1383         f = i40e_find_filter(vsi, macaddr, vlan);
1384         if (!f) {
1385                 f = kzalloc(sizeof(*f), GFP_ATOMIC);
1386                 if (!f)
1387                         return NULL;
1388
1389                 /* Update the boolean indicating if we need to function in
1390                  * VLAN mode.
1391                  */
1392                 if (vlan >= 0)
1393                         vsi->has_vlan_filter = true;
1394
1395                 ether_addr_copy(f->macaddr, macaddr);
1396                 f->vlan = vlan;
1397                 f->state = I40E_FILTER_NEW;
1398                 INIT_HLIST_NODE(&f->hlist);
1399
1400                 key = i40e_addr_to_hkey(macaddr);
1401                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
1402
1403                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1404                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1405         }
1406
1407         /* If we're asked to add a filter that has been marked for removal, it
1408          * is safe to simply restore it to active state. __i40e_del_filter
1409          * will have simply deleted any filters which were previously marked
1410          * NEW or FAILED, so if it is currently marked REMOVE it must have
1411          * previously been ACTIVE. Since we haven't yet run the sync filters
1412          * task, just restore this filter to the ACTIVE state so that the
1413          * sync task leaves it in place
1414          */
1415         if (f->state == I40E_FILTER_REMOVE)
1416                 f->state = I40E_FILTER_ACTIVE;
1417
1418         return f;
1419 }
1420
1421 /**
1422  * __i40e_del_filter - Remove a specific filter from the VSI
1423  * @vsi: VSI to remove from
1424  * @f: the filter to remove from the list
1425  *
1426  * This function should be called instead of i40e_del_filter only if you know
1427  * the exact filter you will remove already, such as via i40e_find_filter or
1428  * i40e_find_mac.
1429  *
1430  * NOTE: This function is expected to be called with mac_filter_hash_lock
1431  * being held.
1432  * ANOTHER NOTE: This function MUST be called from within the context of
1433  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1434  * instead of list_for_each_entry().
1435  **/
1436 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1437 {
1438         if (!f)
1439                 return;
1440
1441         /* If the filter was never added to firmware then we can just delete it
1442          * directly and we don't want to set the status to remove or else an
1443          * admin queue command will unnecessarily fire.
1444          */
1445         if ((f->state == I40E_FILTER_FAILED) ||
1446             (f->state == I40E_FILTER_NEW)) {
1447                 hash_del(&f->hlist);
1448                 kfree(f);
1449         } else {
1450                 f->state = I40E_FILTER_REMOVE;
1451         }
1452
1453         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1454         set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1455 }
1456
1457 /**
1458  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1459  * @vsi: the VSI to be searched
1460  * @macaddr: the MAC address
1461  * @vlan: the VLAN
1462  *
1463  * NOTE: This function is expected to be called with mac_filter_hash_lock
1464  * being held.
1465  * ANOTHER NOTE: This function MUST be called from within the context of
1466  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1467  * instead of list_for_each_entry().
1468  **/
1469 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1470 {
1471         struct i40e_mac_filter *f;
1472
1473         if (!vsi || !macaddr)
1474                 return;
1475
1476         f = i40e_find_filter(vsi, macaddr, vlan);
1477         __i40e_del_filter(vsi, f);
1478 }
1479
1480 /**
1481  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1482  * @vsi: the VSI to be searched
1483  * @macaddr: the mac address to be filtered
1484  *
1485  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1486  * go through all the macvlan filters and add a macvlan filter for each
1487  * unique vlan that already exists. If a PVID has been assigned, instead only
1488  * add the macaddr to that VLAN.
1489  *
1490  * Returns last filter added on success, else NULL
1491  **/
1492 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1493                                             const u8 *macaddr)
1494 {
1495         struct i40e_mac_filter *f, *add = NULL;
1496         struct hlist_node *h;
1497         int bkt;
1498
1499         if (vsi->info.pvid)
1500                 return i40e_add_filter(vsi, macaddr,
1501                                        le16_to_cpu(vsi->info.pvid));
1502
1503         if (!i40e_is_vsi_in_vlan(vsi))
1504                 return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1505
1506         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1507                 if (f->state == I40E_FILTER_REMOVE)
1508                         continue;
1509                 add = i40e_add_filter(vsi, macaddr, f->vlan);
1510                 if (!add)
1511                         return NULL;
1512         }
1513
1514         return add;
1515 }
1516
1517 /**
1518  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1519  * @vsi: the VSI to be searched
1520  * @macaddr: the mac address to be removed
1521  *
1522  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1523  * associated with.
1524  *
1525  * Returns 0 for success, or error
1526  **/
1527 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1528 {
1529         struct i40e_mac_filter *f;
1530         struct hlist_node *h;
1531         bool found = false;
1532         int bkt;
1533
1534         lockdep_assert_held(&vsi->mac_filter_hash_lock);
1535         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1536                 if (ether_addr_equal(macaddr, f->macaddr)) {
1537                         __i40e_del_filter(vsi, f);
1538                         found = true;
1539                 }
1540         }
1541
1542         if (found)
1543                 return 0;
1544         else
1545                 return -ENOENT;
1546 }
1547
1548 /**
1549  * i40e_set_mac - NDO callback to set mac address
1550  * @netdev: network interface device structure
1551  * @p: pointer to an address structure
1552  *
1553  * Returns 0 on success, negative on failure
1554  **/
1555 static int i40e_set_mac(struct net_device *netdev, void *p)
1556 {
1557         struct i40e_netdev_priv *np = netdev_priv(netdev);
1558         struct i40e_vsi *vsi = np->vsi;
1559         struct i40e_pf *pf = vsi->back;
1560         struct i40e_hw *hw = &pf->hw;
1561         struct sockaddr *addr = p;
1562
1563         if (!is_valid_ether_addr(addr->sa_data))
1564                 return -EADDRNOTAVAIL;
1565
1566         if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1567                 netdev_info(netdev, "already using mac address %pM\n",
1568                             addr->sa_data);
1569                 return 0;
1570         }
1571
1572         if (test_bit(__I40E_DOWN, pf->state) ||
1573             test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1574                 return -EADDRNOTAVAIL;
1575
1576         if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1577                 netdev_info(netdev, "returning to hw mac address %pM\n",
1578                             hw->mac.addr);
1579         else
1580                 netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1581
1582         /* Copy the address first, so that we avoid a possible race with
1583          * .set_rx_mode().
1584          * - Remove old address from MAC filter
1585          * - Copy new address
1586          * - Add new address to MAC filter
1587          */
1588         spin_lock_bh(&vsi->mac_filter_hash_lock);
1589         i40e_del_mac_filter(vsi, netdev->dev_addr);
1590         ether_addr_copy(netdev->dev_addr, addr->sa_data);
1591         i40e_add_mac_filter(vsi, netdev->dev_addr);
1592         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1593
1594         if (vsi->type == I40E_VSI_MAIN) {
1595                 i40e_status ret;
1596
1597                 ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1598                                                 addr->sa_data, NULL);
1599                 if (ret)
1600                         netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1601                                     i40e_stat_str(hw, ret),
1602                                     i40e_aq_str(hw, hw->aq.asq_last_status));
1603         }
1604
1605         /* schedule our worker thread which will take care of
1606          * applying the new filter changes
1607          */
1608         i40e_service_event_schedule(pf);
1609         return 0;
1610 }
1611
1612 /**
1613  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1614  * @vsi: vsi structure
1615  * @seed: RSS hash seed
1616  * @lut: pointer to lookup table of lut_size
1617  * @lut_size: size of the lookup table
1618  **/
1619 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1620                               u8 *lut, u16 lut_size)
1621 {
1622         struct i40e_pf *pf = vsi->back;
1623         struct i40e_hw *hw = &pf->hw;
1624         int ret = 0;
1625
1626         if (seed) {
1627                 struct i40e_aqc_get_set_rss_key_data *seed_dw =
1628                         (struct i40e_aqc_get_set_rss_key_data *)seed;
1629                 ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1630                 if (ret) {
1631                         dev_info(&pf->pdev->dev,
1632                                  "Cannot set RSS key, err %s aq_err %s\n",
1633                                  i40e_stat_str(hw, ret),
1634                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1635                         return ret;
1636                 }
1637         }
1638         if (lut) {
1639                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
1640
1641                 ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1642                 if (ret) {
1643                         dev_info(&pf->pdev->dev,
1644                                  "Cannot set RSS lut, err %s aq_err %s\n",
1645                                  i40e_stat_str(hw, ret),
1646                                  i40e_aq_str(hw, hw->aq.asq_last_status));
1647                         return ret;
1648                 }
1649         }
1650         return ret;
1651 }
1652
1653 /**
1654  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1655  * @vsi: VSI structure
1656  **/
1657 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1658 {
1659         struct i40e_pf *pf = vsi->back;
1660         u8 seed[I40E_HKEY_ARRAY_SIZE];
1661         u8 *lut;
1662         int ret;
1663
1664         if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1665                 return 0;
1666         if (!vsi->rss_size)
1667                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
1668                                       vsi->num_queue_pairs);
1669         if (!vsi->rss_size)
1670                 return -EINVAL;
1671         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1672         if (!lut)
1673                 return -ENOMEM;
1674
1675         /* Use the user configured hash keys and lookup table if there is one,
1676          * otherwise use default
1677          */
1678         if (vsi->rss_lut_user)
1679                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1680         else
1681                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1682         if (vsi->rss_hkey_user)
1683                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1684         else
1685                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1686         ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1687         kfree(lut);
1688         return ret;
1689 }
1690
1691 /**
1692  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1693  * @vsi: the VSI being configured,
1694  * @ctxt: VSI context structure
1695  * @enabled_tc: number of traffic classes to enable
1696  *
1697  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1698  **/
1699 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1700                                            struct i40e_vsi_context *ctxt,
1701                                            u8 enabled_tc)
1702 {
1703         u16 qcount = 0, max_qcount, qmap, sections = 0;
1704         int i, override_q, pow, num_qps, ret;
1705         u8 netdev_tc = 0, offset = 0;
1706
1707         if (vsi->type != I40E_VSI_MAIN)
1708                 return -EINVAL;
1709         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1710         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1711         vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1712         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1713         num_qps = vsi->mqprio_qopt.qopt.count[0];
1714
1715         /* find the next higher power-of-2 of num queue pairs */
1716         pow = ilog2(num_qps);
1717         if (!is_power_of_2(num_qps))
1718                 pow++;
1719         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1720                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1721
1722         /* Setup queue offset/count for all TCs for given VSI */
1723         max_qcount = vsi->mqprio_qopt.qopt.count[0];
1724         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1725                 /* See if the given TC is enabled for the given VSI */
1726                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1727                         offset = vsi->mqprio_qopt.qopt.offset[i];
1728                         qcount = vsi->mqprio_qopt.qopt.count[i];
1729                         if (qcount > max_qcount)
1730                                 max_qcount = qcount;
1731                         vsi->tc_config.tc_info[i].qoffset = offset;
1732                         vsi->tc_config.tc_info[i].qcount = qcount;
1733                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1734                 } else {
1735                         /* TC is not enabled so set the offset to
1736                          * default queue and allocate one queue
1737                          * for the given TC.
1738                          */
1739                         vsi->tc_config.tc_info[i].qoffset = 0;
1740                         vsi->tc_config.tc_info[i].qcount = 1;
1741                         vsi->tc_config.tc_info[i].netdev_tc = 0;
1742                 }
1743         }
1744
1745         /* Set actual Tx/Rx queue pairs */
1746         vsi->num_queue_pairs = offset + qcount;
1747
1748         /* Setup queue TC[0].qmap for given VSI context */
1749         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1750         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1751         ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1752         ctxt->info.valid_sections |= cpu_to_le16(sections);
1753
1754         /* Reconfigure RSS for main VSI with max queue count */
1755         vsi->rss_size = max_qcount;
1756         ret = i40e_vsi_config_rss(vsi);
1757         if (ret) {
1758                 dev_info(&vsi->back->pdev->dev,
1759                          "Failed to reconfig rss for num_queues (%u)\n",
1760                          max_qcount);
1761                 return ret;
1762         }
1763         vsi->reconfig_rss = true;
1764         dev_dbg(&vsi->back->pdev->dev,
1765                 "Reconfigured rss with num_queues (%u)\n", max_qcount);
1766
1767         /* Find queue count available for channel VSIs and starting offset
1768          * for channel VSIs
1769          */
1770         override_q = vsi->mqprio_qopt.qopt.count[0];
1771         if (override_q && override_q < vsi->num_queue_pairs) {
1772                 vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1773                 vsi->next_base_queue = override_q;
1774         }
1775         return 0;
1776 }
1777
1778 /**
1779  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1780  * @vsi: the VSI being setup
1781  * @ctxt: VSI context structure
1782  * @enabled_tc: Enabled TCs bitmap
1783  * @is_add: True if called before Add VSI
1784  *
1785  * Setup VSI queue mapping for enabled traffic classes.
1786  **/
1787 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
1788                                      struct i40e_vsi_context *ctxt,
1789                                      u8 enabled_tc,
1790                                      bool is_add)
1791 {
1792         struct i40e_pf *pf = vsi->back;
1793         u16 sections = 0;
1794         u8 netdev_tc = 0;
1795         u16 numtc = 1;
1796         u16 qcount;
1797         u8 offset;
1798         u16 qmap;
1799         int i;
1800         u16 num_tc_qps = 0;
1801
1802         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1803         offset = 0;
1804
1805         /* Number of queues per enabled TC */
1806         num_tc_qps = vsi->alloc_queue_pairs;
1807         if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
1808                 /* Find numtc from enabled TC bitmap */
1809                 for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1810                         if (enabled_tc & BIT(i)) /* TC is enabled */
1811                                 numtc++;
1812                 }
1813                 if (!numtc) {
1814                         dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
1815                         numtc = 1;
1816                 }
1817                 num_tc_qps = num_tc_qps / numtc;
1818                 num_tc_qps = min_t(int, num_tc_qps,
1819                                    i40e_pf_get_max_q_per_tc(pf));
1820         }
1821
1822         vsi->tc_config.numtc = numtc;
1823         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1824
1825         /* Do not allow use more TC queue pairs than MSI-X vectors exist */
1826         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1827                 num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
1828
1829         /* Setup queue offset/count for all TCs for given VSI */
1830         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1831                 /* See if the given TC is enabled for the given VSI */
1832                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1833                         /* TC is enabled */
1834                         int pow, num_qps;
1835
1836                         switch (vsi->type) {
1837                         case I40E_VSI_MAIN:
1838                                 if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
1839                                     I40E_FLAG_FD_ATR_ENABLED)) ||
1840                                     vsi->tc_config.enabled_tc != 1) {
1841                                         qcount = min_t(int, pf->alloc_rss_size,
1842                                                        num_tc_qps);
1843                                         break;
1844                                 }
1845                                 fallthrough;
1846                         case I40E_VSI_FDIR:
1847                         case I40E_VSI_SRIOV:
1848                         case I40E_VSI_VMDQ2:
1849                         default:
1850                                 qcount = num_tc_qps;
1851                                 WARN_ON(i != 0);
1852                                 break;
1853                         }
1854                         vsi->tc_config.tc_info[i].qoffset = offset;
1855                         vsi->tc_config.tc_info[i].qcount = qcount;
1856
1857                         /* find the next higher power-of-2 of num queue pairs */
1858                         num_qps = qcount;
1859                         pow = 0;
1860                         while (num_qps && (BIT_ULL(pow) < qcount)) {
1861                                 pow++;
1862                                 num_qps >>= 1;
1863                         }
1864
1865                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1866                         qmap =
1867                             (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1868                             (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1869
1870                         offset += qcount;
1871                 } else {
1872                         /* TC is not enabled so set the offset to
1873                          * default queue and allocate one queue
1874                          * for the given TC.
1875                          */
1876                         vsi->tc_config.tc_info[i].qoffset = 0;
1877                         vsi->tc_config.tc_info[i].qcount = 1;
1878                         vsi->tc_config.tc_info[i].netdev_tc = 0;
1879
1880                         qmap = 0;
1881                 }
1882                 ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
1883         }
1884
1885         /* Set actual Tx/Rx queue pairs */
1886         vsi->num_queue_pairs = offset;
1887         if ((vsi->type == I40E_VSI_MAIN) && (numtc == 1)) {
1888                 if (vsi->req_queue_pairs > 0)
1889                         vsi->num_queue_pairs = vsi->req_queue_pairs;
1890                 else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1891                         vsi->num_queue_pairs = pf->num_lan_msix;
1892         }
1893
1894         /* Scheduler section valid can only be set for ADD VSI */
1895         if (is_add) {
1896                 sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1897
1898                 ctxt->info.up_enable_bits = enabled_tc;
1899         }
1900         if (vsi->type == I40E_VSI_SRIOV) {
1901                 ctxt->info.mapping_flags |=
1902                                      cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
1903                 for (i = 0; i < vsi->num_queue_pairs; i++)
1904                         ctxt->info.queue_mapping[i] =
1905                                                cpu_to_le16(vsi->base_queue + i);
1906         } else {
1907                 ctxt->info.mapping_flags |=
1908                                         cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1909                 ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1910         }
1911         ctxt->info.valid_sections |= cpu_to_le16(sections);
1912 }
1913
1914 /**
1915  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
1916  * @netdev: the netdevice
1917  * @addr: address to add
1918  *
1919  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
1920  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
1921  */
1922 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
1923 {
1924         struct i40e_netdev_priv *np = netdev_priv(netdev);
1925         struct i40e_vsi *vsi = np->vsi;
1926
1927         if (i40e_add_mac_filter(vsi, addr))
1928                 return 0;
1929         else
1930                 return -ENOMEM;
1931 }
1932
1933 /**
1934  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
1935  * @netdev: the netdevice
1936  * @addr: address to add
1937  *
1938  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
1939  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
1940  */
1941 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
1942 {
1943         struct i40e_netdev_priv *np = netdev_priv(netdev);
1944         struct i40e_vsi *vsi = np->vsi;
1945
1946         /* Under some circumstances, we might receive a request to delete
1947          * our own device address from our uc list. Because we store the
1948          * device address in the VSI's MAC/VLAN filter list, we need to ignore
1949          * such requests and not delete our device address from this list.
1950          */
1951         if (ether_addr_equal(addr, netdev->dev_addr))
1952                 return 0;
1953
1954         i40e_del_mac_filter(vsi, addr);
1955
1956         return 0;
1957 }
1958
1959 /**
1960  * i40e_set_rx_mode - NDO callback to set the netdev filters
1961  * @netdev: network interface device structure
1962  **/
1963 static void i40e_set_rx_mode(struct net_device *netdev)
1964 {
1965         struct i40e_netdev_priv *np = netdev_priv(netdev);
1966         struct i40e_vsi *vsi = np->vsi;
1967
1968         spin_lock_bh(&vsi->mac_filter_hash_lock);
1969
1970         __dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
1971         __dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
1972
1973         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1974
1975         /* check for other flag changes */
1976         if (vsi->current_netdev_flags != vsi->netdev->flags) {
1977                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1978                 set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1979         }
1980 }
1981
1982 /**
1983  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
1984  * @vsi: Pointer to VSI struct
1985  * @from: Pointer to list which contains MAC filter entries - changes to
1986  *        those entries needs to be undone.
1987  *
1988  * MAC filter entries from this list were slated for deletion.
1989  **/
1990 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
1991                                          struct hlist_head *from)
1992 {
1993         struct i40e_mac_filter *f;
1994         struct hlist_node *h;
1995
1996         hlist_for_each_entry_safe(f, h, from, hlist) {
1997                 u64 key = i40e_addr_to_hkey(f->macaddr);
1998
1999                 /* Move the element back into MAC filter list*/
2000                 hlist_del(&f->hlist);
2001                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
2002         }
2003 }
2004
2005 /**
2006  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
2007  * @vsi: Pointer to vsi struct
2008  * @from: Pointer to list which contains MAC filter entries - changes to
2009  *        those entries needs to be undone.
2010  *
2011  * MAC filter entries from this list were slated for addition.
2012  **/
2013 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
2014                                          struct hlist_head *from)
2015 {
2016         struct i40e_new_mac_filter *new;
2017         struct hlist_node *h;
2018
2019         hlist_for_each_entry_safe(new, h, from, hlist) {
2020                 /* We can simply free the wrapper structure */
2021                 hlist_del(&new->hlist);
2022                 kfree(new);
2023         }
2024 }
2025
2026 /**
2027  * i40e_next_filter - Get the next non-broadcast filter from a list
2028  * @next: pointer to filter in list
2029  *
2030  * Returns the next non-broadcast filter in the list. Required so that we
2031  * ignore broadcast filters within the list, since these are not handled via
2032  * the normal firmware update path.
2033  */
2034 static
2035 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2036 {
2037         hlist_for_each_entry_continue(next, hlist) {
2038                 if (!is_broadcast_ether_addr(next->f->macaddr))
2039                         return next;
2040         }
2041
2042         return NULL;
2043 }
2044
2045 /**
2046  * i40e_update_filter_state - Update filter state based on return data
2047  * from firmware
2048  * @count: Number of filters added
2049  * @add_list: return data from fw
2050  * @add_head: pointer to first filter in current batch
2051  *
2052  * MAC filter entries from list were slated to be added to device. Returns
2053  * number of successful filters. Note that 0 does NOT mean success!
2054  **/
2055 static int
2056 i40e_update_filter_state(int count,
2057                          struct i40e_aqc_add_macvlan_element_data *add_list,
2058                          struct i40e_new_mac_filter *add_head)
2059 {
2060         int retval = 0;
2061         int i;
2062
2063         for (i = 0; i < count; i++) {
2064                 /* Always check status of each filter. We don't need to check
2065                  * the firmware return status because we pre-set the filter
2066                  * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2067                  * request to the adminq. Thus, if it no longer matches then
2068                  * we know the filter is active.
2069                  */
2070                 if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2071                         add_head->state = I40E_FILTER_FAILED;
2072                 } else {
2073                         add_head->state = I40E_FILTER_ACTIVE;
2074                         retval++;
2075                 }
2076
2077                 add_head = i40e_next_filter(add_head);
2078                 if (!add_head)
2079                         break;
2080         }
2081
2082         return retval;
2083 }
2084
2085 /**
2086  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2087  * @vsi: ptr to the VSI
2088  * @vsi_name: name to display in messages
2089  * @list: the list of filters to send to firmware
2090  * @num_del: the number of filters to delete
2091  * @retval: Set to -EIO on failure to delete
2092  *
2093  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2094  * *retval instead of a return value so that success does not force ret_val to
2095  * be set to 0. This ensures that a sequence of calls to this function
2096  * preserve the previous value of *retval on successful delete.
2097  */
2098 static
2099 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2100                           struct i40e_aqc_remove_macvlan_element_data *list,
2101                           int num_del, int *retval)
2102 {
2103         struct i40e_hw *hw = &vsi->back->hw;
2104         i40e_status aq_ret;
2105         int aq_err;
2106
2107         aq_ret = i40e_aq_remove_macvlan(hw, vsi->seid, list, num_del, NULL);
2108         aq_err = hw->aq.asq_last_status;
2109
2110         /* Explicitly ignore and do not report when firmware returns ENOENT */
2111         if (aq_ret && !(aq_err == I40E_AQ_RC_ENOENT)) {
2112                 *retval = -EIO;
2113                 dev_info(&vsi->back->pdev->dev,
2114                          "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
2115                          vsi_name, i40e_stat_str(hw, aq_ret),
2116                          i40e_aq_str(hw, aq_err));
2117         }
2118 }
2119
2120 /**
2121  * i40e_aqc_add_filters - Request firmware to add a set of filters
2122  * @vsi: ptr to the VSI
2123  * @vsi_name: name to display in messages
2124  * @list: the list of filters to send to firmware
2125  * @add_head: Position in the add hlist
2126  * @num_add: the number of filters to add
2127  *
2128  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2129  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2130  * space for more filters.
2131  */
2132 static
2133 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2134                           struct i40e_aqc_add_macvlan_element_data *list,
2135                           struct i40e_new_mac_filter *add_head,
2136                           int num_add)
2137 {
2138         struct i40e_hw *hw = &vsi->back->hw;
2139         int aq_err, fcnt;
2140
2141         i40e_aq_add_macvlan(hw, vsi->seid, list, num_add, NULL);
2142         aq_err = hw->aq.asq_last_status;
2143         fcnt = i40e_update_filter_state(num_add, list, add_head);
2144
2145         if (fcnt != num_add) {
2146                 if (vsi->type == I40E_VSI_MAIN) {
2147                         set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2148                         dev_warn(&vsi->back->pdev->dev,
2149                                  "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2150                                  i40e_aq_str(hw, aq_err), vsi_name);
2151                 } else if (vsi->type == I40E_VSI_SRIOV ||
2152                            vsi->type == I40E_VSI_VMDQ1 ||
2153                            vsi->type == I40E_VSI_VMDQ2) {
2154                         dev_warn(&vsi->back->pdev->dev,
2155                                  "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2156                                  i40e_aq_str(hw, aq_err), vsi_name, vsi_name);
2157                 } else {
2158                         dev_warn(&vsi->back->pdev->dev,
2159                                  "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2160                                  i40e_aq_str(hw, aq_err), vsi_name, vsi->type);
2161                 }
2162         }
2163 }
2164
2165 /**
2166  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2167  * @vsi: pointer to the VSI
2168  * @vsi_name: the VSI name
2169  * @f: filter data
2170  *
2171  * This function sets or clears the promiscuous broadcast flags for VLAN
2172  * filters in order to properly receive broadcast frames. Assumes that only
2173  * broadcast filters are passed.
2174  *
2175  * Returns status indicating success or failure;
2176  **/
2177 static i40e_status
2178 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2179                           struct i40e_mac_filter *f)
2180 {
2181         bool enable = f->state == I40E_FILTER_NEW;
2182         struct i40e_hw *hw = &vsi->back->hw;
2183         i40e_status aq_ret;
2184
2185         if (f->vlan == I40E_VLAN_ANY) {
2186                 aq_ret = i40e_aq_set_vsi_broadcast(hw,
2187                                                    vsi->seid,
2188                                                    enable,
2189                                                    NULL);
2190         } else {
2191                 aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2192                                                             vsi->seid,
2193                                                             enable,
2194                                                             f->vlan,
2195                                                             NULL);
2196         }
2197
2198         if (aq_ret) {
2199                 set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2200                 dev_warn(&vsi->back->pdev->dev,
2201                          "Error %s, forcing overflow promiscuous on %s\n",
2202                          i40e_aq_str(hw, hw->aq.asq_last_status),
2203                          vsi_name);
2204         }
2205
2206         return aq_ret;
2207 }
2208
2209 /**
2210  * i40e_set_promiscuous - set promiscuous mode
2211  * @pf: board private structure
2212  * @promisc: promisc on or off
2213  *
2214  * There are different ways of setting promiscuous mode on a PF depending on
2215  * what state/environment we're in.  This identifies and sets it appropriately.
2216  * Returns 0 on success.
2217  **/
2218 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2219 {
2220         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2221         struct i40e_hw *hw = &pf->hw;
2222         i40e_status aq_ret;
2223
2224         if (vsi->type == I40E_VSI_MAIN &&
2225             pf->lan_veb != I40E_NO_VEB &&
2226             !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2227                 /* set defport ON for Main VSI instead of true promisc
2228                  * this way we will get all unicast/multicast and VLAN
2229                  * promisc behavior but will not get VF or VMDq traffic
2230                  * replicated on the Main VSI.
2231                  */
2232                 if (promisc)
2233                         aq_ret = i40e_aq_set_default_vsi(hw,
2234                                                          vsi->seid,
2235                                                          NULL);
2236                 else
2237                         aq_ret = i40e_aq_clear_default_vsi(hw,
2238                                                            vsi->seid,
2239                                                            NULL);
2240                 if (aq_ret) {
2241                         dev_info(&pf->pdev->dev,
2242                                  "Set default VSI failed, err %s, aq_err %s\n",
2243                                  i40e_stat_str(hw, aq_ret),
2244                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2245                 }
2246         } else {
2247                 aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2248                                                   hw,
2249                                                   vsi->seid,
2250                                                   promisc, NULL,
2251                                                   true);
2252                 if (aq_ret) {
2253                         dev_info(&pf->pdev->dev,
2254                                  "set unicast promisc failed, err %s, aq_err %s\n",
2255                                  i40e_stat_str(hw, aq_ret),
2256                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2257                 }
2258                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2259                                                   hw,
2260                                                   vsi->seid,
2261                                                   promisc, NULL);
2262                 if (aq_ret) {
2263                         dev_info(&pf->pdev->dev,
2264                                  "set multicast promisc failed, err %s, aq_err %s\n",
2265                                  i40e_stat_str(hw, aq_ret),
2266                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2267                 }
2268         }
2269
2270         if (!aq_ret)
2271                 pf->cur_promisc = promisc;
2272
2273         return aq_ret;
2274 }
2275
2276 /**
2277  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2278  * @vsi: ptr to the VSI
2279  *
2280  * Push any outstanding VSI filter changes through the AdminQ.
2281  *
2282  * Returns 0 or error value
2283  **/
2284 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2285 {
2286         struct hlist_head tmp_add_list, tmp_del_list;
2287         struct i40e_mac_filter *f;
2288         struct i40e_new_mac_filter *new, *add_head = NULL;
2289         struct i40e_hw *hw = &vsi->back->hw;
2290         bool old_overflow, new_overflow;
2291         unsigned int failed_filters = 0;
2292         unsigned int vlan_filters = 0;
2293         char vsi_name[16] = "PF";
2294         int filter_list_len = 0;
2295         i40e_status aq_ret = 0;
2296         u32 changed_flags = 0;
2297         struct hlist_node *h;
2298         struct i40e_pf *pf;
2299         int num_add = 0;
2300         int num_del = 0;
2301         int retval = 0;
2302         u16 cmd_flags;
2303         int list_size;
2304         int bkt;
2305
2306         /* empty array typed pointers, kcalloc later */
2307         struct i40e_aqc_add_macvlan_element_data *add_list;
2308         struct i40e_aqc_remove_macvlan_element_data *del_list;
2309
2310         while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2311                 usleep_range(1000, 2000);
2312         pf = vsi->back;
2313
2314         old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2315
2316         if (vsi->netdev) {
2317                 changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2318                 vsi->current_netdev_flags = vsi->netdev->flags;
2319         }
2320
2321         INIT_HLIST_HEAD(&tmp_add_list);
2322         INIT_HLIST_HEAD(&tmp_del_list);
2323
2324         if (vsi->type == I40E_VSI_SRIOV)
2325                 snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2326         else if (vsi->type != I40E_VSI_MAIN)
2327                 snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2328
2329         if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2330                 vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2331
2332                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2333                 /* Create a list of filters to delete. */
2334                 hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2335                         if (f->state == I40E_FILTER_REMOVE) {
2336                                 /* Move the element into temporary del_list */
2337                                 hash_del(&f->hlist);
2338                                 hlist_add_head(&f->hlist, &tmp_del_list);
2339
2340                                 /* Avoid counting removed filters */
2341                                 continue;
2342                         }
2343                         if (f->state == I40E_FILTER_NEW) {
2344                                 /* Create a temporary i40e_new_mac_filter */
2345                                 new = kzalloc(sizeof(*new), GFP_ATOMIC);
2346                                 if (!new)
2347                                         goto err_no_memory_locked;
2348
2349                                 /* Store pointer to the real filter */
2350                                 new->f = f;
2351                                 new->state = f->state;
2352
2353                                 /* Add it to the hash list */
2354                                 hlist_add_head(&new->hlist, &tmp_add_list);
2355                         }
2356
2357                         /* Count the number of active (current and new) VLAN
2358                          * filters we have now. Does not count filters which
2359                          * are marked for deletion.
2360                          */
2361                         if (f->vlan > 0)
2362                                 vlan_filters++;
2363                 }
2364
2365                 retval = i40e_correct_mac_vlan_filters(vsi,
2366                                                        &tmp_add_list,
2367                                                        &tmp_del_list,
2368                                                        vlan_filters);
2369                 if (retval)
2370                         goto err_no_memory_locked;
2371
2372                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2373         }
2374
2375         /* Now process 'del_list' outside the lock */
2376         if (!hlist_empty(&tmp_del_list)) {
2377                 filter_list_len = hw->aq.asq_buf_size /
2378                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2379                 list_size = filter_list_len *
2380                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2381                 del_list = kzalloc(list_size, GFP_ATOMIC);
2382                 if (!del_list)
2383                         goto err_no_memory;
2384
2385                 hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2386                         cmd_flags = 0;
2387
2388                         /* handle broadcast filters by updating the broadcast
2389                          * promiscuous flag and release filter list.
2390                          */
2391                         if (is_broadcast_ether_addr(f->macaddr)) {
2392                                 i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2393
2394                                 hlist_del(&f->hlist);
2395                                 kfree(f);
2396                                 continue;
2397                         }
2398
2399                         /* add to delete list */
2400                         ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2401                         if (f->vlan == I40E_VLAN_ANY) {
2402                                 del_list[num_del].vlan_tag = 0;
2403                                 cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2404                         } else {
2405                                 del_list[num_del].vlan_tag =
2406                                         cpu_to_le16((u16)(f->vlan));
2407                         }
2408
2409                         cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2410                         del_list[num_del].flags = cmd_flags;
2411                         num_del++;
2412
2413                         /* flush a full buffer */
2414                         if (num_del == filter_list_len) {
2415                                 i40e_aqc_del_filters(vsi, vsi_name, del_list,
2416                                                      num_del, &retval);
2417                                 memset(del_list, 0, list_size);
2418                                 num_del = 0;
2419                         }
2420                         /* Release memory for MAC filter entries which were
2421                          * synced up with HW.
2422                          */
2423                         hlist_del(&f->hlist);
2424                         kfree(f);
2425                 }
2426
2427                 if (num_del) {
2428                         i40e_aqc_del_filters(vsi, vsi_name, del_list,
2429                                              num_del, &retval);
2430                 }
2431
2432                 kfree(del_list);
2433                 del_list = NULL;
2434         }
2435
2436         if (!hlist_empty(&tmp_add_list)) {
2437                 /* Do all the adds now. */
2438                 filter_list_len = hw->aq.asq_buf_size /
2439                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2440                 list_size = filter_list_len *
2441                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2442                 add_list = kzalloc(list_size, GFP_ATOMIC);
2443                 if (!add_list)
2444                         goto err_no_memory;
2445
2446                 num_add = 0;
2447                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2448                         /* handle broadcast filters by updating the broadcast
2449                          * promiscuous flag instead of adding a MAC filter.
2450                          */
2451                         if (is_broadcast_ether_addr(new->f->macaddr)) {
2452                                 if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2453                                                               new->f))
2454                                         new->state = I40E_FILTER_FAILED;
2455                                 else
2456                                         new->state = I40E_FILTER_ACTIVE;
2457                                 continue;
2458                         }
2459
2460                         /* add to add array */
2461                         if (num_add == 0)
2462                                 add_head = new;
2463                         cmd_flags = 0;
2464                         ether_addr_copy(add_list[num_add].mac_addr,
2465                                         new->f->macaddr);
2466                         if (new->f->vlan == I40E_VLAN_ANY) {
2467                                 add_list[num_add].vlan_tag = 0;
2468                                 cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2469                         } else {
2470                                 add_list[num_add].vlan_tag =
2471                                         cpu_to_le16((u16)(new->f->vlan));
2472                         }
2473                         add_list[num_add].queue_number = 0;
2474                         /* set invalid match method for later detection */
2475                         add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2476                         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2477                         add_list[num_add].flags = cpu_to_le16(cmd_flags);
2478                         num_add++;
2479
2480                         /* flush a full buffer */
2481                         if (num_add == filter_list_len) {
2482                                 i40e_aqc_add_filters(vsi, vsi_name, add_list,
2483                                                      add_head, num_add);
2484                                 memset(add_list, 0, list_size);
2485                                 num_add = 0;
2486                         }
2487                 }
2488                 if (num_add) {
2489                         i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2490                                              num_add);
2491                 }
2492                 /* Now move all of the filters from the temp add list back to
2493                  * the VSI's list.
2494                  */
2495                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2496                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2497                         /* Only update the state if we're still NEW */
2498                         if (new->f->state == I40E_FILTER_NEW)
2499                                 new->f->state = new->state;
2500                         hlist_del(&new->hlist);
2501                         kfree(new);
2502                 }
2503                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2504                 kfree(add_list);
2505                 add_list = NULL;
2506         }
2507
2508         /* Determine the number of active and failed filters. */
2509         spin_lock_bh(&vsi->mac_filter_hash_lock);
2510         vsi->active_filters = 0;
2511         hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2512                 if (f->state == I40E_FILTER_ACTIVE)
2513                         vsi->active_filters++;
2514                 else if (f->state == I40E_FILTER_FAILED)
2515                         failed_filters++;
2516         }
2517         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2518
2519         /* Check if we are able to exit overflow promiscuous mode. We can
2520          * safely exit if we didn't just enter, we no longer have any failed
2521          * filters, and we have reduced filters below the threshold value.
2522          */
2523         if (old_overflow && !failed_filters &&
2524             vsi->active_filters < vsi->promisc_threshold) {
2525                 dev_info(&pf->pdev->dev,
2526                          "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2527                          vsi_name);
2528                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2529                 vsi->promisc_threshold = 0;
2530         }
2531
2532         /* if the VF is not trusted do not do promisc */
2533         if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2534                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2535                 goto out;
2536         }
2537
2538         new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2539
2540         /* If we are entering overflow promiscuous, we need to calculate a new
2541          * threshold for when we are safe to exit
2542          */
2543         if (!old_overflow && new_overflow)
2544                 vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2545
2546         /* check for changes in promiscuous modes */
2547         if (changed_flags & IFF_ALLMULTI) {
2548                 bool cur_multipromisc;
2549
2550                 cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2551                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2552                                                                vsi->seid,
2553                                                                cur_multipromisc,
2554                                                                NULL);
2555                 if (aq_ret) {
2556                         retval = i40e_aq_rc_to_posix(aq_ret,
2557                                                      hw->aq.asq_last_status);
2558                         dev_info(&pf->pdev->dev,
2559                                  "set multi promisc failed on %s, err %s aq_err %s\n",
2560                                  vsi_name,
2561                                  i40e_stat_str(hw, aq_ret),
2562                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2563                 } else {
2564                         dev_info(&pf->pdev->dev, "%s allmulti mode.\n",
2565                                  cur_multipromisc ? "entering" : "leaving");
2566                 }
2567         }
2568
2569         if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2570                 bool cur_promisc;
2571
2572                 cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2573                                new_overflow);
2574                 aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2575                 if (aq_ret) {
2576                         retval = i40e_aq_rc_to_posix(aq_ret,
2577                                                      hw->aq.asq_last_status);
2578                         dev_info(&pf->pdev->dev,
2579                                  "Setting promiscuous %s failed on %s, err %s aq_err %s\n",
2580                                  cur_promisc ? "on" : "off",
2581                                  vsi_name,
2582                                  i40e_stat_str(hw, aq_ret),
2583                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2584                 }
2585         }
2586 out:
2587         /* if something went wrong then set the changed flag so we try again */
2588         if (retval)
2589                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2590
2591         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2592         return retval;
2593
2594 err_no_memory:
2595         /* Restore elements on the temporary add and delete lists */
2596         spin_lock_bh(&vsi->mac_filter_hash_lock);
2597 err_no_memory_locked:
2598         i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2599         i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2600         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2601
2602         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2603         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2604         return -ENOMEM;
2605 }
2606
2607 /**
2608  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2609  * @pf: board private structure
2610  **/
2611 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2612 {
2613         int v;
2614
2615         if (!pf)
2616                 return;
2617         if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2618                 return;
2619         if (test_bit(__I40E_VF_DISABLE, pf->state)) {
2620                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
2621                 return;
2622         }
2623
2624         for (v = 0; v < pf->num_alloc_vsi; v++) {
2625                 if (pf->vsi[v] &&
2626                     (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED)) {
2627                         int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2628
2629                         if (ret) {
2630                                 /* come back and try again later */
2631                                 set_bit(__I40E_MACVLAN_SYNC_PENDING,
2632                                         pf->state);
2633                                 break;
2634                         }
2635                 }
2636         }
2637 }
2638
2639 /**
2640  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2641  * @vsi: the vsi
2642  **/
2643 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2644 {
2645         if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2646                 return I40E_RXBUFFER_2048;
2647         else
2648                 return I40E_RXBUFFER_3072;
2649 }
2650
2651 /**
2652  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2653  * @netdev: network interface device structure
2654  * @new_mtu: new value for maximum frame size
2655  *
2656  * Returns 0 on success, negative on failure
2657  **/
2658 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2659 {
2660         struct i40e_netdev_priv *np = netdev_priv(netdev);
2661         struct i40e_vsi *vsi = np->vsi;
2662         struct i40e_pf *pf = vsi->back;
2663
2664         if (i40e_enabled_xdp_vsi(vsi)) {
2665                 int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2666
2667                 if (frame_size > i40e_max_xdp_frame_size(vsi))
2668                         return -EINVAL;
2669         }
2670
2671         netdev_dbg(netdev, "changing MTU from %d to %d\n",
2672                    netdev->mtu, new_mtu);
2673         netdev->mtu = new_mtu;
2674         if (netif_running(netdev))
2675                 i40e_vsi_reinit_locked(vsi);
2676         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2677         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2678         return 0;
2679 }
2680
2681 /**
2682  * i40e_ioctl - Access the hwtstamp interface
2683  * @netdev: network interface device structure
2684  * @ifr: interface request data
2685  * @cmd: ioctl command
2686  **/
2687 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2688 {
2689         struct i40e_netdev_priv *np = netdev_priv(netdev);
2690         struct i40e_pf *pf = np->vsi->back;
2691
2692         switch (cmd) {
2693         case SIOCGHWTSTAMP:
2694                 return i40e_ptp_get_ts_config(pf, ifr);
2695         case SIOCSHWTSTAMP:
2696                 return i40e_ptp_set_ts_config(pf, ifr);
2697         default:
2698                 return -EOPNOTSUPP;
2699         }
2700 }
2701
2702 /**
2703  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2704  * @vsi: the vsi being adjusted
2705  **/
2706 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2707 {
2708         struct i40e_vsi_context ctxt;
2709         i40e_status ret;
2710
2711         /* Don't modify stripping options if a port VLAN is active */
2712         if (vsi->info.pvid)
2713                 return;
2714
2715         if ((vsi->info.valid_sections &
2716              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2717             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2718                 return;  /* already enabled */
2719
2720         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2721         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2722                                     I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2723
2724         ctxt.seid = vsi->seid;
2725         ctxt.info = vsi->info;
2726         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2727         if (ret) {
2728                 dev_info(&vsi->back->pdev->dev,
2729                          "update vlan stripping failed, err %s aq_err %s\n",
2730                          i40e_stat_str(&vsi->back->hw, ret),
2731                          i40e_aq_str(&vsi->back->hw,
2732                                      vsi->back->hw.aq.asq_last_status));
2733         }
2734 }
2735
2736 /**
2737  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2738  * @vsi: the vsi being adjusted
2739  **/
2740 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2741 {
2742         struct i40e_vsi_context ctxt;
2743         i40e_status ret;
2744
2745         /* Don't modify stripping options if a port VLAN is active */
2746         if (vsi->info.pvid)
2747                 return;
2748
2749         if ((vsi->info.valid_sections &
2750              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2751             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
2752              I40E_AQ_VSI_PVLAN_EMOD_MASK))
2753                 return;  /* already disabled */
2754
2755         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2756         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2757                                     I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2758
2759         ctxt.seid = vsi->seid;
2760         ctxt.info = vsi->info;
2761         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2762         if (ret) {
2763                 dev_info(&vsi->back->pdev->dev,
2764                          "update vlan stripping failed, err %s aq_err %s\n",
2765                          i40e_stat_str(&vsi->back->hw, ret),
2766                          i40e_aq_str(&vsi->back->hw,
2767                                      vsi->back->hw.aq.asq_last_status));
2768         }
2769 }
2770
2771 /**
2772  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
2773  * @vsi: the vsi being configured
2774  * @vid: vlan id to be added (0 = untagged only , -1 = any)
2775  *
2776  * This is a helper function for adding a new MAC/VLAN filter with the
2777  * specified VLAN for each existing MAC address already in the hash table.
2778  * This function does *not* perform any accounting to update filters based on
2779  * VLAN mode.
2780  *
2781  * NOTE: this function expects to be called while under the
2782  * mac_filter_hash_lock
2783  **/
2784 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2785 {
2786         struct i40e_mac_filter *f, *add_f;
2787         struct hlist_node *h;
2788         int bkt;
2789
2790         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2791                 if (f->state == I40E_FILTER_REMOVE)
2792                         continue;
2793                 add_f = i40e_add_filter(vsi, f->macaddr, vid);
2794                 if (!add_f) {
2795                         dev_info(&vsi->back->pdev->dev,
2796                                  "Could not add vlan filter %d for %pM\n",
2797                                  vid, f->macaddr);
2798                         return -ENOMEM;
2799                 }
2800         }
2801
2802         return 0;
2803 }
2804
2805 /**
2806  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
2807  * @vsi: the VSI being configured
2808  * @vid: VLAN id to be added
2809  **/
2810 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
2811 {
2812         int err;
2813
2814         if (vsi->info.pvid)
2815                 return -EINVAL;
2816
2817         /* The network stack will attempt to add VID=0, with the intention to
2818          * receive priority tagged packets with a VLAN of 0. Our HW receives
2819          * these packets by default when configured to receive untagged
2820          * packets, so we don't need to add a filter for this case.
2821          * Additionally, HW interprets adding a VID=0 filter as meaning to
2822          * receive *only* tagged traffic and stops receiving untagged traffic.
2823          * Thus, we do not want to actually add a filter for VID=0
2824          */
2825         if (!vid)
2826                 return 0;
2827
2828         /* Locked once because all functions invoked below iterates list*/
2829         spin_lock_bh(&vsi->mac_filter_hash_lock);
2830         err = i40e_add_vlan_all_mac(vsi, vid);
2831         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2832         if (err)
2833                 return err;
2834
2835         /* schedule our worker thread which will take care of
2836          * applying the new filter changes
2837          */
2838         i40e_service_event_schedule(vsi->back);
2839         return 0;
2840 }
2841
2842 /**
2843  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
2844  * @vsi: the vsi being configured
2845  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
2846  *
2847  * This function should be used to remove all VLAN filters which match the
2848  * given VID. It does not schedule the service event and does not take the
2849  * mac_filter_hash_lock so it may be combined with other operations under
2850  * a single invocation of the mac_filter_hash_lock.
2851  *
2852  * NOTE: this function expects to be called while under the
2853  * mac_filter_hash_lock
2854  */
2855 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2856 {
2857         struct i40e_mac_filter *f;
2858         struct hlist_node *h;
2859         int bkt;
2860
2861         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2862                 if (f->vlan == vid)
2863                         __i40e_del_filter(vsi, f);
2864         }
2865 }
2866
2867 /**
2868  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
2869  * @vsi: the VSI being configured
2870  * @vid: VLAN id to be removed
2871  **/
2872 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
2873 {
2874         if (!vid || vsi->info.pvid)
2875                 return;
2876
2877         spin_lock_bh(&vsi->mac_filter_hash_lock);
2878         i40e_rm_vlan_all_mac(vsi, vid);
2879         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2880
2881         /* schedule our worker thread which will take care of
2882          * applying the new filter changes
2883          */
2884         i40e_service_event_schedule(vsi->back);
2885 }
2886
2887 /**
2888  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
2889  * @netdev: network interface to be adjusted
2890  * @proto: unused protocol value
2891  * @vid: vlan id to be added
2892  *
2893  * net_device_ops implementation for adding vlan ids
2894  **/
2895 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
2896                                 __always_unused __be16 proto, u16 vid)
2897 {
2898         struct i40e_netdev_priv *np = netdev_priv(netdev);
2899         struct i40e_vsi *vsi = np->vsi;
2900         int ret = 0;
2901
2902         if (vid >= VLAN_N_VID)
2903                 return -EINVAL;
2904
2905         ret = i40e_vsi_add_vlan(vsi, vid);
2906         if (!ret)
2907                 set_bit(vid, vsi->active_vlans);
2908
2909         return ret;
2910 }
2911
2912 /**
2913  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
2914  * @netdev: network interface to be adjusted
2915  * @proto: unused protocol value
2916  * @vid: vlan id to be added
2917  **/
2918 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
2919                                     __always_unused __be16 proto, u16 vid)
2920 {
2921         struct i40e_netdev_priv *np = netdev_priv(netdev);
2922         struct i40e_vsi *vsi = np->vsi;
2923
2924         if (vid >= VLAN_N_VID)
2925                 return;
2926         set_bit(vid, vsi->active_vlans);
2927 }
2928
2929 /**
2930  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
2931  * @netdev: network interface to be adjusted
2932  * @proto: unused protocol value
2933  * @vid: vlan id to be removed
2934  *
2935  * net_device_ops implementation for removing vlan ids
2936  **/
2937 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
2938                                  __always_unused __be16 proto, u16 vid)
2939 {
2940         struct i40e_netdev_priv *np = netdev_priv(netdev);
2941         struct i40e_vsi *vsi = np->vsi;
2942
2943         /* return code is ignored as there is nothing a user
2944          * can do about failure to remove and a log message was
2945          * already printed from the other function
2946          */
2947         i40e_vsi_kill_vlan(vsi, vid);
2948
2949         clear_bit(vid, vsi->active_vlans);
2950
2951         return 0;
2952 }
2953
2954 /**
2955  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
2956  * @vsi: the vsi being brought back up
2957  **/
2958 static void i40e_restore_vlan(struct i40e_vsi *vsi)
2959 {
2960         u16 vid;
2961
2962         if (!vsi->netdev)
2963                 return;
2964
2965         if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
2966                 i40e_vlan_stripping_enable(vsi);
2967         else
2968                 i40e_vlan_stripping_disable(vsi);
2969
2970         for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
2971                 i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
2972                                         vid);
2973 }
2974
2975 /**
2976  * i40e_vsi_add_pvid - Add pvid for the VSI
2977  * @vsi: the vsi being adjusted
2978  * @vid: the vlan id to set as a PVID
2979  **/
2980 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
2981 {
2982         struct i40e_vsi_context ctxt;
2983         i40e_status ret;
2984
2985         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2986         vsi->info.pvid = cpu_to_le16(vid);
2987         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
2988                                     I40E_AQ_VSI_PVLAN_INSERT_PVID |
2989                                     I40E_AQ_VSI_PVLAN_EMOD_STR;
2990
2991         ctxt.seid = vsi->seid;
2992         ctxt.info = vsi->info;
2993         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2994         if (ret) {
2995                 dev_info(&vsi->back->pdev->dev,
2996                          "add pvid failed, err %s aq_err %s\n",
2997                          i40e_stat_str(&vsi->back->hw, ret),
2998                          i40e_aq_str(&vsi->back->hw,
2999                                      vsi->back->hw.aq.asq_last_status));
3000                 return -ENOENT;
3001         }
3002
3003         return 0;
3004 }
3005
3006 /**
3007  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
3008  * @vsi: the vsi being adjusted
3009  *
3010  * Just use the vlan_rx_register() service to put it back to normal
3011  **/
3012 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
3013 {
3014         vsi->info.pvid = 0;
3015
3016         i40e_vlan_stripping_disable(vsi);
3017 }
3018
3019 /**
3020  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
3021  * @vsi: ptr to the VSI
3022  *
3023  * If this function returns with an error, then it's possible one or
3024  * more of the rings is populated (while the rest are not).  It is the
3025  * callers duty to clean those orphaned rings.
3026  *
3027  * Return 0 on success, negative on failure
3028  **/
3029 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3030 {
3031         int i, err = 0;
3032
3033         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3034                 err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3035
3036         if (!i40e_enabled_xdp_vsi(vsi))
3037                 return err;
3038
3039         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3040                 err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3041
3042         return err;
3043 }
3044
3045 /**
3046  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3047  * @vsi: ptr to the VSI
3048  *
3049  * Free VSI's transmit software resources
3050  **/
3051 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3052 {
3053         int i;
3054
3055         if (vsi->tx_rings) {
3056                 for (i = 0; i < vsi->num_queue_pairs; i++)
3057                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3058                                 i40e_free_tx_resources(vsi->tx_rings[i]);
3059         }
3060
3061         if (vsi->xdp_rings) {
3062                 for (i = 0; i < vsi->num_queue_pairs; i++)
3063                         if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3064                                 i40e_free_tx_resources(vsi->xdp_rings[i]);
3065         }
3066 }
3067
3068 /**
3069  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3070  * @vsi: ptr to the VSI
3071  *
3072  * If this function returns with an error, then it's possible one or
3073  * more of the rings is populated (while the rest are not).  It is the
3074  * callers duty to clean those orphaned rings.
3075  *
3076  * Return 0 on success, negative on failure
3077  **/
3078 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3079 {
3080         int i, err = 0;
3081
3082         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3083                 err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3084         return err;
3085 }
3086
3087 /**
3088  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3089  * @vsi: ptr to the VSI
3090  *
3091  * Free all receive software resources
3092  **/
3093 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3094 {
3095         int i;
3096
3097         if (!vsi->rx_rings)
3098                 return;
3099
3100         for (i = 0; i < vsi->num_queue_pairs; i++)
3101                 if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3102                         i40e_free_rx_resources(vsi->rx_rings[i]);
3103 }
3104
3105 /**
3106  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3107  * @ring: The Tx ring to configure
3108  *
3109  * This enables/disables XPS for a given Tx descriptor ring
3110  * based on the TCs enabled for the VSI that ring belongs to.
3111  **/
3112 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3113 {
3114         int cpu;
3115
3116         if (!ring->q_vector || !ring->netdev || ring->ch)
3117                 return;
3118
3119         /* We only initialize XPS once, so as not to overwrite user settings */
3120         if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3121                 return;
3122
3123         cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3124         netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3125                             ring->queue_index);
3126 }
3127
3128 /**
3129  * i40e_xsk_pool - Retrieve the AF_XDP buffer pool if XDP and ZC is enabled
3130  * @ring: The Tx or Rx ring
3131  *
3132  * Returns the AF_XDP buffer pool or NULL.
3133  **/
3134 static struct xsk_buff_pool *i40e_xsk_pool(struct i40e_ring *ring)
3135 {
3136         bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3137         int qid = ring->queue_index;
3138
3139         if (ring_is_xdp(ring))
3140                 qid -= ring->vsi->alloc_queue_pairs;
3141
3142         if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3143                 return NULL;
3144
3145         return xsk_get_pool_from_qid(ring->vsi->netdev, qid);
3146 }
3147
3148 /**
3149  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3150  * @ring: The Tx ring to configure
3151  *
3152  * Configure the Tx descriptor ring in the HMC context.
3153  **/
3154 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3155 {
3156         struct i40e_vsi *vsi = ring->vsi;
3157         u16 pf_q = vsi->base_queue + ring->queue_index;
3158         struct i40e_hw *hw = &vsi->back->hw;
3159         struct i40e_hmc_obj_txq tx_ctx;
3160         i40e_status err = 0;
3161         u32 qtx_ctl = 0;
3162
3163         if (ring_is_xdp(ring))
3164                 ring->xsk_pool = i40e_xsk_pool(ring);
3165
3166         /* some ATR related tx ring init */
3167         if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3168                 ring->atr_sample_rate = vsi->back->atr_sample_rate;
3169                 ring->atr_count = 0;
3170         } else {
3171                 ring->atr_sample_rate = 0;
3172         }
3173
3174         /* configure XPS */
3175         i40e_config_xps_tx_ring(ring);
3176
3177         /* clear the context structure first */
3178         memset(&tx_ctx, 0, sizeof(tx_ctx));
3179
3180         tx_ctx.new_context = 1;
3181         tx_ctx.base = (ring->dma / 128);
3182         tx_ctx.qlen = ring->count;
3183         tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3184                                                I40E_FLAG_FD_ATR_ENABLED));
3185         tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3186         /* FDIR VSI tx ring can still use RS bit and writebacks */
3187         if (vsi->type != I40E_VSI_FDIR)
3188                 tx_ctx.head_wb_ena = 1;
3189         tx_ctx.head_wb_addr = ring->dma +
3190                               (ring->count * sizeof(struct i40e_tx_desc));
3191
3192         /* As part of VSI creation/update, FW allocates certain
3193          * Tx arbitration queue sets for each TC enabled for
3194          * the VSI. The FW returns the handles to these queue
3195          * sets as part of the response buffer to Add VSI,
3196          * Update VSI, etc. AQ commands. It is expected that
3197          * these queue set handles be associated with the Tx
3198          * queues by the driver as part of the TX queue context
3199          * initialization. This has to be done regardless of
3200          * DCB as by default everything is mapped to TC0.
3201          */
3202
3203         if (ring->ch)
3204                 tx_ctx.rdylist =
3205                         le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3206
3207         else
3208                 tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3209
3210         tx_ctx.rdylist_act = 0;
3211
3212         /* clear the context in the HMC */
3213         err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3214         if (err) {
3215                 dev_info(&vsi->back->pdev->dev,
3216                          "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3217                          ring->queue_index, pf_q, err);
3218                 return -ENOMEM;
3219         }
3220
3221         /* set the context in the HMC */
3222         err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3223         if (err) {
3224                 dev_info(&vsi->back->pdev->dev,
3225                          "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3226                          ring->queue_index, pf_q, err);
3227                 return -ENOMEM;
3228         }
3229
3230         /* Now associate this queue with this PCI function */
3231         if (ring->ch) {
3232                 if (ring->ch->type == I40E_VSI_VMDQ2)
3233                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3234                 else
3235                         return -EINVAL;
3236
3237                 qtx_ctl |= (ring->ch->vsi_number <<
3238                             I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3239                             I40E_QTX_CTL_VFVM_INDX_MASK;
3240         } else {
3241                 if (vsi->type == I40E_VSI_VMDQ2) {
3242                         qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3243                         qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3244                                     I40E_QTX_CTL_VFVM_INDX_MASK;
3245                 } else {
3246                         qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3247                 }
3248         }
3249
3250         qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3251                     I40E_QTX_CTL_PF_INDX_MASK);
3252         wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3253         i40e_flush(hw);
3254
3255         /* cache tail off for easier writes later */
3256         ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3257
3258         return 0;
3259 }
3260
3261 /**
3262  * i40e_rx_offset - Return expected offset into page to access data
3263  * @rx_ring: Ring we are requesting offset of
3264  *
3265  * Returns the offset value for ring into the data buffer.
3266  */
3267 static unsigned int i40e_rx_offset(struct i40e_ring *rx_ring)
3268 {
3269         return ring_uses_build_skb(rx_ring) ? I40E_SKB_PAD : 0;
3270 }
3271
3272 /**
3273  * i40e_configure_rx_ring - Configure a receive ring context
3274  * @ring: The Rx ring to configure
3275  *
3276  * Configure the Rx descriptor ring in the HMC context.
3277  **/
3278 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3279 {
3280         struct i40e_vsi *vsi = ring->vsi;
3281         u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3282         u16 pf_q = vsi->base_queue + ring->queue_index;
3283         struct i40e_hw *hw = &vsi->back->hw;
3284         struct i40e_hmc_obj_rxq rx_ctx;
3285         i40e_status err = 0;
3286         bool ok;
3287         int ret;
3288
3289         bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3290
3291         /* clear the context structure first */
3292         memset(&rx_ctx, 0, sizeof(rx_ctx));
3293
3294         if (ring->vsi->type == I40E_VSI_MAIN)
3295                 xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3296
3297         kfree(ring->rx_bi);
3298         ring->xsk_pool = i40e_xsk_pool(ring);
3299         if (ring->xsk_pool) {
3300                 ret = i40e_alloc_rx_bi_zc(ring);
3301                 if (ret)
3302                         return ret;
3303                 ring->rx_buf_len =
3304                   xsk_pool_get_rx_frame_size(ring->xsk_pool);
3305                 /* For AF_XDP ZC, we disallow packets to span on
3306                  * multiple buffers, thus letting us skip that
3307                  * handling in the fast-path.
3308                  */
3309                 chain_len = 1;
3310                 ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3311                                                  MEM_TYPE_XSK_BUFF_POOL,
3312                                                  NULL);
3313                 if (ret)
3314                         return ret;
3315                 dev_info(&vsi->back->pdev->dev,
3316                          "Registered XDP mem model MEM_TYPE_XSK_BUFF_POOL on Rx ring %d\n",
3317                          ring->queue_index);
3318
3319         } else {
3320                 ret = i40e_alloc_rx_bi(ring);
3321                 if (ret)
3322                         return ret;
3323                 ring->rx_buf_len = vsi->rx_buf_len;
3324                 if (ring->vsi->type == I40E_VSI_MAIN) {
3325                         ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3326                                                          MEM_TYPE_PAGE_SHARED,
3327                                                          NULL);
3328                         if (ret)
3329                                 return ret;
3330                 }
3331         }
3332
3333         rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3334                                     BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3335
3336         rx_ctx.base = (ring->dma / 128);
3337         rx_ctx.qlen = ring->count;
3338
3339         /* use 16 byte descriptors */
3340         rx_ctx.dsize = 0;
3341
3342         /* descriptor type is always zero
3343          * rx_ctx.dtype = 0;
3344          */
3345         rx_ctx.hsplit_0 = 0;
3346
3347         rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3348         if (hw->revision_id == 0)
3349                 rx_ctx.lrxqthresh = 0;
3350         else
3351                 rx_ctx.lrxqthresh = 1;
3352         rx_ctx.crcstrip = 1;
3353         rx_ctx.l2tsel = 1;
3354         /* this controls whether VLAN is stripped from inner headers */
3355         rx_ctx.showiv = 0;
3356         /* set the prefena field to 1 because the manual says to */
3357         rx_ctx.prefena = 1;
3358
3359         /* clear the context in the HMC */
3360         err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3361         if (err) {
3362                 dev_info(&vsi->back->pdev->dev,
3363                          "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3364                          ring->queue_index, pf_q, err);
3365                 return -ENOMEM;
3366         }
3367
3368         /* set the context in the HMC */
3369         err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3370         if (err) {
3371                 dev_info(&vsi->back->pdev->dev,
3372                          "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3373                          ring->queue_index, pf_q, err);
3374                 return -ENOMEM;
3375         }
3376
3377         /* configure Rx buffer alignment */
3378         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3379                 clear_ring_build_skb_enabled(ring);
3380         else
3381                 set_ring_build_skb_enabled(ring);
3382
3383         ring->rx_offset = i40e_rx_offset(ring);
3384
3385         /* cache tail for quicker writes, and clear the reg before use */
3386         ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3387         writel(0, ring->tail);
3388
3389         if (ring->xsk_pool) {
3390                 xsk_pool_set_rxq_info(ring->xsk_pool, &ring->xdp_rxq);
3391                 ok = i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring));
3392         } else {
3393                 ok = !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3394         }
3395         if (!ok) {
3396                 /* Log this in case the user has forgotten to give the kernel
3397                  * any buffers, even later in the application.
3398                  */
3399                 dev_info(&vsi->back->pdev->dev,
3400                          "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3401                          ring->xsk_pool ? "AF_XDP ZC enabled " : "",
3402                          ring->queue_index, pf_q);
3403         }
3404
3405         return 0;
3406 }
3407
3408 /**
3409  * i40e_vsi_configure_tx - Configure the VSI for Tx
3410  * @vsi: VSI structure describing this set of rings and resources
3411  *
3412  * Configure the Tx VSI for operation.
3413  **/
3414 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3415 {
3416         int err = 0;
3417         u16 i;
3418
3419         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3420                 err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3421
3422         if (err || !i40e_enabled_xdp_vsi(vsi))
3423                 return err;
3424
3425         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3426                 err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3427
3428         return err;
3429 }
3430
3431 /**
3432  * i40e_vsi_configure_rx - Configure the VSI for Rx
3433  * @vsi: the VSI being configured
3434  *
3435  * Configure the Rx VSI for operation.
3436  **/
3437 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3438 {
3439         int err = 0;
3440         u16 i;
3441
3442         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3443                 vsi->max_frame = I40E_MAX_RXBUFFER;
3444                 vsi->rx_buf_len = I40E_RXBUFFER_2048;
3445 #if (PAGE_SIZE < 8192)
3446         } else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3447                    (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3448                 vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3449                 vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3450 #endif
3451         } else {
3452                 vsi->max_frame = I40E_MAX_RXBUFFER;
3453                 vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3454                                                        I40E_RXBUFFER_2048;
3455         }
3456
3457         /* set up individual rings */
3458         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3459                 err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3460
3461         return err;
3462 }
3463
3464 /**
3465  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3466  * @vsi: ptr to the VSI
3467  **/
3468 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3469 {
3470         struct i40e_ring *tx_ring, *rx_ring;
3471         u16 qoffset, qcount;
3472         int i, n;
3473
3474         if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3475                 /* Reset the TC information */
3476                 for (i = 0; i < vsi->num_queue_pairs; i++) {
3477                         rx_ring = vsi->rx_rings[i];
3478                         tx_ring = vsi->tx_rings[i];
3479                         rx_ring->dcb_tc = 0;
3480                         tx_ring->dcb_tc = 0;
3481                 }
3482                 return;
3483         }
3484
3485         for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3486                 if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3487                         continue;
3488
3489                 qoffset = vsi->tc_config.tc_info[n].qoffset;
3490                 qcount = vsi->tc_config.tc_info[n].qcount;
3491                 for (i = qoffset; i < (qoffset + qcount); i++) {
3492                         rx_ring = vsi->rx_rings[i];
3493                         tx_ring = vsi->tx_rings[i];
3494                         rx_ring->dcb_tc = n;
3495                         tx_ring->dcb_tc = n;
3496                 }
3497         }
3498 }
3499
3500 /**
3501  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3502  * @vsi: ptr to the VSI
3503  **/
3504 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3505 {
3506         if (vsi->netdev)
3507                 i40e_set_rx_mode(vsi->netdev);
3508 }
3509
3510 /**
3511  * i40e_reset_fdir_filter_cnt - Reset flow director filter counters
3512  * @pf: Pointer to the targeted PF
3513  *
3514  * Set all flow director counters to 0.
3515  */
3516 static void i40e_reset_fdir_filter_cnt(struct i40e_pf *pf)
3517 {
3518         pf->fd_tcp4_filter_cnt = 0;
3519         pf->fd_udp4_filter_cnt = 0;
3520         pf->fd_sctp4_filter_cnt = 0;
3521         pf->fd_ip4_filter_cnt = 0;
3522         pf->fd_tcp6_filter_cnt = 0;
3523         pf->fd_udp6_filter_cnt = 0;
3524         pf->fd_sctp6_filter_cnt = 0;
3525         pf->fd_ip6_filter_cnt = 0;
3526 }
3527
3528 /**
3529  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3530  * @vsi: Pointer to the targeted VSI
3531  *
3532  * This function replays the hlist on the hw where all the SB Flow Director
3533  * filters were saved.
3534  **/
3535 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3536 {
3537         struct i40e_fdir_filter *filter;
3538         struct i40e_pf *pf = vsi->back;
3539         struct hlist_node *node;
3540
3541         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3542                 return;
3543
3544         /* Reset FDir counters as we're replaying all existing filters */
3545         i40e_reset_fdir_filter_cnt(pf);
3546
3547         hlist_for_each_entry_safe(filter, node,
3548                                   &pf->fdir_filter_list, fdir_node) {
3549                 i40e_add_del_fdir(vsi, filter, true);
3550         }
3551 }
3552
3553 /**
3554  * i40e_vsi_configure - Set up the VSI for action
3555  * @vsi: the VSI being configured
3556  **/
3557 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3558 {
3559         int err;
3560
3561         i40e_set_vsi_rx_mode(vsi);
3562         i40e_restore_vlan(vsi);
3563         i40e_vsi_config_dcb_rings(vsi);
3564         err = i40e_vsi_configure_tx(vsi);
3565         if (!err)
3566                 err = i40e_vsi_configure_rx(vsi);
3567
3568         return err;
3569 }
3570
3571 /**
3572  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3573  * @vsi: the VSI being configured
3574  **/
3575 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3576 {
3577         bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3578         struct i40e_pf *pf = vsi->back;
3579         struct i40e_hw *hw = &pf->hw;
3580         u16 vector;
3581         int i, q;
3582         u32 qp;
3583
3584         /* The interrupt indexing is offset by 1 in the PFINT_ITRn
3585          * and PFINT_LNKLSTn registers, e.g.:
3586          *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3587          */
3588         qp = vsi->base_queue;
3589         vector = vsi->base_vector;
3590         for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3591                 struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3592
3593                 q_vector->rx.next_update = jiffies + 1;
3594                 q_vector->rx.target_itr =
3595                         ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3596                 wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3597                      q_vector->rx.target_itr >> 1);
3598                 q_vector->rx.current_itr = q_vector->rx.target_itr;
3599
3600                 q_vector->tx.next_update = jiffies + 1;
3601                 q_vector->tx.target_itr =
3602                         ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3603                 wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3604                      q_vector->tx.target_itr >> 1);
3605                 q_vector->tx.current_itr = q_vector->tx.target_itr;
3606
3607                 wr32(hw, I40E_PFINT_RATEN(vector - 1),
3608                      i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3609
3610                 /* Linked list for the queuepairs assigned to this vector */
3611                 wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3612                 for (q = 0; q < q_vector->num_ringpairs; q++) {
3613                         u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3614                         u32 val;
3615
3616                         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3617                               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3618                               (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3619                               (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3620                               (I40E_QUEUE_TYPE_TX <<
3621                                I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3622
3623                         wr32(hw, I40E_QINT_RQCTL(qp), val);
3624
3625                         if (has_xdp) {
3626                                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3627                                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3628                                       (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3629                                       (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3630                                       (I40E_QUEUE_TYPE_TX <<
3631                                        I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3632
3633                                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3634                         }
3635
3636                         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3637                               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3638                               (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3639                               ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3640                               (I40E_QUEUE_TYPE_RX <<
3641                                I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3642
3643                         /* Terminate the linked list */
3644                         if (q == (q_vector->num_ringpairs - 1))
3645                                 val |= (I40E_QUEUE_END_OF_LIST <<
3646                                         I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3647
3648                         wr32(hw, I40E_QINT_TQCTL(qp), val);
3649                         qp++;
3650                 }
3651         }
3652
3653         i40e_flush(hw);
3654 }
3655
3656 /**
3657  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3658  * @pf: pointer to private device data structure
3659  **/
3660 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3661 {
3662         struct i40e_hw *hw = &pf->hw;
3663         u32 val;
3664
3665         /* clear things first */
3666         wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3667         rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3668
3669         val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3670               I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3671               I40E_PFINT_ICR0_ENA_GRST_MASK          |
3672               I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3673               I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3674               I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3675               I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3676               I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3677
3678         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3679                 val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3680
3681         if (pf->flags & I40E_FLAG_PTP)
3682                 val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3683
3684         wr32(hw, I40E_PFINT_ICR0_ENA, val);
3685
3686         /* SW_ITR_IDX = 0, but don't change INTENA */
3687         wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3688                                         I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3689
3690         /* OTHER_ITR_IDX = 0 */
3691         wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3692 }
3693
3694 /**
3695  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3696  * @vsi: the VSI being configured
3697  **/
3698 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3699 {
3700         u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3701         struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3702         struct i40e_pf *pf = vsi->back;
3703         struct i40e_hw *hw = &pf->hw;
3704         u32 val;
3705
3706         /* set the ITR configuration */
3707         q_vector->rx.next_update = jiffies + 1;
3708         q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3709         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr >> 1);
3710         q_vector->rx.current_itr = q_vector->rx.target_itr;
3711         q_vector->tx.next_update = jiffies + 1;
3712         q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3713         wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr >> 1);
3714         q_vector->tx.current_itr = q_vector->tx.target_itr;
3715
3716         i40e_enable_misc_int_causes(pf);
3717
3718         /* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3719         wr32(hw, I40E_PFINT_LNKLST0, 0);
3720
3721         /* Associate the queue pair to the vector and enable the queue int */
3722         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK                   |
3723               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3724               (nextqp      << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3725               (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3726
3727         wr32(hw, I40E_QINT_RQCTL(0), val);
3728
3729         if (i40e_enabled_xdp_vsi(vsi)) {
3730                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                 |
3731                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
3732                       (I40E_QUEUE_TYPE_TX
3733                        << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3734
3735                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3736         }
3737
3738         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                  |
3739               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3740               (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3741
3742         wr32(hw, I40E_QINT_TQCTL(0), val);
3743         i40e_flush(hw);
3744 }
3745
3746 /**
3747  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
3748  * @pf: board private structure
3749  **/
3750 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
3751 {
3752         struct i40e_hw *hw = &pf->hw;
3753
3754         wr32(hw, I40E_PFINT_DYN_CTL0,
3755              I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
3756         i40e_flush(hw);
3757 }
3758
3759 /**
3760  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
3761  * @pf: board private structure
3762  **/
3763 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
3764 {
3765         struct i40e_hw *hw = &pf->hw;
3766         u32 val;
3767
3768         val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
3769               I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
3770               (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
3771
3772         wr32(hw, I40E_PFINT_DYN_CTL0, val);
3773         i40e_flush(hw);
3774 }
3775
3776 /**
3777  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
3778  * @irq: interrupt number
3779  * @data: pointer to a q_vector
3780  **/
3781 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
3782 {
3783         struct i40e_q_vector *q_vector = data;
3784
3785         if (!q_vector->tx.ring && !q_vector->rx.ring)
3786                 return IRQ_HANDLED;
3787
3788         napi_schedule_irqoff(&q_vector->napi);
3789
3790         return IRQ_HANDLED;
3791 }
3792
3793 /**
3794  * i40e_irq_affinity_notify - Callback for affinity changes
3795  * @notify: context as to what irq was changed
3796  * @mask: the new affinity mask
3797  *
3798  * This is a callback function used by the irq_set_affinity_notifier function
3799  * so that we may register to receive changes to the irq affinity masks.
3800  **/
3801 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
3802                                      const cpumask_t *mask)
3803 {
3804         struct i40e_q_vector *q_vector =
3805                 container_of(notify, struct i40e_q_vector, affinity_notify);
3806
3807         cpumask_copy(&q_vector->affinity_mask, mask);
3808 }
3809
3810 /**
3811  * i40e_irq_affinity_release - Callback for affinity notifier release
3812  * @ref: internal core kernel usage
3813  *
3814  * This is a callback function used by the irq_set_affinity_notifier function
3815  * to inform the current notification subscriber that they will no longer
3816  * receive notifications.
3817  **/
3818 static void i40e_irq_affinity_release(struct kref *ref) {}
3819
3820 /**
3821  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
3822  * @vsi: the VSI being configured
3823  * @basename: name for the vector
3824  *
3825  * Allocates MSI-X vectors and requests interrupts from the kernel.
3826  **/
3827 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
3828 {
3829         int q_vectors = vsi->num_q_vectors;
3830         struct i40e_pf *pf = vsi->back;
3831         int base = vsi->base_vector;
3832         int rx_int_idx = 0;
3833         int tx_int_idx = 0;
3834         int vector, err;
3835         int irq_num;
3836         int cpu;
3837
3838         for (vector = 0; vector < q_vectors; vector++) {
3839                 struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
3840
3841                 irq_num = pf->msix_entries[base + vector].vector;
3842
3843                 if (q_vector->tx.ring && q_vector->rx.ring) {
3844                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3845                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
3846                         tx_int_idx++;
3847                 } else if (q_vector->rx.ring) {
3848                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3849                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
3850                 } else if (q_vector->tx.ring) {
3851                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3852                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
3853                 } else {
3854                         /* skip this unused q_vector */
3855                         continue;
3856                 }
3857                 err = request_irq(irq_num,
3858                                   vsi->irq_handler,
3859                                   0,
3860                                   q_vector->name,
3861                                   q_vector);
3862                 if (err) {
3863                         dev_info(&pf->pdev->dev,
3864                                  "MSIX request_irq failed, error: %d\n", err);
3865                         goto free_queue_irqs;
3866                 }
3867
3868                 /* register for affinity change notifications */
3869                 q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
3870                 q_vector->affinity_notify.release = i40e_irq_affinity_release;
3871                 irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
3872                 /* Spread affinity hints out across online CPUs.
3873                  *
3874                  * get_cpu_mask returns a static constant mask with
3875                  * a permanent lifetime so it's ok to pass to
3876                  * irq_set_affinity_hint without making a copy.
3877                  */
3878                 cpu = cpumask_local_spread(q_vector->v_idx, -1);
3879                 irq_set_affinity_hint(irq_num, get_cpu_mask(cpu));
3880         }
3881
3882         vsi->irqs_ready = true;
3883         return 0;
3884
3885 free_queue_irqs:
3886         while (vector) {
3887                 vector--;
3888                 irq_num = pf->msix_entries[base + vector].vector;
3889                 irq_set_affinity_notifier(irq_num, NULL);
3890                 irq_set_affinity_hint(irq_num, NULL);
3891                 free_irq(irq_num, &vsi->q_vectors[vector]);
3892         }
3893         return err;
3894 }
3895
3896 /**
3897  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
3898  * @vsi: the VSI being un-configured
3899  **/
3900 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
3901 {
3902         struct i40e_pf *pf = vsi->back;
3903         struct i40e_hw *hw = &pf->hw;
3904         int base = vsi->base_vector;
3905         int i;
3906
3907         /* disable interrupt causation from each queue */
3908         for (i = 0; i < vsi->num_queue_pairs; i++) {
3909                 u32 val;
3910
3911                 val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
3912                 val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
3913                 wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
3914
3915                 val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
3916                 val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
3917                 wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
3918
3919                 if (!i40e_enabled_xdp_vsi(vsi))
3920                         continue;
3921                 wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
3922         }
3923
3924         /* disable each interrupt */
3925         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3926                 for (i = vsi->base_vector;
3927                      i < (vsi->num_q_vectors + vsi->base_vector); i++)
3928                         wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
3929
3930                 i40e_flush(hw);
3931                 for (i = 0; i < vsi->num_q_vectors; i++)
3932                         synchronize_irq(pf->msix_entries[i + base].vector);
3933         } else {
3934                 /* Legacy and MSI mode - this stops all interrupt handling */
3935                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
3936                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
3937                 i40e_flush(hw);
3938                 synchronize_irq(pf->pdev->irq);
3939         }
3940 }
3941
3942 /**
3943  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
3944  * @vsi: the VSI being configured
3945  **/
3946 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
3947 {
3948         struct i40e_pf *pf = vsi->back;
3949         int i;
3950
3951         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3952                 for (i = 0; i < vsi->num_q_vectors; i++)
3953                         i40e_irq_dynamic_enable(vsi, i);
3954         } else {
3955                 i40e_irq_dynamic_enable_icr0(pf);
3956         }
3957
3958         i40e_flush(&pf->hw);
3959         return 0;
3960 }
3961
3962 /**
3963  * i40e_free_misc_vector - Free the vector that handles non-queue events
3964  * @pf: board private structure
3965  **/
3966 static void i40e_free_misc_vector(struct i40e_pf *pf)
3967 {
3968         /* Disable ICR 0 */
3969         wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
3970         i40e_flush(&pf->hw);
3971
3972         if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
3973                 synchronize_irq(pf->msix_entries[0].vector);
3974                 free_irq(pf->msix_entries[0].vector, pf);
3975                 clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
3976         }
3977 }
3978
3979 /**
3980  * i40e_intr - MSI/Legacy and non-queue interrupt handler
3981  * @irq: interrupt number
3982  * @data: pointer to a q_vector
3983  *
3984  * This is the handler used for all MSI/Legacy interrupts, and deals
3985  * with both queue and non-queue interrupts.  This is also used in
3986  * MSIX mode to handle the non-queue interrupts.
3987  **/
3988 static irqreturn_t i40e_intr(int irq, void *data)
3989 {
3990         struct i40e_pf *pf = (struct i40e_pf *)data;
3991         struct i40e_hw *hw = &pf->hw;
3992         irqreturn_t ret = IRQ_NONE;
3993         u32 icr0, icr0_remaining;
3994         u32 val, ena_mask;
3995
3996         icr0 = rd32(hw, I40E_PFINT_ICR0);
3997         ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
3998
3999         /* if sharing a legacy IRQ, we might get called w/o an intr pending */
4000         if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
4001                 goto enable_intr;
4002
4003         /* if interrupt but no bits showing, must be SWINT */
4004         if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
4005             (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
4006                 pf->sw_int_count++;
4007
4008         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
4009             (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
4010                 ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
4011                 dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
4012                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
4013         }
4014
4015         /* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
4016         if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
4017                 struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
4018                 struct i40e_q_vector *q_vector = vsi->q_vectors[0];
4019
4020                 /* We do not have a way to disarm Queue causes while leaving
4021                  * interrupt enabled for all other causes, ideally
4022                  * interrupt should be disabled while we are in NAPI but
4023                  * this is not a performance path and napi_schedule()
4024                  * can deal with rescheduling.
4025                  */
4026                 if (!test_bit(__I40E_DOWN, pf->state))
4027                         napi_schedule_irqoff(&q_vector->napi);
4028         }
4029
4030         if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
4031                 ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
4032                 set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
4033                 i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
4034         }
4035
4036         if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
4037                 ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
4038                 set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
4039         }
4040
4041         if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
4042                 /* disable any further VFLR event notifications */
4043                 if (test_bit(__I40E_VF_RESETS_DISABLED, pf->state)) {
4044                         u32 reg = rd32(hw, I40E_PFINT_ICR0_ENA);
4045
4046                         reg &= ~I40E_PFINT_ICR0_VFLR_MASK;
4047                         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
4048                 } else {
4049                         ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
4050                         set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
4051                 }
4052         }
4053
4054         if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
4055                 if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4056                         set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
4057                 ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
4058                 val = rd32(hw, I40E_GLGEN_RSTAT);
4059                 val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
4060                        >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
4061                 if (val == I40E_RESET_CORER) {
4062                         pf->corer_count++;
4063                 } else if (val == I40E_RESET_GLOBR) {
4064                         pf->globr_count++;
4065                 } else if (val == I40E_RESET_EMPR) {
4066                         pf->empr_count++;
4067                         set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
4068                 }
4069         }
4070
4071         if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
4072                 icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
4073                 dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4074                 dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4075                          rd32(hw, I40E_PFHMC_ERRORINFO),
4076                          rd32(hw, I40E_PFHMC_ERRORDATA));
4077         }
4078
4079         if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4080                 u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4081
4082                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_EVENT0_MASK)
4083                         schedule_work(&pf->ptp_extts0_work);
4084
4085                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK)
4086                         i40e_ptp_tx_hwtstamp(pf);
4087
4088                 icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4089         }
4090
4091         /* If a critical error is pending we have no choice but to reset the
4092          * device.
4093          * Report and mask out any remaining unexpected interrupts.
4094          */
4095         icr0_remaining = icr0 & ena_mask;
4096         if (icr0_remaining) {
4097                 dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4098                          icr0_remaining);
4099                 if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4100                     (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4101                     (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4102                         dev_info(&pf->pdev->dev, "device will be reset\n");
4103                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4104                         i40e_service_event_schedule(pf);
4105                 }
4106                 ena_mask &= ~icr0_remaining;
4107         }
4108         ret = IRQ_HANDLED;
4109
4110 enable_intr:
4111         /* re-enable interrupt causes */
4112         wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4113         if (!test_bit(__I40E_DOWN, pf->state) ||
4114             test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4115                 i40e_service_event_schedule(pf);
4116                 i40e_irq_dynamic_enable_icr0(pf);
4117         }
4118
4119         return ret;
4120 }
4121
4122 /**
4123  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4124  * @tx_ring:  tx ring to clean
4125  * @budget:   how many cleans we're allowed
4126  *
4127  * Returns true if there's any budget left (e.g. the clean is finished)
4128  **/
4129 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4130 {
4131         struct i40e_vsi *vsi = tx_ring->vsi;
4132         u16 i = tx_ring->next_to_clean;
4133         struct i40e_tx_buffer *tx_buf;
4134         struct i40e_tx_desc *tx_desc;
4135
4136         tx_buf = &tx_ring->tx_bi[i];
4137         tx_desc = I40E_TX_DESC(tx_ring, i);
4138         i -= tx_ring->count;
4139
4140         do {
4141                 struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4142
4143                 /* if next_to_watch is not set then there is no work pending */
4144                 if (!eop_desc)
4145                         break;
4146
4147                 /* prevent any other reads prior to eop_desc */
4148                 smp_rmb();
4149
4150                 /* if the descriptor isn't done, no work yet to do */
4151                 if (!(eop_desc->cmd_type_offset_bsz &
4152                       cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4153                         break;
4154
4155                 /* clear next_to_watch to prevent false hangs */
4156                 tx_buf->next_to_watch = NULL;
4157
4158                 tx_desc->buffer_addr = 0;
4159                 tx_desc->cmd_type_offset_bsz = 0;
4160                 /* move past filter desc */
4161                 tx_buf++;
4162                 tx_desc++;
4163                 i++;
4164                 if (unlikely(!i)) {
4165                         i -= tx_ring->count;
4166                         tx_buf = tx_ring->tx_bi;
4167                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4168                 }
4169                 /* unmap skb header data */
4170                 dma_unmap_single(tx_ring->dev,
4171                                  dma_unmap_addr(tx_buf, dma),
4172                                  dma_unmap_len(tx_buf, len),
4173                                  DMA_TO_DEVICE);
4174                 if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4175                         kfree(tx_buf->raw_buf);
4176
4177                 tx_buf->raw_buf = NULL;
4178                 tx_buf->tx_flags = 0;
4179                 tx_buf->next_to_watch = NULL;
4180                 dma_unmap_len_set(tx_buf, len, 0);
4181                 tx_desc->buffer_addr = 0;
4182                 tx_desc->cmd_type_offset_bsz = 0;
4183
4184                 /* move us past the eop_desc for start of next FD desc */
4185                 tx_buf++;
4186                 tx_desc++;
4187                 i++;
4188                 if (unlikely(!i)) {
4189                         i -= tx_ring->count;
4190                         tx_buf = tx_ring->tx_bi;
4191                         tx_desc = I40E_TX_DESC(tx_ring, 0);
4192                 }
4193
4194                 /* update budget accounting */
4195                 budget--;
4196         } while (likely(budget));
4197
4198         i += tx_ring->count;
4199         tx_ring->next_to_clean = i;
4200
4201         if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4202                 i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4203
4204         return budget > 0;
4205 }
4206
4207 /**
4208  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4209  * @irq: interrupt number
4210  * @data: pointer to a q_vector
4211  **/
4212 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4213 {
4214         struct i40e_q_vector *q_vector = data;
4215         struct i40e_vsi *vsi;
4216
4217         if (!q_vector->tx.ring)
4218                 return IRQ_HANDLED;
4219
4220         vsi = q_vector->tx.ring->vsi;
4221         i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4222
4223         return IRQ_HANDLED;
4224 }
4225
4226 /**
4227  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4228  * @vsi: the VSI being configured
4229  * @v_idx: vector index
4230  * @qp_idx: queue pair index
4231  **/
4232 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4233 {
4234         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4235         struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4236         struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4237
4238         tx_ring->q_vector = q_vector;
4239         tx_ring->next = q_vector->tx.ring;
4240         q_vector->tx.ring = tx_ring;
4241         q_vector->tx.count++;
4242
4243         /* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4244         if (i40e_enabled_xdp_vsi(vsi)) {
4245                 struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4246
4247                 xdp_ring->q_vector = q_vector;
4248                 xdp_ring->next = q_vector->tx.ring;
4249                 q_vector->tx.ring = xdp_ring;
4250                 q_vector->tx.count++;
4251         }
4252
4253         rx_ring->q_vector = q_vector;
4254         rx_ring->next = q_vector->rx.ring;
4255         q_vector->rx.ring = rx_ring;
4256         q_vector->rx.count++;
4257 }
4258
4259 /**
4260  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4261  * @vsi: the VSI being configured
4262  *
4263  * This function maps descriptor rings to the queue-specific vectors
4264  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4265  * one vector per queue pair, but on a constrained vector budget, we
4266  * group the queue pairs as "efficiently" as possible.
4267  **/
4268 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4269 {
4270         int qp_remaining = vsi->num_queue_pairs;
4271         int q_vectors = vsi->num_q_vectors;
4272         int num_ringpairs;
4273         int v_start = 0;
4274         int qp_idx = 0;
4275
4276         /* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4277          * group them so there are multiple queues per vector.
4278          * It is also important to go through all the vectors available to be
4279          * sure that if we don't use all the vectors, that the remaining vectors
4280          * are cleared. This is especially important when decreasing the
4281          * number of queues in use.
4282          */
4283         for (; v_start < q_vectors; v_start++) {
4284                 struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4285
4286                 num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4287
4288                 q_vector->num_ringpairs = num_ringpairs;
4289                 q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4290
4291                 q_vector->rx.count = 0;
4292                 q_vector->tx.count = 0;
4293                 q_vector->rx.ring = NULL;
4294                 q_vector->tx.ring = NULL;
4295
4296                 while (num_ringpairs--) {
4297                         i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4298                         qp_idx++;
4299                         qp_remaining--;
4300                 }
4301         }
4302 }
4303
4304 /**
4305  * i40e_vsi_request_irq - Request IRQ from the OS
4306  * @vsi: the VSI being configured
4307  * @basename: name for the vector
4308  **/
4309 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4310 {
4311         struct i40e_pf *pf = vsi->back;
4312         int err;
4313
4314         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4315                 err = i40e_vsi_request_irq_msix(vsi, basename);
4316         else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4317                 err = request_irq(pf->pdev->irq, i40e_intr, 0,
4318                                   pf->int_name, pf);
4319         else
4320                 err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4321                                   pf->int_name, pf);
4322
4323         if (err)
4324                 dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4325
4326         return err;
4327 }
4328
4329 #ifdef CONFIG_NET_POLL_CONTROLLER
4330 /**
4331  * i40e_netpoll - A Polling 'interrupt' handler
4332  * @netdev: network interface device structure
4333  *
4334  * This is used by netconsole to send skbs without having to re-enable
4335  * interrupts.  It's not called while the normal interrupt routine is executing.
4336  **/
4337 static void i40e_netpoll(struct net_device *netdev)
4338 {
4339         struct i40e_netdev_priv *np = netdev_priv(netdev);
4340         struct i40e_vsi *vsi = np->vsi;
4341         struct i40e_pf *pf = vsi->back;
4342         int i;
4343
4344         /* if interface is down do nothing */
4345         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4346                 return;
4347
4348         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4349                 for (i = 0; i < vsi->num_q_vectors; i++)
4350                         i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4351         } else {
4352                 i40e_intr(pf->pdev->irq, netdev);
4353         }
4354 }
4355 #endif
4356
4357 #define I40E_QTX_ENA_WAIT_COUNT 50
4358
4359 /**
4360  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4361  * @pf: the PF being configured
4362  * @pf_q: the PF queue
4363  * @enable: enable or disable state of the queue
4364  *
4365  * This routine will wait for the given Tx queue of the PF to reach the
4366  * enabled or disabled state.
4367  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4368  * multiple retries; else will return 0 in case of success.
4369  **/
4370 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4371 {
4372         int i;
4373         u32 tx_reg;
4374
4375         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4376                 tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4377                 if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4378                         break;
4379
4380                 usleep_range(10, 20);
4381         }
4382         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4383                 return -ETIMEDOUT;
4384
4385         return 0;
4386 }
4387
4388 /**
4389  * i40e_control_tx_q - Start or stop a particular Tx queue
4390  * @pf: the PF structure
4391  * @pf_q: the PF queue to configure
4392  * @enable: start or stop the queue
4393  *
4394  * This function enables or disables a single queue. Note that any delay
4395  * required after the operation is expected to be handled by the caller of
4396  * this function.
4397  **/
4398 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4399 {
4400         struct i40e_hw *hw = &pf->hw;
4401         u32 tx_reg;
4402         int i;
4403
4404         /* warn the TX unit of coming changes */
4405         i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4406         if (!enable)
4407                 usleep_range(10, 20);
4408
4409         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4410                 tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4411                 if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4412                     ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4413                         break;
4414                 usleep_range(1000, 2000);
4415         }
4416
4417         /* Skip if the queue is already in the requested state */
4418         if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4419                 return;
4420
4421         /* turn on/off the queue */
4422         if (enable) {
4423                 wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4424                 tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4425         } else {
4426                 tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4427         }
4428
4429         wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4430 }
4431
4432 /**
4433  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4434  * @seid: VSI SEID
4435  * @pf: the PF structure
4436  * @pf_q: the PF queue to configure
4437  * @is_xdp: true if the queue is used for XDP
4438  * @enable: start or stop the queue
4439  **/
4440 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4441                            bool is_xdp, bool enable)
4442 {
4443         int ret;
4444
4445         i40e_control_tx_q(pf, pf_q, enable);
4446
4447         /* wait for the change to finish */
4448         ret = i40e_pf_txq_wait(pf, pf_q, enable);
4449         if (ret) {
4450                 dev_info(&pf->pdev->dev,
4451                          "VSI seid %d %sTx ring %d %sable timeout\n",
4452                          seid, (is_xdp ? "XDP " : ""), pf_q,
4453                          (enable ? "en" : "dis"));
4454         }
4455
4456         return ret;
4457 }
4458
4459 /**
4460  * i40e_vsi_enable_tx - Start a VSI's rings
4461  * @vsi: the VSI being configured
4462  **/
4463 static int i40e_vsi_enable_tx(struct i40e_vsi *vsi)
4464 {
4465         struct i40e_pf *pf = vsi->back;
4466         int i, pf_q, ret = 0;
4467
4468         pf_q = vsi->base_queue;
4469         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4470                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4471                                              pf_q,
4472                                              false /*is xdp*/, true);
4473                 if (ret)
4474                         break;
4475
4476                 if (!i40e_enabled_xdp_vsi(vsi))
4477                         continue;
4478
4479                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4480                                              pf_q + vsi->alloc_queue_pairs,
4481                                              true /*is xdp*/, true);
4482                 if (ret)
4483                         break;
4484         }
4485         return ret;
4486 }
4487
4488 /**
4489  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4490  * @pf: the PF being configured
4491  * @pf_q: the PF queue
4492  * @enable: enable or disable state of the queue
4493  *
4494  * This routine will wait for the given Rx queue of the PF to reach the
4495  * enabled or disabled state.
4496  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4497  * multiple retries; else will return 0 in case of success.
4498  **/
4499 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4500 {
4501         int i;
4502         u32 rx_reg;
4503
4504         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4505                 rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4506                 if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4507                         break;
4508
4509                 usleep_range(10, 20);
4510         }
4511         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4512                 return -ETIMEDOUT;
4513
4514         return 0;
4515 }
4516
4517 /**
4518  * i40e_control_rx_q - Start or stop a particular Rx queue
4519  * @pf: the PF structure
4520  * @pf_q: the PF queue to configure
4521  * @enable: start or stop the queue
4522  *
4523  * This function enables or disables a single queue. Note that
4524  * any delay required after the operation is expected to be
4525  * handled by the caller of this function.
4526  **/
4527 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4528 {
4529         struct i40e_hw *hw = &pf->hw;
4530         u32 rx_reg;
4531         int i;
4532
4533         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4534                 rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4535                 if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4536                     ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4537                         break;
4538                 usleep_range(1000, 2000);
4539         }
4540
4541         /* Skip if the queue is already in the requested state */
4542         if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4543                 return;
4544
4545         /* turn on/off the queue */
4546         if (enable)
4547                 rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4548         else
4549                 rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4550
4551         wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4552 }
4553
4554 /**
4555  * i40e_control_wait_rx_q
4556  * @pf: the PF structure
4557  * @pf_q: queue being configured
4558  * @enable: start or stop the rings
4559  *
4560  * This function enables or disables a single queue along with waiting
4561  * for the change to finish. The caller of this function should handle
4562  * the delays needed in the case of disabling queues.
4563  **/
4564 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4565 {
4566         int ret = 0;
4567
4568         i40e_control_rx_q(pf, pf_q, enable);
4569
4570         /* wait for the change to finish */
4571         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4572         if (ret)
4573                 return ret;
4574
4575         return ret;
4576 }
4577
4578 /**
4579  * i40e_vsi_enable_rx - Start a VSI's rings
4580  * @vsi: the VSI being configured
4581  **/
4582 static int i40e_vsi_enable_rx(struct i40e_vsi *vsi)
4583 {
4584         struct i40e_pf *pf = vsi->back;
4585         int i, pf_q, ret = 0;
4586
4587         pf_q = vsi->base_queue;
4588         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4589                 ret = i40e_control_wait_rx_q(pf, pf_q, true);
4590                 if (ret) {
4591                         dev_info(&pf->pdev->dev,
4592                                  "VSI seid %d Rx ring %d enable timeout\n",
4593                                  vsi->seid, pf_q);
4594                         break;
4595                 }
4596         }
4597
4598         return ret;
4599 }
4600
4601 /**
4602  * i40e_vsi_start_rings - Start a VSI's rings
4603  * @vsi: the VSI being configured
4604  **/
4605 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4606 {
4607         int ret = 0;
4608
4609         /* do rx first for enable and last for disable */
4610         ret = i40e_vsi_enable_rx(vsi);
4611         if (ret)
4612                 return ret;
4613         ret = i40e_vsi_enable_tx(vsi);
4614
4615         return ret;
4616 }
4617
4618 #define I40E_DISABLE_TX_GAP_MSEC        50
4619
4620 /**
4621  * i40e_vsi_stop_rings - Stop a VSI's rings
4622  * @vsi: the VSI being configured
4623  **/
4624 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4625 {
4626         struct i40e_pf *pf = vsi->back;
4627         int pf_q, err, q_end;
4628
4629         /* When port TX is suspended, don't wait */
4630         if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4631                 return i40e_vsi_stop_rings_no_wait(vsi);
4632
4633         q_end = vsi->base_queue + vsi->num_queue_pairs;
4634         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4635                 i40e_pre_tx_queue_cfg(&pf->hw, (u32)pf_q, false);
4636
4637         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++) {
4638                 err = i40e_control_wait_rx_q(pf, pf_q, false);
4639                 if (err)
4640                         dev_info(&pf->pdev->dev,
4641                                  "VSI seid %d Rx ring %d disable timeout\n",
4642                                  vsi->seid, pf_q);
4643         }
4644
4645         msleep(I40E_DISABLE_TX_GAP_MSEC);
4646         pf_q = vsi->base_queue;
4647         for (pf_q = vsi->base_queue; pf_q < q_end; pf_q++)
4648                 wr32(&pf->hw, I40E_QTX_ENA(pf_q), 0);
4649
4650         i40e_vsi_wait_queues_disabled(vsi);
4651 }
4652
4653 /**
4654  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4655  * @vsi: the VSI being shutdown
4656  *
4657  * This function stops all the rings for a VSI but does not delay to verify
4658  * that rings have been disabled. It is expected that the caller is shutting
4659  * down multiple VSIs at once and will delay together for all the VSIs after
4660  * initiating the shutdown. This is particularly useful for shutting down lots
4661  * of VFs together. Otherwise, a large delay can be incurred while configuring
4662  * each VSI in serial.
4663  **/
4664 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4665 {
4666         struct i40e_pf *pf = vsi->back;
4667         int i, pf_q;
4668
4669         pf_q = vsi->base_queue;
4670         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4671                 i40e_control_tx_q(pf, pf_q, false);
4672                 i40e_control_rx_q(pf, pf_q, false);
4673         }
4674 }
4675
4676 /**
4677  * i40e_vsi_free_irq - Free the irq association with the OS
4678  * @vsi: the VSI being configured
4679  **/
4680 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4681 {
4682         struct i40e_pf *pf = vsi->back;
4683         struct i40e_hw *hw = &pf->hw;
4684         int base = vsi->base_vector;
4685         u32 val, qp;
4686         int i;
4687
4688         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4689                 if (!vsi->q_vectors)
4690                         return;
4691
4692                 if (!vsi->irqs_ready)
4693                         return;
4694
4695                 vsi->irqs_ready = false;
4696                 for (i = 0; i < vsi->num_q_vectors; i++) {
4697                         int irq_num;
4698                         u16 vector;
4699
4700                         vector = i + base;
4701                         irq_num = pf->msix_entries[vector].vector;
4702
4703                         /* free only the irqs that were actually requested */
4704                         if (!vsi->q_vectors[i] ||
4705                             !vsi->q_vectors[i]->num_ringpairs)
4706                                 continue;
4707
4708                         /* clear the affinity notifier in the IRQ descriptor */
4709                         irq_set_affinity_notifier(irq_num, NULL);
4710                         /* remove our suggested affinity mask for this IRQ */
4711                         irq_set_affinity_hint(irq_num, NULL);
4712                         synchronize_irq(irq_num);
4713                         free_irq(irq_num, vsi->q_vectors[i]);
4714
4715                         /* Tear down the interrupt queue link list
4716                          *
4717                          * We know that they come in pairs and always
4718                          * the Rx first, then the Tx.  To clear the
4719                          * link list, stick the EOL value into the
4720                          * next_q field of the registers.
4721                          */
4722                         val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4723                         qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4724                                 >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4725                         val |= I40E_QUEUE_END_OF_LIST
4726                                 << I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4727                         wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4728
4729                         while (qp != I40E_QUEUE_END_OF_LIST) {
4730                                 u32 next;
4731
4732                                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4733
4734                                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4735                                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4736                                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4737                                          I40E_QINT_RQCTL_INTEVENT_MASK);
4738
4739                                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4740                                          I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4741
4742                                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4743
4744                                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4745
4746                                 next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
4747                                         >> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
4748
4749                                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4750                                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4751                                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4752                                          I40E_QINT_TQCTL_INTEVENT_MASK);
4753
4754                                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4755                                          I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4756
4757                                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4758                                 qp = next;
4759                         }
4760                 }
4761         } else {
4762                 free_irq(pf->pdev->irq, pf);
4763
4764                 val = rd32(hw, I40E_PFINT_LNKLST0);
4765                 qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4766                         >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4767                 val |= I40E_QUEUE_END_OF_LIST
4768                         << I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
4769                 wr32(hw, I40E_PFINT_LNKLST0, val);
4770
4771                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4772                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4773                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4774                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4775                          I40E_QINT_RQCTL_INTEVENT_MASK);
4776
4777                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4778                         I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4779
4780                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4781
4782                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4783
4784                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4785                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4786                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4787                          I40E_QINT_TQCTL_INTEVENT_MASK);
4788
4789                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4790                         I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4791
4792                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4793         }
4794 }
4795
4796 /**
4797  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
4798  * @vsi: the VSI being configured
4799  * @v_idx: Index of vector to be freed
4800  *
4801  * This function frees the memory allocated to the q_vector.  In addition if
4802  * NAPI is enabled it will delete any references to the NAPI struct prior
4803  * to freeing the q_vector.
4804  **/
4805 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
4806 {
4807         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4808         struct i40e_ring *ring;
4809
4810         if (!q_vector)
4811                 return;
4812
4813         /* disassociate q_vector from rings */
4814         i40e_for_each_ring(ring, q_vector->tx)
4815                 ring->q_vector = NULL;
4816
4817         i40e_for_each_ring(ring, q_vector->rx)
4818                 ring->q_vector = NULL;
4819
4820         /* only VSI w/ an associated netdev is set up w/ NAPI */
4821         if (vsi->netdev)
4822                 netif_napi_del(&q_vector->napi);
4823
4824         vsi->q_vectors[v_idx] = NULL;
4825
4826         kfree_rcu(q_vector, rcu);
4827 }
4828
4829 /**
4830  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
4831  * @vsi: the VSI being un-configured
4832  *
4833  * This frees the memory allocated to the q_vectors and
4834  * deletes references to the NAPI struct.
4835  **/
4836 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
4837 {
4838         int v_idx;
4839
4840         for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
4841                 i40e_free_q_vector(vsi, v_idx);
4842 }
4843
4844 /**
4845  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
4846  * @pf: board private structure
4847  **/
4848 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
4849 {
4850         /* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
4851         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4852                 pci_disable_msix(pf->pdev);
4853                 kfree(pf->msix_entries);
4854                 pf->msix_entries = NULL;
4855                 kfree(pf->irq_pile);
4856                 pf->irq_pile = NULL;
4857         } else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
4858                 pci_disable_msi(pf->pdev);
4859         }
4860         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
4861 }
4862
4863 /**
4864  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
4865  * @pf: board private structure
4866  *
4867  * We go through and clear interrupt specific resources and reset the structure
4868  * to pre-load conditions
4869  **/
4870 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
4871 {
4872         int i;
4873
4874         i40e_free_misc_vector(pf);
4875
4876         i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
4877                       I40E_IWARP_IRQ_PILE_ID);
4878
4879         i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
4880         for (i = 0; i < pf->num_alloc_vsi; i++)
4881                 if (pf->vsi[i])
4882                         i40e_vsi_free_q_vectors(pf->vsi[i]);
4883         i40e_reset_interrupt_capability(pf);
4884 }
4885
4886 /**
4887  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
4888  * @vsi: the VSI being configured
4889  **/
4890 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
4891 {
4892         int q_idx;
4893
4894         if (!vsi->netdev)
4895                 return;
4896
4897         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4898                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4899
4900                 if (q_vector->rx.ring || q_vector->tx.ring)
4901                         napi_enable(&q_vector->napi);
4902         }
4903 }
4904
4905 /**
4906  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
4907  * @vsi: the VSI being configured
4908  **/
4909 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
4910 {
4911         int q_idx;
4912
4913         if (!vsi->netdev)
4914                 return;
4915
4916         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4917                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4918
4919                 if (q_vector->rx.ring || q_vector->tx.ring)
4920                         napi_disable(&q_vector->napi);
4921         }
4922 }
4923
4924 /**
4925  * i40e_vsi_close - Shut down a VSI
4926  * @vsi: the vsi to be quelled
4927  **/
4928 static void i40e_vsi_close(struct i40e_vsi *vsi)
4929 {
4930         struct i40e_pf *pf = vsi->back;
4931         if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
4932                 i40e_down(vsi);
4933         i40e_vsi_free_irq(vsi);
4934         i40e_vsi_free_tx_resources(vsi);
4935         i40e_vsi_free_rx_resources(vsi);
4936         vsi->current_netdev_flags = 0;
4937         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
4938         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4939                 set_bit(__I40E_CLIENT_RESET, pf->state);
4940 }
4941
4942 /**
4943  * i40e_quiesce_vsi - Pause a given VSI
4944  * @vsi: the VSI being paused
4945  **/
4946 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
4947 {
4948         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4949                 return;
4950
4951         set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
4952         if (vsi->netdev && netif_running(vsi->netdev))
4953                 vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
4954         else
4955                 i40e_vsi_close(vsi);
4956 }
4957
4958 /**
4959  * i40e_unquiesce_vsi - Resume a given VSI
4960  * @vsi: the VSI being resumed
4961  **/
4962 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
4963 {
4964         if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
4965                 return;
4966
4967         if (vsi->netdev && netif_running(vsi->netdev))
4968                 vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
4969         else
4970                 i40e_vsi_open(vsi);   /* this clears the DOWN bit */
4971 }
4972
4973 /**
4974  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
4975  * @pf: the PF
4976  **/
4977 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
4978 {
4979         int v;
4980
4981         for (v = 0; v < pf->num_alloc_vsi; v++) {
4982                 if (pf->vsi[v])
4983                         i40e_quiesce_vsi(pf->vsi[v]);
4984         }
4985 }
4986
4987 /**
4988  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
4989  * @pf: the PF
4990  **/
4991 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
4992 {
4993         int v;
4994
4995         for (v = 0; v < pf->num_alloc_vsi; v++) {
4996                 if (pf->vsi[v])
4997                         i40e_unquiesce_vsi(pf->vsi[v]);
4998         }
4999 }
5000
5001 /**
5002  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
5003  * @vsi: the VSI being configured
5004  *
5005  * Wait until all queues on a given VSI have been disabled.
5006  **/
5007 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
5008 {
5009         struct i40e_pf *pf = vsi->back;
5010         int i, pf_q, ret;
5011
5012         pf_q = vsi->base_queue;
5013         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
5014                 /* Check and wait for the Tx queue */
5015                 ret = i40e_pf_txq_wait(pf, pf_q, false);
5016                 if (ret) {
5017                         dev_info(&pf->pdev->dev,
5018                                  "VSI seid %d Tx ring %d disable timeout\n",
5019                                  vsi->seid, pf_q);
5020                         return ret;
5021                 }
5022
5023                 if (!i40e_enabled_xdp_vsi(vsi))
5024                         goto wait_rx;
5025
5026                 /* Check and wait for the XDP Tx queue */
5027                 ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
5028                                        false);
5029                 if (ret) {
5030                         dev_info(&pf->pdev->dev,
5031                                  "VSI seid %d XDP Tx ring %d disable timeout\n",
5032                                  vsi->seid, pf_q);
5033                         return ret;
5034                 }
5035 wait_rx:
5036                 /* Check and wait for the Rx queue */
5037                 ret = i40e_pf_rxq_wait(pf, pf_q, false);
5038                 if (ret) {
5039                         dev_info(&pf->pdev->dev,
5040                                  "VSI seid %d Rx ring %d disable timeout\n",
5041                                  vsi->seid, pf_q);
5042                         return ret;
5043                 }
5044         }
5045
5046         return 0;
5047 }
5048
5049 #ifdef CONFIG_I40E_DCB
5050 /**
5051  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
5052  * @pf: the PF
5053  *
5054  * This function waits for the queues to be in disabled state for all the
5055  * VSIs that are managed by this PF.
5056  **/
5057 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
5058 {
5059         int v, ret = 0;
5060
5061         for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
5062                 if (pf->vsi[v]) {
5063                         ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
5064                         if (ret)
5065                                 break;
5066                 }
5067         }
5068
5069         return ret;
5070 }
5071
5072 #endif
5073
5074 /**
5075  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
5076  * @pf: pointer to PF
5077  *
5078  * Get TC map for ISCSI PF type that will include iSCSI TC
5079  * and LAN TC.
5080  **/
5081 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
5082 {
5083         struct i40e_dcb_app_priority_table app;
5084         struct i40e_hw *hw = &pf->hw;
5085         u8 enabled_tc = 1; /* TC0 is always enabled */
5086         u8 tc, i;
5087         /* Get the iSCSI APP TLV */
5088         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5089
5090         for (i = 0; i < dcbcfg->numapps; i++) {
5091                 app = dcbcfg->app[i];
5092                 if (app.selector == I40E_APP_SEL_TCPIP &&
5093                     app.protocolid == I40E_APP_PROTOID_ISCSI) {
5094                         tc = dcbcfg->etscfg.prioritytable[app.priority];
5095                         enabled_tc |= BIT(tc);
5096                         break;
5097                 }
5098         }
5099
5100         return enabled_tc;
5101 }
5102
5103 /**
5104  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5105  * @dcbcfg: the corresponding DCBx configuration structure
5106  *
5107  * Return the number of TCs from given DCBx configuration
5108  **/
5109 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5110 {
5111         int i, tc_unused = 0;
5112         u8 num_tc = 0;
5113         u8 ret = 0;
5114
5115         /* Scan the ETS Config Priority Table to find
5116          * traffic class enabled for a given priority
5117          * and create a bitmask of enabled TCs
5118          */
5119         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5120                 num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5121
5122         /* Now scan the bitmask to check for
5123          * contiguous TCs starting with TC0
5124          */
5125         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5126                 if (num_tc & BIT(i)) {
5127                         if (!tc_unused) {
5128                                 ret++;
5129                         } else {
5130                                 pr_err("Non-contiguous TC - Disabling DCB\n");
5131                                 return 1;
5132                         }
5133                 } else {
5134                         tc_unused = 1;
5135                 }
5136         }
5137
5138         /* There is always at least TC0 */
5139         if (!ret)
5140                 ret = 1;
5141
5142         return ret;
5143 }
5144
5145 /**
5146  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5147  * @dcbcfg: the corresponding DCBx configuration structure
5148  *
5149  * Query the current DCB configuration and return the number of
5150  * traffic classes enabled from the given DCBX config
5151  **/
5152 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5153 {
5154         u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5155         u8 enabled_tc = 1;
5156         u8 i;
5157
5158         for (i = 0; i < num_tc; i++)
5159                 enabled_tc |= BIT(i);
5160
5161         return enabled_tc;
5162 }
5163
5164 /**
5165  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5166  * @pf: PF being queried
5167  *
5168  * Query the current MQPRIO configuration and return the number of
5169  * traffic classes enabled.
5170  **/
5171 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5172 {
5173         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5174         u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5175         u8 enabled_tc = 1, i;
5176
5177         for (i = 1; i < num_tc; i++)
5178                 enabled_tc |= BIT(i);
5179         return enabled_tc;
5180 }
5181
5182 /**
5183  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5184  * @pf: PF being queried
5185  *
5186  * Return number of traffic classes enabled for the given PF
5187  **/
5188 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5189 {
5190         struct i40e_hw *hw = &pf->hw;
5191         u8 i, enabled_tc = 1;
5192         u8 num_tc = 0;
5193         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5194
5195         if (pf->flags & I40E_FLAG_TC_MQPRIO)
5196                 return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5197
5198         /* If neither MQPRIO nor DCB is enabled, then always use single TC */
5199         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5200                 return 1;
5201
5202         /* SFP mode will be enabled for all TCs on port */
5203         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5204                 return i40e_dcb_get_num_tc(dcbcfg);
5205
5206         /* MFP mode return count of enabled TCs for this PF */
5207         if (pf->hw.func_caps.iscsi)
5208                 enabled_tc =  i40e_get_iscsi_tc_map(pf);
5209         else
5210                 return 1; /* Only TC0 */
5211
5212         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5213                 if (enabled_tc & BIT(i))
5214                         num_tc++;
5215         }
5216         return num_tc;
5217 }
5218
5219 /**
5220  * i40e_pf_get_tc_map - Get bitmap for enabled traffic classes
5221  * @pf: PF being queried
5222  *
5223  * Return a bitmap for enabled traffic classes for this PF.
5224  **/
5225 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5226 {
5227         if (pf->flags & I40E_FLAG_TC_MQPRIO)
5228                 return i40e_mqprio_get_enabled_tc(pf);
5229
5230         /* If neither MQPRIO nor DCB is enabled for this PF then just return
5231          * default TC
5232          */
5233         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5234                 return I40E_DEFAULT_TRAFFIC_CLASS;
5235
5236         /* SFP mode we want PF to be enabled for all TCs */
5237         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5238                 return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5239
5240         /* MFP enabled and iSCSI PF type */
5241         if (pf->hw.func_caps.iscsi)
5242                 return i40e_get_iscsi_tc_map(pf);
5243         else
5244                 return I40E_DEFAULT_TRAFFIC_CLASS;
5245 }
5246
5247 /**
5248  * i40e_vsi_get_bw_info - Query VSI BW Information
5249  * @vsi: the VSI being queried
5250  *
5251  * Returns 0 on success, negative value on failure
5252  **/
5253 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5254 {
5255         struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5256         struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5257         struct i40e_pf *pf = vsi->back;
5258         struct i40e_hw *hw = &pf->hw;
5259         i40e_status ret;
5260         u32 tc_bw_max;
5261         int i;
5262
5263         /* Get the VSI level BW configuration */
5264         ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5265         if (ret) {
5266                 dev_info(&pf->pdev->dev,
5267                          "couldn't get PF vsi bw config, err %s aq_err %s\n",
5268                          i40e_stat_str(&pf->hw, ret),
5269                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5270                 return -EINVAL;
5271         }
5272
5273         /* Get the VSI level BW configuration per TC */
5274         ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5275                                                NULL);
5276         if (ret) {
5277                 dev_info(&pf->pdev->dev,
5278                          "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
5279                          i40e_stat_str(&pf->hw, ret),
5280                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5281                 return -EINVAL;
5282         }
5283
5284         if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5285                 dev_info(&pf->pdev->dev,
5286                          "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5287                          bw_config.tc_valid_bits,
5288                          bw_ets_config.tc_valid_bits);
5289                 /* Still continuing */
5290         }
5291
5292         vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5293         vsi->bw_max_quanta = bw_config.max_bw;
5294         tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5295                     (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5296         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5297                 vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5298                 vsi->bw_ets_limit_credits[i] =
5299                                         le16_to_cpu(bw_ets_config.credits[i]);
5300                 /* 3 bits out of 4 for each TC */
5301                 vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5302         }
5303
5304         return 0;
5305 }
5306
5307 /**
5308  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5309  * @vsi: the VSI being configured
5310  * @enabled_tc: TC bitmap
5311  * @bw_share: BW shared credits per TC
5312  *
5313  * Returns 0 on success, negative value on failure
5314  **/
5315 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5316                                        u8 *bw_share)
5317 {
5318         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5319         struct i40e_pf *pf = vsi->back;
5320         i40e_status ret;
5321         int i;
5322
5323         /* There is no need to reset BW when mqprio mode is on.  */
5324         if (pf->flags & I40E_FLAG_TC_MQPRIO)
5325                 return 0;
5326         if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5327                 ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5328                 if (ret)
5329                         dev_info(&pf->pdev->dev,
5330                                  "Failed to reset tx rate for vsi->seid %u\n",
5331                                  vsi->seid);
5332                 return ret;
5333         }
5334         memset(&bw_data, 0, sizeof(bw_data));
5335         bw_data.tc_valid_bits = enabled_tc;
5336         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5337                 bw_data.tc_bw_credits[i] = bw_share[i];
5338
5339         ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5340         if (ret) {
5341                 dev_info(&pf->pdev->dev,
5342                          "AQ command Config VSI BW allocation per TC failed = %d\n",
5343                          pf->hw.aq.asq_last_status);
5344                 return -EINVAL;
5345         }
5346
5347         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5348                 vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5349
5350         return 0;
5351 }
5352
5353 /**
5354  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5355  * @vsi: the VSI being configured
5356  * @enabled_tc: TC map to be enabled
5357  *
5358  **/
5359 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5360 {
5361         struct net_device *netdev = vsi->netdev;
5362         struct i40e_pf *pf = vsi->back;
5363         struct i40e_hw *hw = &pf->hw;
5364         u8 netdev_tc = 0;
5365         int i;
5366         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5367
5368         if (!netdev)
5369                 return;
5370
5371         if (!enabled_tc) {
5372                 netdev_reset_tc(netdev);
5373                 return;
5374         }
5375
5376         /* Set up actual enabled TCs on the VSI */
5377         if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5378                 return;
5379
5380         /* set per TC queues for the VSI */
5381         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5382                 /* Only set TC queues for enabled tcs
5383                  *
5384                  * e.g. For a VSI that has TC0 and TC3 enabled the
5385                  * enabled_tc bitmap would be 0x00001001; the driver
5386                  * will set the numtc for netdev as 2 that will be
5387                  * referenced by the netdev layer as TC 0 and 1.
5388                  */
5389                 if (vsi->tc_config.enabled_tc & BIT(i))
5390                         netdev_set_tc_queue(netdev,
5391                                         vsi->tc_config.tc_info[i].netdev_tc,
5392                                         vsi->tc_config.tc_info[i].qcount,
5393                                         vsi->tc_config.tc_info[i].qoffset);
5394         }
5395
5396         if (pf->flags & I40E_FLAG_TC_MQPRIO)
5397                 return;
5398
5399         /* Assign UP2TC map for the VSI */
5400         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5401                 /* Get the actual TC# for the UP */
5402                 u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5403                 /* Get the mapped netdev TC# for the UP */
5404                 netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5405                 netdev_set_prio_tc_map(netdev, i, netdev_tc);
5406         }
5407 }
5408
5409 /**
5410  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5411  * @vsi: the VSI being configured
5412  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5413  **/
5414 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5415                                       struct i40e_vsi_context *ctxt)
5416 {
5417         /* copy just the sections touched not the entire info
5418          * since not all sections are valid as returned by
5419          * update vsi params
5420          */
5421         vsi->info.mapping_flags = ctxt->info.mapping_flags;
5422         memcpy(&vsi->info.queue_mapping,
5423                &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5424         memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5425                sizeof(vsi->info.tc_mapping));
5426 }
5427
5428 /**
5429  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5430  * @vsi: VSI to be configured
5431  * @enabled_tc: TC bitmap
5432  *
5433  * This configures a particular VSI for TCs that are mapped to the
5434  * given TC bitmap. It uses default bandwidth share for TCs across
5435  * VSIs to configure TC for a particular VSI.
5436  *
5437  * NOTE:
5438  * It is expected that the VSI queues have been quisced before calling
5439  * this function.
5440  **/
5441 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5442 {
5443         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5444         struct i40e_pf *pf = vsi->back;
5445         struct i40e_hw *hw = &pf->hw;
5446         struct i40e_vsi_context ctxt;
5447         int ret = 0;
5448         int i;
5449
5450         /* Check if enabled_tc is same as existing or new TCs */
5451         if (vsi->tc_config.enabled_tc == enabled_tc &&
5452             vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5453                 return ret;
5454
5455         /* Enable ETS TCs with equal BW Share for now across all VSIs */
5456         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5457                 if (enabled_tc & BIT(i))
5458                         bw_share[i] = 1;
5459         }
5460
5461         ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5462         if (ret) {
5463                 struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5464
5465                 dev_info(&pf->pdev->dev,
5466                          "Failed configuring TC map %d for VSI %d\n",
5467                          enabled_tc, vsi->seid);
5468                 ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5469                                                   &bw_config, NULL);
5470                 if (ret) {
5471                         dev_info(&pf->pdev->dev,
5472                                  "Failed querying vsi bw info, err %s aq_err %s\n",
5473                                  i40e_stat_str(hw, ret),
5474                                  i40e_aq_str(hw, hw->aq.asq_last_status));
5475                         goto out;
5476                 }
5477                 if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5478                         u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5479
5480                         if (!valid_tc)
5481                                 valid_tc = bw_config.tc_valid_bits;
5482                         /* Always enable TC0, no matter what */
5483                         valid_tc |= 1;
5484                         dev_info(&pf->pdev->dev,
5485                                  "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5486                                  enabled_tc, bw_config.tc_valid_bits, valid_tc);
5487                         enabled_tc = valid_tc;
5488                 }
5489
5490                 ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5491                 if (ret) {
5492                         dev_err(&pf->pdev->dev,
5493                                 "Unable to  configure TC map %d for VSI %d\n",
5494                                 enabled_tc, vsi->seid);
5495                         goto out;
5496                 }
5497         }
5498
5499         /* Update Queue Pairs Mapping for currently enabled UPs */
5500         ctxt.seid = vsi->seid;
5501         ctxt.pf_num = vsi->back->hw.pf_id;
5502         ctxt.vf_num = 0;
5503         ctxt.uplink_seid = vsi->uplink_seid;
5504         ctxt.info = vsi->info;
5505         if (vsi->back->flags & I40E_FLAG_TC_MQPRIO) {
5506                 ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5507                 if (ret)
5508                         goto out;
5509         } else {
5510                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5511         }
5512
5513         /* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5514          * queues changed.
5515          */
5516         if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5517                 vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5518                                       vsi->num_queue_pairs);
5519                 ret = i40e_vsi_config_rss(vsi);
5520                 if (ret) {
5521                         dev_info(&vsi->back->pdev->dev,
5522                                  "Failed to reconfig rss for num_queues\n");
5523                         return ret;
5524                 }
5525                 vsi->reconfig_rss = false;
5526         }
5527         if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5528                 ctxt.info.valid_sections |=
5529                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5530                 ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5531         }
5532
5533         /* Update the VSI after updating the VSI queue-mapping
5534          * information
5535          */
5536         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5537         if (ret) {
5538                 dev_info(&pf->pdev->dev,
5539                          "Update vsi tc config failed, err %s aq_err %s\n",
5540                          i40e_stat_str(hw, ret),
5541                          i40e_aq_str(hw, hw->aq.asq_last_status));
5542                 goto out;
5543         }
5544         /* update the local VSI info with updated queue map */
5545         i40e_vsi_update_queue_map(vsi, &ctxt);
5546         vsi->info.valid_sections = 0;
5547
5548         /* Update current VSI BW information */
5549         ret = i40e_vsi_get_bw_info(vsi);
5550         if (ret) {
5551                 dev_info(&pf->pdev->dev,
5552                          "Failed updating vsi bw info, err %s aq_err %s\n",
5553                          i40e_stat_str(hw, ret),
5554                          i40e_aq_str(hw, hw->aq.asq_last_status));
5555                 goto out;
5556         }
5557
5558         /* Update the netdev TC setup */
5559         i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5560 out:
5561         return ret;
5562 }
5563
5564 /**
5565  * i40e_get_link_speed - Returns link speed for the interface
5566  * @vsi: VSI to be configured
5567  *
5568  **/
5569 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5570 {
5571         struct i40e_pf *pf = vsi->back;
5572
5573         switch (pf->hw.phy.link_info.link_speed) {
5574         case I40E_LINK_SPEED_40GB:
5575                 return 40000;
5576         case I40E_LINK_SPEED_25GB:
5577                 return 25000;
5578         case I40E_LINK_SPEED_20GB:
5579                 return 20000;
5580         case I40E_LINK_SPEED_10GB:
5581                 return 10000;
5582         case I40E_LINK_SPEED_1GB:
5583                 return 1000;
5584         default:
5585                 return -EINVAL;
5586         }
5587 }
5588
5589 /**
5590  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5591  * @vsi: VSI to be configured
5592  * @seid: seid of the channel/VSI
5593  * @max_tx_rate: max TX rate to be configured as BW limit
5594  *
5595  * Helper function to set BW limit for a given VSI
5596  **/
5597 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5598 {
5599         struct i40e_pf *pf = vsi->back;
5600         u64 credits = 0;
5601         int speed = 0;
5602         int ret = 0;
5603
5604         speed = i40e_get_link_speed(vsi);
5605         if (max_tx_rate > speed) {
5606                 dev_err(&pf->pdev->dev,
5607                         "Invalid max tx rate %llu specified for VSI seid %d.",
5608                         max_tx_rate, seid);
5609                 return -EINVAL;
5610         }
5611         if (max_tx_rate && max_tx_rate < 50) {
5612                 dev_warn(&pf->pdev->dev,
5613                          "Setting max tx rate to minimum usable value of 50Mbps.\n");
5614                 max_tx_rate = 50;
5615         }
5616
5617         /* Tx rate credits are in values of 50Mbps, 0 is disabled */
5618         credits = max_tx_rate;
5619         do_div(credits, I40E_BW_CREDIT_DIVISOR);
5620         ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5621                                           I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5622         if (ret)
5623                 dev_err(&pf->pdev->dev,
5624                         "Failed set tx rate (%llu Mbps) for vsi->seid %u, err %s aq_err %s\n",
5625                         max_tx_rate, seid, i40e_stat_str(&pf->hw, ret),
5626                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5627         return ret;
5628 }
5629
5630 /**
5631  * i40e_remove_queue_channels - Remove queue channels for the TCs
5632  * @vsi: VSI to be configured
5633  *
5634  * Remove queue channels for the TCs
5635  **/
5636 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5637 {
5638         enum i40e_admin_queue_err last_aq_status;
5639         struct i40e_cloud_filter *cfilter;
5640         struct i40e_channel *ch, *ch_tmp;
5641         struct i40e_pf *pf = vsi->back;
5642         struct hlist_node *node;
5643         int ret, i;
5644
5645         /* Reset rss size that was stored when reconfiguring rss for
5646          * channel VSIs with non-power-of-2 queue count.
5647          */
5648         vsi->current_rss_size = 0;
5649
5650         /* perform cleanup for channels if they exist */
5651         if (list_empty(&vsi->ch_list))
5652                 return;
5653
5654         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5655                 struct i40e_vsi *p_vsi;
5656
5657                 list_del(&ch->list);
5658                 p_vsi = ch->parent_vsi;
5659                 if (!p_vsi || !ch->initialized) {
5660                         kfree(ch);
5661                         continue;
5662                 }
5663                 /* Reset queue contexts */
5664                 for (i = 0; i < ch->num_queue_pairs; i++) {
5665                         struct i40e_ring *tx_ring, *rx_ring;
5666                         u16 pf_q;
5667
5668                         pf_q = ch->base_queue + i;
5669                         tx_ring = vsi->tx_rings[pf_q];
5670                         tx_ring->ch = NULL;
5671
5672                         rx_ring = vsi->rx_rings[pf_q];
5673                         rx_ring->ch = NULL;
5674                 }
5675
5676                 /* Reset BW configured for this VSI via mqprio */
5677                 ret = i40e_set_bw_limit(vsi, ch->seid, 0);
5678                 if (ret)
5679                         dev_info(&vsi->back->pdev->dev,
5680                                  "Failed to reset tx rate for ch->seid %u\n",
5681                                  ch->seid);
5682
5683                 /* delete cloud filters associated with this channel */
5684                 hlist_for_each_entry_safe(cfilter, node,
5685                                           &pf->cloud_filter_list, cloud_node) {
5686                         if (cfilter->seid != ch->seid)
5687                                 continue;
5688
5689                         hash_del(&cfilter->cloud_node);
5690                         if (cfilter->dst_port)
5691                                 ret = i40e_add_del_cloud_filter_big_buf(vsi,
5692                                                                         cfilter,
5693                                                                         false);
5694                         else
5695                                 ret = i40e_add_del_cloud_filter(vsi, cfilter,
5696                                                                 false);
5697                         last_aq_status = pf->hw.aq.asq_last_status;
5698                         if (ret)
5699                                 dev_info(&pf->pdev->dev,
5700                                          "Failed to delete cloud filter, err %s aq_err %s\n",
5701                                          i40e_stat_str(&pf->hw, ret),
5702                                          i40e_aq_str(&pf->hw, last_aq_status));
5703                         kfree(cfilter);
5704                 }
5705
5706                 /* delete VSI from FW */
5707                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
5708                                              NULL);
5709                 if (ret)
5710                         dev_err(&vsi->back->pdev->dev,
5711                                 "unable to remove channel (%d) for parent VSI(%d)\n",
5712                                 ch->seid, p_vsi->seid);
5713                 kfree(ch);
5714         }
5715         INIT_LIST_HEAD(&vsi->ch_list);
5716 }
5717
5718 /**
5719  * i40e_is_any_channel - channel exist or not
5720  * @vsi: ptr to VSI to which channels are associated with
5721  *
5722  * Returns true or false if channel(s) exist for associated VSI or not
5723  **/
5724 static bool i40e_is_any_channel(struct i40e_vsi *vsi)
5725 {
5726         struct i40e_channel *ch, *ch_tmp;
5727
5728         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5729                 if (ch->initialized)
5730                         return true;
5731         }
5732
5733         return false;
5734 }
5735
5736 /**
5737  * i40e_get_max_queues_for_channel
5738  * @vsi: ptr to VSI to which channels are associated with
5739  *
5740  * Helper function which returns max value among the queue counts set on the
5741  * channels/TCs created.
5742  **/
5743 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
5744 {
5745         struct i40e_channel *ch, *ch_tmp;
5746         int max = 0;
5747
5748         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5749                 if (!ch->initialized)
5750                         continue;
5751                 if (ch->num_queue_pairs > max)
5752                         max = ch->num_queue_pairs;
5753         }
5754
5755         return max;
5756 }
5757
5758 /**
5759  * i40e_validate_num_queues - validate num_queues w.r.t channel
5760  * @pf: ptr to PF device
5761  * @num_queues: number of queues
5762  * @vsi: the parent VSI
5763  * @reconfig_rss: indicates should the RSS be reconfigured or not
5764  *
5765  * This function validates number of queues in the context of new channel
5766  * which is being established and determines if RSS should be reconfigured
5767  * or not for parent VSI.
5768  **/
5769 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
5770                                     struct i40e_vsi *vsi, bool *reconfig_rss)
5771 {
5772         int max_ch_queues;
5773
5774         if (!reconfig_rss)
5775                 return -EINVAL;
5776
5777         *reconfig_rss = false;
5778         if (vsi->current_rss_size) {
5779                 if (num_queues > vsi->current_rss_size) {
5780                         dev_dbg(&pf->pdev->dev,
5781                                 "Error: num_queues (%d) > vsi's current_size(%d)\n",
5782                                 num_queues, vsi->current_rss_size);
5783                         return -EINVAL;
5784                 } else if ((num_queues < vsi->current_rss_size) &&
5785                            (!is_power_of_2(num_queues))) {
5786                         dev_dbg(&pf->pdev->dev,
5787                                 "Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
5788                                 num_queues, vsi->current_rss_size);
5789                         return -EINVAL;
5790                 }
5791         }
5792
5793         if (!is_power_of_2(num_queues)) {
5794                 /* Find the max num_queues configured for channel if channel
5795                  * exist.
5796                  * if channel exist, then enforce 'num_queues' to be more than
5797                  * max ever queues configured for channel.
5798                  */
5799                 max_ch_queues = i40e_get_max_queues_for_channel(vsi);
5800                 if (num_queues < max_ch_queues) {
5801                         dev_dbg(&pf->pdev->dev,
5802                                 "Error: num_queues (%d) < max queues configured for channel(%d)\n",
5803                                 num_queues, max_ch_queues);
5804                         return -EINVAL;
5805                 }
5806                 *reconfig_rss = true;
5807         }
5808
5809         return 0;
5810 }
5811
5812 /**
5813  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
5814  * @vsi: the VSI being setup
5815  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
5816  *
5817  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
5818  **/
5819 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
5820 {
5821         struct i40e_pf *pf = vsi->back;
5822         u8 seed[I40E_HKEY_ARRAY_SIZE];
5823         struct i40e_hw *hw = &pf->hw;
5824         int local_rss_size;
5825         u8 *lut;
5826         int ret;
5827
5828         if (!vsi->rss_size)
5829                 return -EINVAL;
5830
5831         if (rss_size > vsi->rss_size)
5832                 return -EINVAL;
5833
5834         local_rss_size = min_t(int, vsi->rss_size, rss_size);
5835         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
5836         if (!lut)
5837                 return -ENOMEM;
5838
5839         /* Ignoring user configured lut if there is one */
5840         i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
5841
5842         /* Use user configured hash key if there is one, otherwise
5843          * use default.
5844          */
5845         if (vsi->rss_hkey_user)
5846                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
5847         else
5848                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
5849
5850         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
5851         if (ret) {
5852                 dev_info(&pf->pdev->dev,
5853                          "Cannot set RSS lut, err %s aq_err %s\n",
5854                          i40e_stat_str(hw, ret),
5855                          i40e_aq_str(hw, hw->aq.asq_last_status));
5856                 kfree(lut);
5857                 return ret;
5858         }
5859         kfree(lut);
5860
5861         /* Do the update w.r.t. storing rss_size */
5862         if (!vsi->orig_rss_size)
5863                 vsi->orig_rss_size = vsi->rss_size;
5864         vsi->current_rss_size = local_rss_size;
5865
5866         return ret;
5867 }
5868
5869 /**
5870  * i40e_channel_setup_queue_map - Setup a channel queue map
5871  * @pf: ptr to PF device
5872  * @ctxt: VSI context structure
5873  * @ch: ptr to channel structure
5874  *
5875  * Setup queue map for a specific channel
5876  **/
5877 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
5878                                          struct i40e_vsi_context *ctxt,
5879                                          struct i40e_channel *ch)
5880 {
5881         u16 qcount, qmap, sections = 0;
5882         u8 offset = 0;
5883         int pow;
5884
5885         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
5886         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
5887
5888         qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
5889         ch->num_queue_pairs = qcount;
5890
5891         /* find the next higher power-of-2 of num queue pairs */
5892         pow = ilog2(qcount);
5893         if (!is_power_of_2(qcount))
5894                 pow++;
5895
5896         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
5897                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
5898
5899         /* Setup queue TC[0].qmap for given VSI context */
5900         ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
5901
5902         ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
5903         ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
5904         ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
5905         ctxt->info.valid_sections |= cpu_to_le16(sections);
5906 }
5907
5908 /**
5909  * i40e_add_channel - add a channel by adding VSI
5910  * @pf: ptr to PF device
5911  * @uplink_seid: underlying HW switching element (VEB) ID
5912  * @ch: ptr to channel structure
5913  *
5914  * Add a channel (VSI) using add_vsi and queue_map
5915  **/
5916 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
5917                             struct i40e_channel *ch)
5918 {
5919         struct i40e_hw *hw = &pf->hw;
5920         struct i40e_vsi_context ctxt;
5921         u8 enabled_tc = 0x1; /* TC0 enabled */
5922         int ret;
5923
5924         if (ch->type != I40E_VSI_VMDQ2) {
5925                 dev_info(&pf->pdev->dev,
5926                          "add new vsi failed, ch->type %d\n", ch->type);
5927                 return -EINVAL;
5928         }
5929
5930         memset(&ctxt, 0, sizeof(ctxt));
5931         ctxt.pf_num = hw->pf_id;
5932         ctxt.vf_num = 0;
5933         ctxt.uplink_seid = uplink_seid;
5934         ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5935         if (ch->type == I40E_VSI_VMDQ2)
5936                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
5937
5938         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
5939                 ctxt.info.valid_sections |=
5940                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
5941                 ctxt.info.switch_id =
5942                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
5943         }
5944
5945         /* Set queue map for a given VSI context */
5946         i40e_channel_setup_queue_map(pf, &ctxt, ch);
5947
5948         /* Now time to create VSI */
5949         ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
5950         if (ret) {
5951                 dev_info(&pf->pdev->dev,
5952                          "add new vsi failed, err %s aq_err %s\n",
5953                          i40e_stat_str(&pf->hw, ret),
5954                          i40e_aq_str(&pf->hw,
5955                                      pf->hw.aq.asq_last_status));
5956                 return -ENOENT;
5957         }
5958
5959         /* Success, update channel, set enabled_tc only if the channel
5960          * is not a macvlan
5961          */
5962         ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
5963         ch->seid = ctxt.seid;
5964         ch->vsi_number = ctxt.vsi_number;
5965         ch->stat_counter_idx = le16_to_cpu(ctxt.info.stat_counter_idx);
5966
5967         /* copy just the sections touched not the entire info
5968          * since not all sections are valid as returned by
5969          * update vsi params
5970          */
5971         ch->info.mapping_flags = ctxt.info.mapping_flags;
5972         memcpy(&ch->info.queue_mapping,
5973                &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
5974         memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
5975                sizeof(ctxt.info.tc_mapping));
5976
5977         return 0;
5978 }
5979
5980 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
5981                                   u8 *bw_share)
5982 {
5983         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5984         i40e_status ret;
5985         int i;
5986
5987         memset(&bw_data, 0, sizeof(bw_data));
5988         bw_data.tc_valid_bits = ch->enabled_tc;
5989         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5990                 bw_data.tc_bw_credits[i] = bw_share[i];
5991
5992         ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
5993                                        &bw_data, NULL);
5994         if (ret) {
5995                 dev_info(&vsi->back->pdev->dev,
5996                          "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
5997                          vsi->back->hw.aq.asq_last_status, ch->seid);
5998                 return -EINVAL;
5999         }
6000
6001         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
6002                 ch->info.qs_handle[i] = bw_data.qs_handles[i];
6003
6004         return 0;
6005 }
6006
6007 /**
6008  * i40e_channel_config_tx_ring - config TX ring associated with new channel
6009  * @pf: ptr to PF device
6010  * @vsi: the VSI being setup
6011  * @ch: ptr to channel structure
6012  *
6013  * Configure TX rings associated with channel (VSI) since queues are being
6014  * from parent VSI.
6015  **/
6016 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
6017                                        struct i40e_vsi *vsi,
6018                                        struct i40e_channel *ch)
6019 {
6020         i40e_status ret;
6021         int i;
6022         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
6023
6024         /* Enable ETS TCs with equal BW Share for now across all VSIs */
6025         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6026                 if (ch->enabled_tc & BIT(i))
6027                         bw_share[i] = 1;
6028         }
6029
6030         /* configure BW for new VSI */
6031         ret = i40e_channel_config_bw(vsi, ch, bw_share);
6032         if (ret) {
6033                 dev_info(&vsi->back->pdev->dev,
6034                          "Failed configuring TC map %d for channel (seid %u)\n",
6035                          ch->enabled_tc, ch->seid);
6036                 return ret;
6037         }
6038
6039         for (i = 0; i < ch->num_queue_pairs; i++) {
6040                 struct i40e_ring *tx_ring, *rx_ring;
6041                 u16 pf_q;
6042
6043                 pf_q = ch->base_queue + i;
6044
6045                 /* Get to TX ring ptr of main VSI, for re-setup TX queue
6046                  * context
6047                  */
6048                 tx_ring = vsi->tx_rings[pf_q];
6049                 tx_ring->ch = ch;
6050
6051                 /* Get the RX ring ptr */
6052                 rx_ring = vsi->rx_rings[pf_q];
6053                 rx_ring->ch = ch;
6054         }
6055
6056         return 0;
6057 }
6058
6059 /**
6060  * i40e_setup_hw_channel - setup new channel
6061  * @pf: ptr to PF device
6062  * @vsi: the VSI being setup
6063  * @ch: ptr to channel structure
6064  * @uplink_seid: underlying HW switching element (VEB) ID
6065  * @type: type of channel to be created (VMDq2/VF)
6066  *
6067  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6068  * and configures TX rings accordingly
6069  **/
6070 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
6071                                         struct i40e_vsi *vsi,
6072                                         struct i40e_channel *ch,
6073                                         u16 uplink_seid, u8 type)
6074 {
6075         int ret;
6076
6077         ch->initialized = false;
6078         ch->base_queue = vsi->next_base_queue;
6079         ch->type = type;
6080
6081         /* Proceed with creation of channel (VMDq2) VSI */
6082         ret = i40e_add_channel(pf, uplink_seid, ch);
6083         if (ret) {
6084                 dev_info(&pf->pdev->dev,
6085                          "failed to add_channel using uplink_seid %u\n",
6086                          uplink_seid);
6087                 return ret;
6088         }
6089
6090         /* Mark the successful creation of channel */
6091         ch->initialized = true;
6092
6093         /* Reconfigure TX queues using QTX_CTL register */
6094         ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6095         if (ret) {
6096                 dev_info(&pf->pdev->dev,
6097                          "failed to configure TX rings for channel %u\n",
6098                          ch->seid);
6099                 return ret;
6100         }
6101
6102         /* update 'next_base_queue' */
6103         vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6104         dev_dbg(&pf->pdev->dev,
6105                 "Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6106                 ch->seid, ch->vsi_number, ch->stat_counter_idx,
6107                 ch->num_queue_pairs,
6108                 vsi->next_base_queue);
6109         return ret;
6110 }
6111
6112 /**
6113  * i40e_setup_channel - setup new channel using uplink element
6114  * @pf: ptr to PF device
6115  * @vsi: pointer to the VSI to set up the channel within
6116  * @ch: ptr to channel structure
6117  *
6118  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6119  * and uplink switching element (uplink_seid)
6120  **/
6121 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6122                                struct i40e_channel *ch)
6123 {
6124         u8 vsi_type;
6125         u16 seid;
6126         int ret;
6127
6128         if (vsi->type == I40E_VSI_MAIN) {
6129                 vsi_type = I40E_VSI_VMDQ2;
6130         } else {
6131                 dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6132                         vsi->type);
6133                 return false;
6134         }
6135
6136         /* underlying switching element */
6137         seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6138
6139         /* create channel (VSI), configure TX rings */
6140         ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6141         if (ret) {
6142                 dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6143                 return false;
6144         }
6145
6146         return ch->initialized ? true : false;
6147 }
6148
6149 /**
6150  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6151  * @vsi: ptr to VSI which has PF backing
6152  *
6153  * Sets up switch mode correctly if it needs to be changed and perform
6154  * what are allowed modes.
6155  **/
6156 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6157 {
6158         u8 mode;
6159         struct i40e_pf *pf = vsi->back;
6160         struct i40e_hw *hw = &pf->hw;
6161         int ret;
6162
6163         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6164         if (ret)
6165                 return -EINVAL;
6166
6167         if (hw->dev_caps.switch_mode) {
6168                 /* if switch mode is set, support mode2 (non-tunneled for
6169                  * cloud filter) for now
6170                  */
6171                 u32 switch_mode = hw->dev_caps.switch_mode &
6172                                   I40E_SWITCH_MODE_MASK;
6173                 if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6174                         if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6175                                 return 0;
6176                         dev_err(&pf->pdev->dev,
6177                                 "Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6178                                 hw->dev_caps.switch_mode);
6179                         return -EINVAL;
6180                 }
6181         }
6182
6183         /* Set Bit 7 to be valid */
6184         mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6185
6186         /* Set L4type for TCP support */
6187         mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6188
6189         /* Set cloud filter mode */
6190         mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6191
6192         /* Prep mode field for set_switch_config */
6193         ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6194                                         pf->last_sw_conf_valid_flags,
6195                                         mode, NULL);
6196         if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6197                 dev_err(&pf->pdev->dev,
6198                         "couldn't set switch config bits, err %s aq_err %s\n",
6199                         i40e_stat_str(hw, ret),
6200                         i40e_aq_str(hw,
6201                                     hw->aq.asq_last_status));
6202
6203         return ret;
6204 }
6205
6206 /**
6207  * i40e_create_queue_channel - function to create channel
6208  * @vsi: VSI to be configured
6209  * @ch: ptr to channel (it contains channel specific params)
6210  *
6211  * This function creates channel (VSI) using num_queues specified by user,
6212  * reconfigs RSS if needed.
6213  **/
6214 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6215                               struct i40e_channel *ch)
6216 {
6217         struct i40e_pf *pf = vsi->back;
6218         bool reconfig_rss;
6219         int err;
6220
6221         if (!ch)
6222                 return -EINVAL;
6223
6224         if (!ch->num_queue_pairs) {
6225                 dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6226                         ch->num_queue_pairs);
6227                 return -EINVAL;
6228         }
6229
6230         /* validate user requested num_queues for channel */
6231         err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6232                                        &reconfig_rss);
6233         if (err) {
6234                 dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6235                          ch->num_queue_pairs);
6236                 return -EINVAL;
6237         }
6238
6239         /* By default we are in VEPA mode, if this is the first VF/VMDq
6240          * VSI to be added switch to VEB mode.
6241          */
6242         if ((!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) ||
6243             (!i40e_is_any_channel(vsi))) {
6244                 if (!is_power_of_2(vsi->tc_config.tc_info[0].qcount)) {
6245                         dev_dbg(&pf->pdev->dev,
6246                                 "Failed to create channel. Override queues (%u) not power of 2\n",
6247                                 vsi->tc_config.tc_info[0].qcount);
6248                         return -EINVAL;
6249                 }
6250
6251                 if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6252                         pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6253
6254                         if (vsi->type == I40E_VSI_MAIN) {
6255                                 if (pf->flags & I40E_FLAG_TC_MQPRIO)
6256                                         i40e_do_reset(pf, I40E_PF_RESET_FLAG,
6257                                                       true);
6258                                 else
6259                                         i40e_do_reset_safe(pf,
6260                                                            I40E_PF_RESET_FLAG);
6261                         }
6262                 }
6263                 /* now onwards for main VSI, number of queues will be value
6264                  * of TC0's queue count
6265                  */
6266         }
6267
6268         /* By this time, vsi->cnt_q_avail shall be set to non-zero and
6269          * it should be more than num_queues
6270          */
6271         if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6272                 dev_dbg(&pf->pdev->dev,
6273                         "Error: cnt_q_avail (%u) less than num_queues %d\n",
6274                         vsi->cnt_q_avail, ch->num_queue_pairs);
6275                 return -EINVAL;
6276         }
6277
6278         /* reconfig_rss only if vsi type is MAIN_VSI */
6279         if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6280                 err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6281                 if (err) {
6282                         dev_info(&pf->pdev->dev,
6283                                  "Error: unable to reconfig rss for num_queues (%u)\n",
6284                                  ch->num_queue_pairs);
6285                         return -EINVAL;
6286                 }
6287         }
6288
6289         if (!i40e_setup_channel(pf, vsi, ch)) {
6290                 dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6291                 return -EINVAL;
6292         }
6293
6294         dev_info(&pf->pdev->dev,
6295                  "Setup channel (id:%u) utilizing num_queues %d\n",
6296                  ch->seid, ch->num_queue_pairs);
6297
6298         /* configure VSI for BW limit */
6299         if (ch->max_tx_rate) {
6300                 u64 credits = ch->max_tx_rate;
6301
6302                 if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6303                         return -EINVAL;
6304
6305                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
6306                 dev_dbg(&pf->pdev->dev,
6307                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6308                         ch->max_tx_rate,
6309                         credits,
6310                         ch->seid);
6311         }
6312
6313         /* in case of VF, this will be main SRIOV VSI */
6314         ch->parent_vsi = vsi;
6315
6316         /* and update main_vsi's count for queue_available to use */
6317         vsi->cnt_q_avail -= ch->num_queue_pairs;
6318
6319         return 0;
6320 }
6321
6322 /**
6323  * i40e_configure_queue_channels - Add queue channel for the given TCs
6324  * @vsi: VSI to be configured
6325  *
6326  * Configures queue channel mapping to the given TCs
6327  **/
6328 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6329 {
6330         struct i40e_channel *ch;
6331         u64 max_rate = 0;
6332         int ret = 0, i;
6333
6334         /* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6335         vsi->tc_seid_map[0] = vsi->seid;
6336         for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6337                 if (vsi->tc_config.enabled_tc & BIT(i)) {
6338                         ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6339                         if (!ch) {
6340                                 ret = -ENOMEM;
6341                                 goto err_free;
6342                         }
6343
6344                         INIT_LIST_HEAD(&ch->list);
6345                         ch->num_queue_pairs =
6346                                 vsi->tc_config.tc_info[i].qcount;
6347                         ch->base_queue =
6348                                 vsi->tc_config.tc_info[i].qoffset;
6349
6350                         /* Bandwidth limit through tc interface is in bytes/s,
6351                          * change to Mbit/s
6352                          */
6353                         max_rate = vsi->mqprio_qopt.max_rate[i];
6354                         do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6355                         ch->max_tx_rate = max_rate;
6356
6357                         list_add_tail(&ch->list, &vsi->ch_list);
6358
6359                         ret = i40e_create_queue_channel(vsi, ch);
6360                         if (ret) {
6361                                 dev_err(&vsi->back->pdev->dev,
6362                                         "Failed creating queue channel with TC%d: queues %d\n",
6363                                         i, ch->num_queue_pairs);
6364                                 goto err_free;
6365                         }
6366                         vsi->tc_seid_map[i] = ch->seid;
6367                 }
6368         }
6369         return ret;
6370
6371 err_free:
6372         i40e_remove_queue_channels(vsi);
6373         return ret;
6374 }
6375
6376 /**
6377  * i40e_veb_config_tc - Configure TCs for given VEB
6378  * @veb: given VEB
6379  * @enabled_tc: TC bitmap
6380  *
6381  * Configures given TC bitmap for VEB (switching) element
6382  **/
6383 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6384 {
6385         struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6386         struct i40e_pf *pf = veb->pf;
6387         int ret = 0;
6388         int i;
6389
6390         /* No TCs or already enabled TCs just return */
6391         if (!enabled_tc || veb->enabled_tc == enabled_tc)
6392                 return ret;
6393
6394         bw_data.tc_valid_bits = enabled_tc;
6395         /* bw_data.absolute_credits is not set (relative) */
6396
6397         /* Enable ETS TCs with equal BW Share for now */
6398         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6399                 if (enabled_tc & BIT(i))
6400                         bw_data.tc_bw_share_credits[i] = 1;
6401         }
6402
6403         ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6404                                                    &bw_data, NULL);
6405         if (ret) {
6406                 dev_info(&pf->pdev->dev,
6407                          "VEB bw config failed, err %s aq_err %s\n",
6408                          i40e_stat_str(&pf->hw, ret),
6409                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6410                 goto out;
6411         }
6412
6413         /* Update the BW information */
6414         ret = i40e_veb_get_bw_info(veb);
6415         if (ret) {
6416                 dev_info(&pf->pdev->dev,
6417                          "Failed getting veb bw config, err %s aq_err %s\n",
6418                          i40e_stat_str(&pf->hw, ret),
6419                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6420         }
6421
6422 out:
6423         return ret;
6424 }
6425
6426 #ifdef CONFIG_I40E_DCB
6427 /**
6428  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6429  * @pf: PF struct
6430  *
6431  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6432  * the caller would've quiesce all the VSIs before calling
6433  * this function
6434  **/
6435 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6436 {
6437         u8 tc_map = 0;
6438         int ret;
6439         u8 v;
6440
6441         /* Enable the TCs available on PF to all VEBs */
6442         tc_map = i40e_pf_get_tc_map(pf);
6443         if (tc_map == I40E_DEFAULT_TRAFFIC_CLASS)
6444                 return;
6445
6446         for (v = 0; v < I40E_MAX_VEB; v++) {
6447                 if (!pf->veb[v])
6448                         continue;
6449                 ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6450                 if (ret) {
6451                         dev_info(&pf->pdev->dev,
6452                                  "Failed configuring TC for VEB seid=%d\n",
6453                                  pf->veb[v]->seid);
6454                         /* Will try to configure as many components */
6455                 }
6456         }
6457
6458         /* Update each VSI */
6459         for (v = 0; v < pf->num_alloc_vsi; v++) {
6460                 if (!pf->vsi[v])
6461                         continue;
6462
6463                 /* - Enable all TCs for the LAN VSI
6464                  * - For all others keep them at TC0 for now
6465                  */
6466                 if (v == pf->lan_vsi)
6467                         tc_map = i40e_pf_get_tc_map(pf);
6468                 else
6469                         tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6470
6471                 ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6472                 if (ret) {
6473                         dev_info(&pf->pdev->dev,
6474                                  "Failed configuring TC for VSI seid=%d\n",
6475                                  pf->vsi[v]->seid);
6476                         /* Will try to configure as many components */
6477                 } else {
6478                         /* Re-configure VSI vectors based on updated TC map */
6479                         i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6480                         if (pf->vsi[v]->netdev)
6481                                 i40e_dcbnl_set_all(pf->vsi[v]);
6482                 }
6483         }
6484 }
6485
6486 /**
6487  * i40e_resume_port_tx - Resume port Tx
6488  * @pf: PF struct
6489  *
6490  * Resume a port's Tx and issue a PF reset in case of failure to
6491  * resume.
6492  **/
6493 static int i40e_resume_port_tx(struct i40e_pf *pf)
6494 {
6495         struct i40e_hw *hw = &pf->hw;
6496         int ret;
6497
6498         ret = i40e_aq_resume_port_tx(hw, NULL);
6499         if (ret) {
6500                 dev_info(&pf->pdev->dev,
6501                          "Resume Port Tx failed, err %s aq_err %s\n",
6502                           i40e_stat_str(&pf->hw, ret),
6503                           i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6504                 /* Schedule PF reset to recover */
6505                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6506                 i40e_service_event_schedule(pf);
6507         }
6508
6509         return ret;
6510 }
6511
6512 /**
6513  * i40e_suspend_port_tx - Suspend port Tx
6514  * @pf: PF struct
6515  *
6516  * Suspend a port's Tx and issue a PF reset in case of failure.
6517  **/
6518 static int i40e_suspend_port_tx(struct i40e_pf *pf)
6519 {
6520         struct i40e_hw *hw = &pf->hw;
6521         int ret;
6522
6523         ret = i40e_aq_suspend_port_tx(hw, pf->mac_seid, NULL);
6524         if (ret) {
6525                 dev_info(&pf->pdev->dev,
6526                          "Suspend Port Tx failed, err %s aq_err %s\n",
6527                          i40e_stat_str(&pf->hw, ret),
6528                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6529                 /* Schedule PF reset to recover */
6530                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6531                 i40e_service_event_schedule(pf);
6532         }
6533
6534         return ret;
6535 }
6536
6537 /**
6538  * i40e_hw_set_dcb_config - Program new DCBX settings into HW
6539  * @pf: PF being configured
6540  * @new_cfg: New DCBX configuration
6541  *
6542  * Program DCB settings into HW and reconfigure VEB/VSIs on
6543  * given PF. Uses "Set LLDP MIB" AQC to program the hardware.
6544  **/
6545 static int i40e_hw_set_dcb_config(struct i40e_pf *pf,
6546                                   struct i40e_dcbx_config *new_cfg)
6547 {
6548         struct i40e_dcbx_config *old_cfg = &pf->hw.local_dcbx_config;
6549         int ret;
6550
6551         /* Check if need reconfiguration */
6552         if (!memcmp(&new_cfg, &old_cfg, sizeof(new_cfg))) {
6553                 dev_dbg(&pf->pdev->dev, "No Change in DCB Config required.\n");
6554                 return 0;
6555         }
6556
6557         /* Config change disable all VSIs */
6558         i40e_pf_quiesce_all_vsi(pf);
6559
6560         /* Copy the new config to the current config */
6561         *old_cfg = *new_cfg;
6562         old_cfg->etsrec = old_cfg->etscfg;
6563         ret = i40e_set_dcb_config(&pf->hw);
6564         if (ret) {
6565                 dev_info(&pf->pdev->dev,
6566                          "Set DCB Config failed, err %s aq_err %s\n",
6567                          i40e_stat_str(&pf->hw, ret),
6568                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6569                 goto out;
6570         }
6571
6572         /* Changes in configuration update VEB/VSI */
6573         i40e_dcb_reconfigure(pf);
6574 out:
6575         /* In case of reset do not try to resume anything */
6576         if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
6577                 /* Re-start the VSIs if disabled */
6578                 ret = i40e_resume_port_tx(pf);
6579                 /* In case of error no point in resuming VSIs */
6580                 if (ret)
6581                         goto err;
6582                 i40e_pf_unquiesce_all_vsi(pf);
6583         }
6584 err:
6585         return ret;
6586 }
6587
6588 /**
6589  * i40e_hw_dcb_config - Program new DCBX settings into HW
6590  * @pf: PF being configured
6591  * @new_cfg: New DCBX configuration
6592  *
6593  * Program DCB settings into HW and reconfigure VEB/VSIs on
6594  * given PF
6595  **/
6596 int i40e_hw_dcb_config(struct i40e_pf *pf, struct i40e_dcbx_config *new_cfg)
6597 {
6598         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6599         u8 prio_type[I40E_MAX_TRAFFIC_CLASS] = {0};
6600         u32 mfs_tc[I40E_MAX_TRAFFIC_CLASS];
6601         struct i40e_dcbx_config *old_cfg;
6602         u8 mode[I40E_MAX_TRAFFIC_CLASS];
6603         struct i40e_rx_pb_config pb_cfg;
6604         struct i40e_hw *hw = &pf->hw;
6605         u8 num_ports = hw->num_ports;
6606         bool need_reconfig;
6607         int ret = -EINVAL;
6608         u8 lltc_map = 0;
6609         u8 tc_map = 0;
6610         u8 new_numtc;
6611         u8 i;
6612
6613         dev_dbg(&pf->pdev->dev, "Configuring DCB registers directly\n");
6614         /* Un-pack information to Program ETS HW via shared API
6615          * numtc, tcmap
6616          * LLTC map
6617          * ETS/NON-ETS arbiter mode
6618          * max exponent (credit refills)
6619          * Total number of ports
6620          * PFC priority bit-map
6621          * Priority Table
6622          * BW % per TC
6623          * Arbiter mode between UPs sharing same TC
6624          * TSA table (ETS or non-ETS)
6625          * EEE enabled or not
6626          * MFS TC table
6627          */
6628
6629         new_numtc = i40e_dcb_get_num_tc(new_cfg);
6630
6631         memset(&ets_data, 0, sizeof(ets_data));
6632         for (i = 0; i < new_numtc; i++) {
6633                 tc_map |= BIT(i);
6634                 switch (new_cfg->etscfg.tsatable[i]) {
6635                 case I40E_IEEE_TSA_ETS:
6636                         prio_type[i] = I40E_DCB_PRIO_TYPE_ETS;
6637                         ets_data.tc_bw_share_credits[i] =
6638                                         new_cfg->etscfg.tcbwtable[i];
6639                         break;
6640                 case I40E_IEEE_TSA_STRICT:
6641                         prio_type[i] = I40E_DCB_PRIO_TYPE_STRICT;
6642                         lltc_map |= BIT(i);
6643                         ets_data.tc_bw_share_credits[i] =
6644                                         I40E_DCB_STRICT_PRIO_CREDITS;
6645                         break;
6646                 default:
6647                         /* Invalid TSA type */
6648                         need_reconfig = false;
6649                         goto out;
6650                 }
6651         }
6652
6653         old_cfg = &hw->local_dcbx_config;
6654         /* Check if need reconfiguration */
6655         need_reconfig = i40e_dcb_need_reconfig(pf, old_cfg, new_cfg);
6656
6657         /* If needed, enable/disable frame tagging, disable all VSIs
6658          * and suspend port tx
6659          */
6660         if (need_reconfig) {
6661                 /* Enable DCB tagging only when more than one TC */
6662                 if (new_numtc > 1)
6663                         pf->flags |= I40E_FLAG_DCB_ENABLED;
6664                 else
6665                         pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6666
6667                 set_bit(__I40E_PORT_SUSPENDED, pf->state);
6668                 /* Reconfiguration needed quiesce all VSIs */
6669                 i40e_pf_quiesce_all_vsi(pf);
6670                 ret = i40e_suspend_port_tx(pf);
6671                 if (ret)
6672                         goto err;
6673         }
6674
6675         /* Configure Port ETS Tx Scheduler */
6676         ets_data.tc_valid_bits = tc_map;
6677         ets_data.tc_strict_priority_flags = lltc_map;
6678         ret = i40e_aq_config_switch_comp_ets
6679                 (hw, pf->mac_seid, &ets_data,
6680                  i40e_aqc_opc_modify_switching_comp_ets, NULL);
6681         if (ret) {
6682                 dev_info(&pf->pdev->dev,
6683                          "Modify Port ETS failed, err %s aq_err %s\n",
6684                          i40e_stat_str(&pf->hw, ret),
6685                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6686                 goto out;
6687         }
6688
6689         /* Configure Rx ETS HW */
6690         memset(&mode, I40E_DCB_ARB_MODE_ROUND_ROBIN, sizeof(mode));
6691         i40e_dcb_hw_set_num_tc(hw, new_numtc);
6692         i40e_dcb_hw_rx_fifo_config(hw, I40E_DCB_ARB_MODE_ROUND_ROBIN,
6693                                    I40E_DCB_ARB_MODE_STRICT_PRIORITY,
6694                                    I40E_DCB_DEFAULT_MAX_EXPONENT,
6695                                    lltc_map);
6696         i40e_dcb_hw_rx_cmd_monitor_config(hw, new_numtc, num_ports);
6697         i40e_dcb_hw_rx_ets_bw_config(hw, new_cfg->etscfg.tcbwtable, mode,
6698                                      prio_type);
6699         i40e_dcb_hw_pfc_config(hw, new_cfg->pfc.pfcenable,
6700                                new_cfg->etscfg.prioritytable);
6701         i40e_dcb_hw_rx_up2tc_config(hw, new_cfg->etscfg.prioritytable);
6702
6703         /* Configure Rx Packet Buffers in HW */
6704         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6705                 mfs_tc[i] = pf->vsi[pf->lan_vsi]->netdev->mtu;
6706                 mfs_tc[i] += I40E_PACKET_HDR_PAD;
6707         }
6708
6709         i40e_dcb_hw_calculate_pool_sizes(hw, num_ports,
6710                                          false, new_cfg->pfc.pfcenable,
6711                                          mfs_tc, &pb_cfg);
6712         i40e_dcb_hw_rx_pb_config(hw, &pf->pb_cfg, &pb_cfg);
6713
6714         /* Update the local Rx Packet buffer config */
6715         pf->pb_cfg = pb_cfg;
6716
6717         /* Inform the FW about changes to DCB configuration */
6718         ret = i40e_aq_dcb_updated(&pf->hw, NULL);
6719         if (ret) {
6720                 dev_info(&pf->pdev->dev,
6721                          "DCB Updated failed, err %s aq_err %s\n",
6722                          i40e_stat_str(&pf->hw, ret),
6723                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6724                 goto out;
6725         }
6726
6727         /* Update the port DCBx configuration */
6728         *old_cfg = *new_cfg;
6729
6730         /* Changes in configuration update VEB/VSI */
6731         i40e_dcb_reconfigure(pf);
6732 out:
6733         /* Re-start the VSIs if disabled */
6734         if (need_reconfig) {
6735                 ret = i40e_resume_port_tx(pf);
6736
6737                 clear_bit(__I40E_PORT_SUSPENDED, pf->state);
6738                 /* In case of error no point in resuming VSIs */
6739                 if (ret)
6740                         goto err;
6741
6742                 /* Wait for the PF's queues to be disabled */
6743                 ret = i40e_pf_wait_queues_disabled(pf);
6744                 if (ret) {
6745                         /* Schedule PF reset to recover */
6746                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6747                         i40e_service_event_schedule(pf);
6748                         goto err;
6749                 } else {
6750                         i40e_pf_unquiesce_all_vsi(pf);
6751                         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
6752                         set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
6753                 }
6754                 /* registers are set, lets apply */
6755                 if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB)
6756                         ret = i40e_hw_set_dcb_config(pf, new_cfg);
6757         }
6758
6759 err:
6760         return ret;
6761 }
6762
6763 /**
6764  * i40e_dcb_sw_default_config - Set default DCB configuration when DCB in SW
6765  * @pf: PF being queried
6766  *
6767  * Set default DCB configuration in case DCB is to be done in SW.
6768  **/
6769 int i40e_dcb_sw_default_config(struct i40e_pf *pf)
6770 {
6771         struct i40e_dcbx_config *dcb_cfg = &pf->hw.local_dcbx_config;
6772         struct i40e_aqc_configure_switching_comp_ets_data ets_data;
6773         struct i40e_hw *hw = &pf->hw;
6774         int err;
6775
6776         if (pf->hw_features & I40E_HW_USE_SET_LLDP_MIB) {
6777                 /* Update the local cached instance with TC0 ETS */
6778                 memset(&pf->tmp_cfg, 0, sizeof(struct i40e_dcbx_config));
6779                 pf->tmp_cfg.etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
6780                 pf->tmp_cfg.etscfg.maxtcs = 0;
6781                 pf->tmp_cfg.etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
6782                 pf->tmp_cfg.etscfg.tsatable[0] = I40E_IEEE_TSA_ETS;
6783                 pf->tmp_cfg.pfc.willing = I40E_IEEE_DEFAULT_PFC_WILLING;
6784                 pf->tmp_cfg.pfc.pfccap = I40E_MAX_TRAFFIC_CLASS;
6785                 /* FW needs one App to configure HW */
6786                 pf->tmp_cfg.numapps = I40E_IEEE_DEFAULT_NUM_APPS;
6787                 pf->tmp_cfg.app[0].selector = I40E_APP_SEL_ETHTYPE;
6788                 pf->tmp_cfg.app[0].priority = I40E_IEEE_DEFAULT_APP_PRIO;
6789                 pf->tmp_cfg.app[0].protocolid = I40E_APP_PROTOID_FCOE;
6790
6791                 return i40e_hw_set_dcb_config(pf, &pf->tmp_cfg);
6792         }
6793
6794         memset(&ets_data, 0, sizeof(ets_data));
6795         ets_data.tc_valid_bits = I40E_DEFAULT_TRAFFIC_CLASS; /* TC0 only */
6796         ets_data.tc_strict_priority_flags = 0; /* ETS */
6797         ets_data.tc_bw_share_credits[0] = I40E_IEEE_DEFAULT_ETS_TCBW; /* 100% to TC0 */
6798
6799         /* Enable ETS on the Physical port */
6800         err = i40e_aq_config_switch_comp_ets
6801                 (hw, pf->mac_seid, &ets_data,
6802                  i40e_aqc_opc_enable_switching_comp_ets, NULL);
6803         if (err) {
6804                 dev_info(&pf->pdev->dev,
6805                          "Enable Port ETS failed, err %s aq_err %s\n",
6806                          i40e_stat_str(&pf->hw, err),
6807                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6808                 err = -ENOENT;
6809                 goto out;
6810         }
6811
6812         /* Update the local cached instance with TC0 ETS */
6813         dcb_cfg->etscfg.willing = I40E_IEEE_DEFAULT_ETS_WILLING;
6814         dcb_cfg->etscfg.cbs = 0;
6815         dcb_cfg->etscfg.maxtcs = I40E_MAX_TRAFFIC_CLASS;
6816         dcb_cfg->etscfg.tcbwtable[0] = I40E_IEEE_DEFAULT_ETS_TCBW;
6817
6818 out:
6819         return err;
6820 }
6821
6822 /**
6823  * i40e_init_pf_dcb - Initialize DCB configuration
6824  * @pf: PF being configured
6825  *
6826  * Query the current DCB configuration and cache it
6827  * in the hardware structure
6828  **/
6829 static int i40e_init_pf_dcb(struct i40e_pf *pf)
6830 {
6831         struct i40e_hw *hw = &pf->hw;
6832         int err;
6833
6834         /* Do not enable DCB for SW1 and SW2 images even if the FW is capable
6835          * Also do not enable DCBx if FW LLDP agent is disabled
6836          */
6837         if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT) {
6838                 dev_info(&pf->pdev->dev, "DCB is not supported.\n");
6839                 err = I40E_NOT_SUPPORTED;
6840                 goto out;
6841         }
6842         if (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) {
6843                 dev_info(&pf->pdev->dev, "FW LLDP is disabled, attempting SW DCB\n");
6844                 err = i40e_dcb_sw_default_config(pf);
6845                 if (err) {
6846                         dev_info(&pf->pdev->dev, "Could not initialize SW DCB\n");
6847                         goto out;
6848                 }
6849                 dev_info(&pf->pdev->dev, "SW DCB initialization succeeded.\n");
6850                 pf->dcbx_cap = DCB_CAP_DCBX_HOST |
6851                                DCB_CAP_DCBX_VER_IEEE;
6852                 /* at init capable but disabled */
6853                 pf->flags |= I40E_FLAG_DCB_CAPABLE;
6854                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6855                 goto out;
6856         }
6857         err = i40e_init_dcb(hw, true);
6858         if (!err) {
6859                 /* Device/Function is not DCBX capable */
6860                 if ((!hw->func_caps.dcb) ||
6861                     (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
6862                         dev_info(&pf->pdev->dev,
6863                                  "DCBX offload is not supported or is disabled for this PF.\n");
6864                 } else {
6865                         /* When status is not DISABLED then DCBX in FW */
6866                         pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
6867                                        DCB_CAP_DCBX_VER_IEEE;
6868
6869                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
6870                         /* Enable DCB tagging only when more than one TC
6871                          * or explicitly disable if only one TC
6872                          */
6873                         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
6874                                 pf->flags |= I40E_FLAG_DCB_ENABLED;
6875                         else
6876                                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6877                         dev_dbg(&pf->pdev->dev,
6878                                 "DCBX offload is supported for this PF.\n");
6879                 }
6880         } else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
6881                 dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
6882                 pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
6883         } else {
6884                 dev_info(&pf->pdev->dev,
6885                          "Query for DCB configuration failed, err %s aq_err %s\n",
6886                          i40e_stat_str(&pf->hw, err),
6887                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6888         }
6889
6890 out:
6891         return err;
6892 }
6893 #endif /* CONFIG_I40E_DCB */
6894
6895 /**
6896  * i40e_print_link_message - print link up or down
6897  * @vsi: the VSI for which link needs a message
6898  * @isup: true of link is up, false otherwise
6899  */
6900 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
6901 {
6902         enum i40e_aq_link_speed new_speed;
6903         struct i40e_pf *pf = vsi->back;
6904         char *speed = "Unknown";
6905         char *fc = "Unknown";
6906         char *fec = "";
6907         char *req_fec = "";
6908         char *an = "";
6909
6910         if (isup)
6911                 new_speed = pf->hw.phy.link_info.link_speed;
6912         else
6913                 new_speed = I40E_LINK_SPEED_UNKNOWN;
6914
6915         if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
6916                 return;
6917         vsi->current_isup = isup;
6918         vsi->current_speed = new_speed;
6919         if (!isup) {
6920                 netdev_info(vsi->netdev, "NIC Link is Down\n");
6921                 return;
6922         }
6923
6924         /* Warn user if link speed on NPAR enabled partition is not at
6925          * least 10GB
6926          */
6927         if (pf->hw.func_caps.npar_enable &&
6928             (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
6929              pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
6930                 netdev_warn(vsi->netdev,
6931                             "The partition detected link speed that is less than 10Gbps\n");
6932
6933         switch (pf->hw.phy.link_info.link_speed) {
6934         case I40E_LINK_SPEED_40GB:
6935                 speed = "40 G";
6936                 break;
6937         case I40E_LINK_SPEED_20GB:
6938                 speed = "20 G";
6939                 break;
6940         case I40E_LINK_SPEED_25GB:
6941                 speed = "25 G";
6942                 break;
6943         case I40E_LINK_SPEED_10GB:
6944                 speed = "10 G";
6945                 break;
6946         case I40E_LINK_SPEED_5GB:
6947                 speed = "5 G";
6948                 break;
6949         case I40E_LINK_SPEED_2_5GB:
6950                 speed = "2.5 G";
6951                 break;
6952         case I40E_LINK_SPEED_1GB:
6953                 speed = "1000 M";
6954                 break;
6955         case I40E_LINK_SPEED_100MB:
6956                 speed = "100 M";
6957                 break;
6958         default:
6959                 break;
6960         }
6961
6962         switch (pf->hw.fc.current_mode) {
6963         case I40E_FC_FULL:
6964                 fc = "RX/TX";
6965                 break;
6966         case I40E_FC_TX_PAUSE:
6967                 fc = "TX";
6968                 break;
6969         case I40E_FC_RX_PAUSE:
6970                 fc = "RX";
6971                 break;
6972         default:
6973                 fc = "None";
6974                 break;
6975         }
6976
6977         if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
6978                 req_fec = "None";
6979                 fec = "None";
6980                 an = "False";
6981
6982                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
6983                         an = "True";
6984
6985                 if (pf->hw.phy.link_info.fec_info &
6986                     I40E_AQ_CONFIG_FEC_KR_ENA)
6987                         fec = "CL74 FC-FEC/BASE-R";
6988                 else if (pf->hw.phy.link_info.fec_info &
6989                          I40E_AQ_CONFIG_FEC_RS_ENA)
6990                         fec = "CL108 RS-FEC";
6991
6992                 /* 'CL108 RS-FEC' should be displayed when RS is requested, or
6993                  * both RS and FC are requested
6994                  */
6995                 if (vsi->back->hw.phy.link_info.req_fec_info &
6996                     (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
6997                         if (vsi->back->hw.phy.link_info.req_fec_info &
6998                             I40E_AQ_REQUEST_FEC_RS)
6999                                 req_fec = "CL108 RS-FEC";
7000                         else
7001                                 req_fec = "CL74 FC-FEC/BASE-R";
7002                 }
7003                 netdev_info(vsi->netdev,
7004                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7005                             speed, req_fec, fec, an, fc);
7006         } else if (pf->hw.device_id == I40E_DEV_ID_KX_X722) {
7007                 req_fec = "None";
7008                 fec = "None";
7009                 an = "False";
7010
7011                 if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
7012                         an = "True";
7013
7014                 if (pf->hw.phy.link_info.fec_info &
7015                     I40E_AQ_CONFIG_FEC_KR_ENA)
7016                         fec = "CL74 FC-FEC/BASE-R";
7017
7018                 if (pf->hw.phy.link_info.req_fec_info &
7019                     I40E_AQ_REQUEST_FEC_KR)
7020                         req_fec = "CL74 FC-FEC/BASE-R";
7021
7022                 netdev_info(vsi->netdev,
7023                             "NIC Link is Up, %sbps Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
7024                             speed, req_fec, fec, an, fc);
7025         } else {
7026                 netdev_info(vsi->netdev,
7027                             "NIC Link is Up, %sbps Full Duplex, Flow Control: %s\n",
7028                             speed, fc);
7029         }
7030
7031 }
7032
7033 /**
7034  * i40e_up_complete - Finish the last steps of bringing up a connection
7035  * @vsi: the VSI being configured
7036  **/
7037 static int i40e_up_complete(struct i40e_vsi *vsi)
7038 {
7039         struct i40e_pf *pf = vsi->back;
7040         int err;
7041
7042         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7043                 i40e_vsi_configure_msix(vsi);
7044         else
7045                 i40e_configure_msi_and_legacy(vsi);
7046
7047         /* start rings */
7048         err = i40e_vsi_start_rings(vsi);
7049         if (err)
7050                 return err;
7051
7052         clear_bit(__I40E_VSI_DOWN, vsi->state);
7053         i40e_napi_enable_all(vsi);
7054         i40e_vsi_enable_irq(vsi);
7055
7056         if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
7057             (vsi->netdev)) {
7058                 i40e_print_link_message(vsi, true);
7059                 netif_tx_start_all_queues(vsi->netdev);
7060                 netif_carrier_on(vsi->netdev);
7061         }
7062
7063         /* replay FDIR SB filters */
7064         if (vsi->type == I40E_VSI_FDIR) {
7065                 /* reset fd counters */
7066                 pf->fd_add_err = 0;
7067                 pf->fd_atr_cnt = 0;
7068                 i40e_fdir_filter_restore(vsi);
7069         }
7070
7071         /* On the next run of the service_task, notify any clients of the new
7072          * opened netdev
7073          */
7074         set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
7075         i40e_service_event_schedule(pf);
7076
7077         return 0;
7078 }
7079
7080 /**
7081  * i40e_vsi_reinit_locked - Reset the VSI
7082  * @vsi: the VSI being configured
7083  *
7084  * Rebuild the ring structs after some configuration
7085  * has changed, e.g. MTU size.
7086  **/
7087 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
7088 {
7089         struct i40e_pf *pf = vsi->back;
7090
7091         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
7092                 usleep_range(1000, 2000);
7093         i40e_down(vsi);
7094
7095         i40e_up(vsi);
7096         clear_bit(__I40E_CONFIG_BUSY, pf->state);
7097 }
7098
7099 /**
7100  * i40e_force_link_state - Force the link status
7101  * @pf: board private structure
7102  * @is_up: whether the link state should be forced up or down
7103  **/
7104 static i40e_status i40e_force_link_state(struct i40e_pf *pf, bool is_up)
7105 {
7106         struct i40e_aq_get_phy_abilities_resp abilities;
7107         struct i40e_aq_set_phy_config config = {0};
7108         bool non_zero_phy_type = is_up;
7109         struct i40e_hw *hw = &pf->hw;
7110         i40e_status err;
7111         u64 mask;
7112         u8 speed;
7113
7114         /* Card might've been put in an unstable state by other drivers
7115          * and applications, which causes incorrect speed values being
7116          * set on startup. In order to clear speed registers, we call
7117          * get_phy_capabilities twice, once to get initial state of
7118          * available speeds, and once to get current PHY config.
7119          */
7120         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
7121                                            NULL);
7122         if (err) {
7123                 dev_err(&pf->pdev->dev,
7124                         "failed to get phy cap., ret =  %s last_status =  %s\n",
7125                         i40e_stat_str(hw, err),
7126                         i40e_aq_str(hw, hw->aq.asq_last_status));
7127                 return err;
7128         }
7129         speed = abilities.link_speed;
7130
7131         /* Get the current phy config */
7132         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
7133                                            NULL);
7134         if (err) {
7135                 dev_err(&pf->pdev->dev,
7136                         "failed to get phy cap., ret =  %s last_status =  %s\n",
7137                         i40e_stat_str(hw, err),
7138                         i40e_aq_str(hw, hw->aq.asq_last_status));
7139                 return err;
7140         }
7141
7142         /* If link needs to go up, but was not forced to go down,
7143          * and its speed values are OK, no need for a flap
7144          * if non_zero_phy_type was set, still need to force up
7145          */
7146         if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED)
7147                 non_zero_phy_type = true;
7148         else if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
7149                 return I40E_SUCCESS;
7150
7151         /* To force link we need to set bits for all supported PHY types,
7152          * but there are now more than 32, so we need to split the bitmap
7153          * across two fields.
7154          */
7155         mask = I40E_PHY_TYPES_BITMASK;
7156         config.phy_type =
7157                 non_zero_phy_type ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
7158         config.phy_type_ext =
7159                 non_zero_phy_type ? (u8)((mask >> 32) & 0xff) : 0;
7160         /* Copy the old settings, except of phy_type */
7161         config.abilities = abilities.abilities;
7162         if (pf->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED) {
7163                 if (is_up)
7164                         config.abilities |= I40E_AQ_PHY_ENABLE_LINK;
7165                 else
7166                         config.abilities &= ~(I40E_AQ_PHY_ENABLE_LINK);
7167         }
7168         if (abilities.link_speed != 0)
7169                 config.link_speed = abilities.link_speed;
7170         else
7171                 config.link_speed = speed;
7172         config.eee_capability = abilities.eee_capability;
7173         config.eeer = abilities.eeer_val;
7174         config.low_power_ctrl = abilities.d3_lpan;
7175         config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
7176                             I40E_AQ_PHY_FEC_CONFIG_MASK;
7177         err = i40e_aq_set_phy_config(hw, &config, NULL);
7178
7179         if (err) {
7180                 dev_err(&pf->pdev->dev,
7181                         "set phy config ret =  %s last_status =  %s\n",
7182                         i40e_stat_str(&pf->hw, err),
7183                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7184                 return err;
7185         }
7186
7187         /* Update the link info */
7188         err = i40e_update_link_info(hw);
7189         if (err) {
7190                 /* Wait a little bit (on 40G cards it sometimes takes a really
7191                  * long time for link to come back from the atomic reset)
7192                  * and try once more
7193                  */
7194                 msleep(1000);
7195                 i40e_update_link_info(hw);
7196         }
7197
7198         i40e_aq_set_link_restart_an(hw, is_up, NULL);
7199
7200         return I40E_SUCCESS;
7201 }
7202
7203 /**
7204  * i40e_up - Bring the connection back up after being down
7205  * @vsi: the VSI being configured
7206  **/
7207 int i40e_up(struct i40e_vsi *vsi)
7208 {
7209         int err;
7210
7211         if (vsi->type == I40E_VSI_MAIN &&
7212             (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7213              vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7214                 i40e_force_link_state(vsi->back, true);
7215
7216         err = i40e_vsi_configure(vsi);
7217         if (!err)
7218                 err = i40e_up_complete(vsi);
7219
7220         return err;
7221 }
7222
7223 /**
7224  * i40e_down - Shutdown the connection processing
7225  * @vsi: the VSI being stopped
7226  **/
7227 void i40e_down(struct i40e_vsi *vsi)
7228 {
7229         int i;
7230
7231         /* It is assumed that the caller of this function
7232          * sets the vsi->state __I40E_VSI_DOWN bit.
7233          */
7234         if (vsi->netdev) {
7235                 netif_carrier_off(vsi->netdev);
7236                 netif_tx_disable(vsi->netdev);
7237         }
7238         i40e_vsi_disable_irq(vsi);
7239         i40e_vsi_stop_rings(vsi);
7240         if (vsi->type == I40E_VSI_MAIN &&
7241            (vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED ||
7242             vsi->back->flags & I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED))
7243                 i40e_force_link_state(vsi->back, false);
7244         i40e_napi_disable_all(vsi);
7245
7246         for (i = 0; i < vsi->num_queue_pairs; i++) {
7247                 i40e_clean_tx_ring(vsi->tx_rings[i]);
7248                 if (i40e_enabled_xdp_vsi(vsi)) {
7249                         /* Make sure that in-progress ndo_xdp_xmit and
7250                          * ndo_xsk_wakeup calls are completed.
7251                          */
7252                         synchronize_rcu();
7253                         i40e_clean_tx_ring(vsi->xdp_rings[i]);
7254                 }
7255                 i40e_clean_rx_ring(vsi->rx_rings[i]);
7256         }
7257
7258 }
7259
7260 /**
7261  * i40e_validate_mqprio_qopt- validate queue mapping info
7262  * @vsi: the VSI being configured
7263  * @mqprio_qopt: queue parametrs
7264  **/
7265 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
7266                                      struct tc_mqprio_qopt_offload *mqprio_qopt)
7267 {
7268         u64 sum_max_rate = 0;
7269         u64 max_rate = 0;
7270         int i;
7271
7272         if (mqprio_qopt->qopt.offset[0] != 0 ||
7273             mqprio_qopt->qopt.num_tc < 1 ||
7274             mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
7275                 return -EINVAL;
7276         for (i = 0; ; i++) {
7277                 if (!mqprio_qopt->qopt.count[i])
7278                         return -EINVAL;
7279                 if (mqprio_qopt->min_rate[i]) {
7280                         dev_err(&vsi->back->pdev->dev,
7281                                 "Invalid min tx rate (greater than 0) specified\n");
7282                         return -EINVAL;
7283                 }
7284                 max_rate = mqprio_qopt->max_rate[i];
7285                 do_div(max_rate, I40E_BW_MBPS_DIVISOR);
7286                 sum_max_rate += max_rate;
7287
7288                 if (i >= mqprio_qopt->qopt.num_tc - 1)
7289                         break;
7290                 if (mqprio_qopt->qopt.offset[i + 1] !=
7291                     (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
7292                         return -EINVAL;
7293         }
7294         if (vsi->num_queue_pairs <
7295             (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
7296                 dev_err(&vsi->back->pdev->dev,
7297                         "Failed to create traffic channel, insufficient number of queues.\n");
7298                 return -EINVAL;
7299         }
7300         if (sum_max_rate > i40e_get_link_speed(vsi)) {
7301                 dev_err(&vsi->back->pdev->dev,
7302                         "Invalid max tx rate specified\n");
7303                 return -EINVAL;
7304         }
7305         return 0;
7306 }
7307
7308 /**
7309  * i40e_vsi_set_default_tc_config - set default values for tc configuration
7310  * @vsi: the VSI being configured
7311  **/
7312 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
7313 {
7314         u16 qcount;
7315         int i;
7316
7317         /* Only TC0 is enabled */
7318         vsi->tc_config.numtc = 1;
7319         vsi->tc_config.enabled_tc = 1;
7320         qcount = min_t(int, vsi->alloc_queue_pairs,
7321                        i40e_pf_get_max_q_per_tc(vsi->back));
7322         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
7323                 /* For the TC that is not enabled set the offset to default
7324                  * queue and allocate one queue for the given TC.
7325                  */
7326                 vsi->tc_config.tc_info[i].qoffset = 0;
7327                 if (i == 0)
7328                         vsi->tc_config.tc_info[i].qcount = qcount;
7329                 else
7330                         vsi->tc_config.tc_info[i].qcount = 1;
7331                 vsi->tc_config.tc_info[i].netdev_tc = 0;
7332         }
7333 }
7334
7335 /**
7336  * i40e_del_macvlan_filter
7337  * @hw: pointer to the HW structure
7338  * @seid: seid of the channel VSI
7339  * @macaddr: the mac address to apply as a filter
7340  * @aq_err: store the admin Q error
7341  *
7342  * This function deletes a mac filter on the channel VSI which serves as the
7343  * macvlan. Returns 0 on success.
7344  **/
7345 static i40e_status i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
7346                                            const u8 *macaddr, int *aq_err)
7347 {
7348         struct i40e_aqc_remove_macvlan_element_data element;
7349         i40e_status status;
7350
7351         memset(&element, 0, sizeof(element));
7352         ether_addr_copy(element.mac_addr, macaddr);
7353         element.vlan_tag = 0;
7354         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
7355         status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
7356         *aq_err = hw->aq.asq_last_status;
7357
7358         return status;
7359 }
7360
7361 /**
7362  * i40e_add_macvlan_filter
7363  * @hw: pointer to the HW structure
7364  * @seid: seid of the channel VSI
7365  * @macaddr: the mac address to apply as a filter
7366  * @aq_err: store the admin Q error
7367  *
7368  * This function adds a mac filter on the channel VSI which serves as the
7369  * macvlan. Returns 0 on success.
7370  **/
7371 static i40e_status i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
7372                                            const u8 *macaddr, int *aq_err)
7373 {
7374         struct i40e_aqc_add_macvlan_element_data element;
7375         i40e_status status;
7376         u16 cmd_flags = 0;
7377
7378         ether_addr_copy(element.mac_addr, macaddr);
7379         element.vlan_tag = 0;
7380         element.queue_number = 0;
7381         element.match_method = I40E_AQC_MM_ERR_NO_RES;
7382         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
7383         element.flags = cpu_to_le16(cmd_flags);
7384         status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
7385         *aq_err = hw->aq.asq_last_status;
7386
7387         return status;
7388 }
7389
7390 /**
7391  * i40e_reset_ch_rings - Reset the queue contexts in a channel
7392  * @vsi: the VSI we want to access
7393  * @ch: the channel we want to access
7394  */
7395 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
7396 {
7397         struct i40e_ring *tx_ring, *rx_ring;
7398         u16 pf_q;
7399         int i;
7400
7401         for (i = 0; i < ch->num_queue_pairs; i++) {
7402                 pf_q = ch->base_queue + i;
7403                 tx_ring = vsi->tx_rings[pf_q];
7404                 tx_ring->ch = NULL;
7405                 rx_ring = vsi->rx_rings[pf_q];
7406                 rx_ring->ch = NULL;
7407         }
7408 }
7409
7410 /**
7411  * i40e_free_macvlan_channels
7412  * @vsi: the VSI we want to access
7413  *
7414  * This function frees the Qs of the channel VSI from
7415  * the stack and also deletes the channel VSIs which
7416  * serve as macvlans.
7417  */
7418 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
7419 {
7420         struct i40e_channel *ch, *ch_tmp;
7421         int ret;
7422
7423         if (list_empty(&vsi->macvlan_list))
7424                 return;
7425
7426         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7427                 struct i40e_vsi *parent_vsi;
7428
7429                 if (i40e_is_channel_macvlan(ch)) {
7430                         i40e_reset_ch_rings(vsi, ch);
7431                         clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7432                         netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
7433                         netdev_set_sb_channel(ch->fwd->netdev, 0);
7434                         kfree(ch->fwd);
7435                         ch->fwd = NULL;
7436                 }
7437
7438                 list_del(&ch->list);
7439                 parent_vsi = ch->parent_vsi;
7440                 if (!parent_vsi || !ch->initialized) {
7441                         kfree(ch);
7442                         continue;
7443                 }
7444
7445                 /* remove the VSI */
7446                 ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
7447                                              NULL);
7448                 if (ret)
7449                         dev_err(&vsi->back->pdev->dev,
7450                                 "unable to remove channel (%d) for parent VSI(%d)\n",
7451                                 ch->seid, parent_vsi->seid);
7452                 kfree(ch);
7453         }
7454         vsi->macvlan_cnt = 0;
7455 }
7456
7457 /**
7458  * i40e_fwd_ring_up - bring the macvlan device up
7459  * @vsi: the VSI we want to access
7460  * @vdev: macvlan netdevice
7461  * @fwd: the private fwd structure
7462  */
7463 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7464                             struct i40e_fwd_adapter *fwd)
7465 {
7466         int ret = 0, num_tc = 1,  i, aq_err;
7467         struct i40e_channel *ch, *ch_tmp;
7468         struct i40e_pf *pf = vsi->back;
7469         struct i40e_hw *hw = &pf->hw;
7470
7471         if (list_empty(&vsi->macvlan_list))
7472                 return -EINVAL;
7473
7474         /* Go through the list and find an available channel */
7475         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7476                 if (!i40e_is_channel_macvlan(ch)) {
7477                         ch->fwd = fwd;
7478                         /* record configuration for macvlan interface in vdev */
7479                         for (i = 0; i < num_tc; i++)
7480                                 netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7481                                                              i,
7482                                                              ch->num_queue_pairs,
7483                                                              ch->base_queue);
7484                         for (i = 0; i < ch->num_queue_pairs; i++) {
7485                                 struct i40e_ring *tx_ring, *rx_ring;
7486                                 u16 pf_q;
7487
7488                                 pf_q = ch->base_queue + i;
7489
7490                                 /* Get to TX ring ptr */
7491                                 tx_ring = vsi->tx_rings[pf_q];
7492                                 tx_ring->ch = ch;
7493
7494                                 /* Get the RX ring ptr */
7495                                 rx_ring = vsi->rx_rings[pf_q];
7496                                 rx_ring->ch = ch;
7497                         }
7498                         break;
7499                 }
7500         }
7501
7502         /* Guarantee all rings are updated before we update the
7503          * MAC address filter.
7504          */
7505         wmb();
7506
7507         /* Add a mac filter */
7508         ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7509         if (ret) {
7510                 /* if we cannot add the MAC rule then disable the offload */
7511                 macvlan_release_l2fw_offload(vdev);
7512                 for (i = 0; i < ch->num_queue_pairs; i++) {
7513                         struct i40e_ring *rx_ring;
7514                         u16 pf_q;
7515
7516                         pf_q = ch->base_queue + i;
7517                         rx_ring = vsi->rx_rings[pf_q];
7518                         rx_ring->netdev = NULL;
7519                 }
7520                 dev_info(&pf->pdev->dev,
7521                          "Error adding mac filter on macvlan err %s, aq_err %s\n",
7522                           i40e_stat_str(hw, ret),
7523                           i40e_aq_str(hw, aq_err));
7524                 netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7525         }
7526
7527         return ret;
7528 }
7529
7530 /**
7531  * i40e_setup_macvlans - create the channels which will be macvlans
7532  * @vsi: the VSI we want to access
7533  * @macvlan_cnt: no. of macvlans to be setup
7534  * @qcnt: no. of Qs per macvlan
7535  * @vdev: macvlan netdevice
7536  */
7537 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7538                                struct net_device *vdev)
7539 {
7540         struct i40e_pf *pf = vsi->back;
7541         struct i40e_hw *hw = &pf->hw;
7542         struct i40e_vsi_context ctxt;
7543         u16 sections, qmap, num_qps;
7544         struct i40e_channel *ch;
7545         int i, pow, ret = 0;
7546         u8 offset = 0;
7547
7548         if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7549                 return -EINVAL;
7550
7551         num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7552
7553         /* find the next higher power-of-2 of num queue pairs */
7554         pow = fls(roundup_pow_of_two(num_qps) - 1);
7555
7556         qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7557                 (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7558
7559         /* Setup context bits for the main VSI */
7560         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7561         sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7562         memset(&ctxt, 0, sizeof(ctxt));
7563         ctxt.seid = vsi->seid;
7564         ctxt.pf_num = vsi->back->hw.pf_id;
7565         ctxt.vf_num = 0;
7566         ctxt.uplink_seid = vsi->uplink_seid;
7567         ctxt.info = vsi->info;
7568         ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7569         ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7570         ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7571         ctxt.info.valid_sections |= cpu_to_le16(sections);
7572
7573         /* Reconfigure RSS for main VSI with new max queue count */
7574         vsi->rss_size = max_t(u16, num_qps, qcnt);
7575         ret = i40e_vsi_config_rss(vsi);
7576         if (ret) {
7577                 dev_info(&pf->pdev->dev,
7578                          "Failed to reconfig RSS for num_queues (%u)\n",
7579                          vsi->rss_size);
7580                 return ret;
7581         }
7582         vsi->reconfig_rss = true;
7583         dev_dbg(&vsi->back->pdev->dev,
7584                 "Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7585         vsi->next_base_queue = num_qps;
7586         vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7587
7588         /* Update the VSI after updating the VSI queue-mapping
7589          * information
7590          */
7591         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7592         if (ret) {
7593                 dev_info(&pf->pdev->dev,
7594                          "Update vsi tc config failed, err %s aq_err %s\n",
7595                          i40e_stat_str(hw, ret),
7596                          i40e_aq_str(hw, hw->aq.asq_last_status));
7597                 return ret;
7598         }
7599         /* update the local VSI info with updated queue map */
7600         i40e_vsi_update_queue_map(vsi, &ctxt);
7601         vsi->info.valid_sections = 0;
7602
7603         /* Create channels for macvlans */
7604         INIT_LIST_HEAD(&vsi->macvlan_list);
7605         for (i = 0; i < macvlan_cnt; i++) {
7606                 ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7607                 if (!ch) {
7608                         ret = -ENOMEM;
7609                         goto err_free;
7610                 }
7611                 INIT_LIST_HEAD(&ch->list);
7612                 ch->num_queue_pairs = qcnt;
7613                 if (!i40e_setup_channel(pf, vsi, ch)) {
7614                         ret = -EINVAL;
7615                         kfree(ch);
7616                         goto err_free;
7617                 }
7618                 ch->parent_vsi = vsi;
7619                 vsi->cnt_q_avail -= ch->num_queue_pairs;
7620                 vsi->macvlan_cnt++;
7621                 list_add_tail(&ch->list, &vsi->macvlan_list);
7622         }
7623
7624         return ret;
7625
7626 err_free:
7627         dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7628         i40e_free_macvlan_channels(vsi);
7629
7630         return ret;
7631 }
7632
7633 /**
7634  * i40e_fwd_add - configure macvlans
7635  * @netdev: net device to configure
7636  * @vdev: macvlan netdevice
7637  **/
7638 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7639 {
7640         struct i40e_netdev_priv *np = netdev_priv(netdev);
7641         u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7642         struct i40e_vsi *vsi = np->vsi;
7643         struct i40e_pf *pf = vsi->back;
7644         struct i40e_fwd_adapter *fwd;
7645         int avail_macvlan, ret;
7646
7647         if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7648                 netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7649                 return ERR_PTR(-EINVAL);
7650         }
7651         if ((pf->flags & I40E_FLAG_TC_MQPRIO)) {
7652                 netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7653                 return ERR_PTR(-EINVAL);
7654         }
7655         if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7656                 netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7657                 return ERR_PTR(-EINVAL);
7658         }
7659
7660         /* The macvlan device has to be a single Q device so that the
7661          * tc_to_txq field can be reused to pick the tx queue.
7662          */
7663         if (netif_is_multiqueue(vdev))
7664                 return ERR_PTR(-ERANGE);
7665
7666         if (!vsi->macvlan_cnt) {
7667                 /* reserve bit 0 for the pf device */
7668                 set_bit(0, vsi->fwd_bitmask);
7669
7670                 /* Try to reserve as many queues as possible for macvlans. First
7671                  * reserve 3/4th of max vectors, then half, then quarter and
7672                  * calculate Qs per macvlan as you go
7673                  */
7674                 vectors = pf->num_lan_msix;
7675                 if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7676                         /* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7677                         q_per_macvlan = 4;
7678                         macvlan_cnt = (vectors - 32) / 4;
7679                 } else if (vectors <= 64 && vectors > 32) {
7680                         /* allocate 2 Qs per macvlan and 16 Qs to the PF*/
7681                         q_per_macvlan = 2;
7682                         macvlan_cnt = (vectors - 16) / 2;
7683                 } else if (vectors <= 32 && vectors > 16) {
7684                         /* allocate 1 Q per macvlan and 16 Qs to the PF*/
7685                         q_per_macvlan = 1;
7686                         macvlan_cnt = vectors - 16;
7687                 } else if (vectors <= 16 && vectors > 8) {
7688                         /* allocate 1 Q per macvlan and 8 Qs to the PF */
7689                         q_per_macvlan = 1;
7690                         macvlan_cnt = vectors - 8;
7691                 } else {
7692                         /* allocate 1 Q per macvlan and 1 Q to the PF */
7693                         q_per_macvlan = 1;
7694                         macvlan_cnt = vectors - 1;
7695                 }
7696
7697                 if (macvlan_cnt == 0)
7698                         return ERR_PTR(-EBUSY);
7699
7700                 /* Quiesce VSI queues */
7701                 i40e_quiesce_vsi(vsi);
7702
7703                 /* sets up the macvlans but does not "enable" them */
7704                 ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
7705                                           vdev);
7706                 if (ret)
7707                         return ERR_PTR(ret);
7708
7709                 /* Unquiesce VSI */
7710                 i40e_unquiesce_vsi(vsi);
7711         }
7712         avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
7713                                             vsi->macvlan_cnt);
7714         if (avail_macvlan >= I40E_MAX_MACVLANS)
7715                 return ERR_PTR(-EBUSY);
7716
7717         /* create the fwd struct */
7718         fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
7719         if (!fwd)
7720                 return ERR_PTR(-ENOMEM);
7721
7722         set_bit(avail_macvlan, vsi->fwd_bitmask);
7723         fwd->bit_no = avail_macvlan;
7724         netdev_set_sb_channel(vdev, avail_macvlan);
7725         fwd->netdev = vdev;
7726
7727         if (!netif_running(netdev))
7728                 return fwd;
7729
7730         /* Set fwd ring up */
7731         ret = i40e_fwd_ring_up(vsi, vdev, fwd);
7732         if (ret) {
7733                 /* unbind the queues and drop the subordinate channel config */
7734                 netdev_unbind_sb_channel(netdev, vdev);
7735                 netdev_set_sb_channel(vdev, 0);
7736
7737                 kfree(fwd);
7738                 return ERR_PTR(-EINVAL);
7739         }
7740
7741         return fwd;
7742 }
7743
7744 /**
7745  * i40e_del_all_macvlans - Delete all the mac filters on the channels
7746  * @vsi: the VSI we want to access
7747  */
7748 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
7749 {
7750         struct i40e_channel *ch, *ch_tmp;
7751         struct i40e_pf *pf = vsi->back;
7752         struct i40e_hw *hw = &pf->hw;
7753         int aq_err, ret = 0;
7754
7755         if (list_empty(&vsi->macvlan_list))
7756                 return;
7757
7758         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7759                 if (i40e_is_channel_macvlan(ch)) {
7760                         ret = i40e_del_macvlan_filter(hw, ch->seid,
7761                                                       i40e_channel_mac(ch),
7762                                                       &aq_err);
7763                         if (!ret) {
7764                                 /* Reset queue contexts */
7765                                 i40e_reset_ch_rings(vsi, ch);
7766                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7767                                 netdev_unbind_sb_channel(vsi->netdev,
7768                                                          ch->fwd->netdev);
7769                                 netdev_set_sb_channel(ch->fwd->netdev, 0);
7770                                 kfree(ch->fwd);
7771                                 ch->fwd = NULL;
7772                         }
7773                 }
7774         }
7775 }
7776
7777 /**
7778  * i40e_fwd_del - delete macvlan interfaces
7779  * @netdev: net device to configure
7780  * @vdev: macvlan netdevice
7781  */
7782 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
7783 {
7784         struct i40e_netdev_priv *np = netdev_priv(netdev);
7785         struct i40e_fwd_adapter *fwd = vdev;
7786         struct i40e_channel *ch, *ch_tmp;
7787         struct i40e_vsi *vsi = np->vsi;
7788         struct i40e_pf *pf = vsi->back;
7789         struct i40e_hw *hw = &pf->hw;
7790         int aq_err, ret = 0;
7791
7792         /* Find the channel associated with the macvlan and del mac filter */
7793         list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7794                 if (i40e_is_channel_macvlan(ch) &&
7795                     ether_addr_equal(i40e_channel_mac(ch),
7796                                      fwd->netdev->dev_addr)) {
7797                         ret = i40e_del_macvlan_filter(hw, ch->seid,
7798                                                       i40e_channel_mac(ch),
7799                                                       &aq_err);
7800                         if (!ret) {
7801                                 /* Reset queue contexts */
7802                                 i40e_reset_ch_rings(vsi, ch);
7803                                 clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7804                                 netdev_unbind_sb_channel(netdev, fwd->netdev);
7805                                 netdev_set_sb_channel(fwd->netdev, 0);
7806                                 kfree(ch->fwd);
7807                                 ch->fwd = NULL;
7808                         } else {
7809                                 dev_info(&pf->pdev->dev,
7810                                          "Error deleting mac filter on macvlan err %s, aq_err %s\n",
7811                                           i40e_stat_str(hw, ret),
7812                                           i40e_aq_str(hw, aq_err));
7813                         }
7814                         break;
7815                 }
7816         }
7817 }
7818
7819 /**
7820  * i40e_setup_tc - configure multiple traffic classes
7821  * @netdev: net device to configure
7822  * @type_data: tc offload data
7823  **/
7824 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
7825 {
7826         struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
7827         struct i40e_netdev_priv *np = netdev_priv(netdev);
7828         struct i40e_vsi *vsi = np->vsi;
7829         struct i40e_pf *pf = vsi->back;
7830         u8 enabled_tc = 0, num_tc, hw;
7831         bool need_reset = false;
7832         int old_queue_pairs;
7833         int ret = -EINVAL;
7834         u16 mode;
7835         int i;
7836
7837         old_queue_pairs = vsi->num_queue_pairs;
7838         num_tc = mqprio_qopt->qopt.num_tc;
7839         hw = mqprio_qopt->qopt.hw;
7840         mode = mqprio_qopt->mode;
7841         if (!hw) {
7842                 pf->flags &= ~I40E_FLAG_TC_MQPRIO;
7843                 memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
7844                 goto config_tc;
7845         }
7846
7847         /* Check if MFP enabled */
7848         if (pf->flags & I40E_FLAG_MFP_ENABLED) {
7849                 netdev_info(netdev,
7850                             "Configuring TC not supported in MFP mode\n");
7851                 return ret;
7852         }
7853         switch (mode) {
7854         case TC_MQPRIO_MODE_DCB:
7855                 pf->flags &= ~I40E_FLAG_TC_MQPRIO;
7856
7857                 /* Check if DCB enabled to continue */
7858                 if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
7859                         netdev_info(netdev,
7860                                     "DCB is not enabled for adapter\n");
7861                         return ret;
7862                 }
7863
7864                 /* Check whether tc count is within enabled limit */
7865                 if (num_tc > i40e_pf_get_num_tc(pf)) {
7866                         netdev_info(netdev,
7867                                     "TC count greater than enabled on link for adapter\n");
7868                         return ret;
7869                 }
7870                 break;
7871         case TC_MQPRIO_MODE_CHANNEL:
7872                 if (pf->flags & I40E_FLAG_DCB_ENABLED) {
7873                         netdev_info(netdev,
7874                                     "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
7875                         return ret;
7876                 }
7877                 if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
7878                         return ret;
7879                 ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
7880                 if (ret)
7881                         return ret;
7882                 memcpy(&vsi->mqprio_qopt, mqprio_qopt,
7883                        sizeof(*mqprio_qopt));
7884                 pf->flags |= I40E_FLAG_TC_MQPRIO;
7885                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7886                 break;
7887         default:
7888                 return -EINVAL;
7889         }
7890
7891 config_tc:
7892         /* Generate TC map for number of tc requested */
7893         for (i = 0; i < num_tc; i++)
7894                 enabled_tc |= BIT(i);
7895
7896         /* Requesting same TC configuration as already enabled */
7897         if (enabled_tc == vsi->tc_config.enabled_tc &&
7898             mode != TC_MQPRIO_MODE_CHANNEL)
7899                 return 0;
7900
7901         /* Quiesce VSI queues */
7902         i40e_quiesce_vsi(vsi);
7903
7904         if (!hw && !(pf->flags & I40E_FLAG_TC_MQPRIO))
7905                 i40e_remove_queue_channels(vsi);
7906
7907         /* Configure VSI for enabled TCs */
7908         ret = i40e_vsi_config_tc(vsi, enabled_tc);
7909         if (ret) {
7910                 netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
7911                             vsi->seid);
7912                 need_reset = true;
7913                 goto exit;
7914         } else {
7915                 dev_info(&vsi->back->pdev->dev,
7916                          "Setup channel (id:%u) utilizing num_queues %d\n",
7917                          vsi->seid, vsi->tc_config.tc_info[0].qcount);
7918         }
7919
7920         if (pf->flags & I40E_FLAG_TC_MQPRIO) {
7921                 if (vsi->mqprio_qopt.max_rate[0]) {
7922                         u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
7923
7924                         do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
7925                         ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
7926                         if (!ret) {
7927                                 u64 credits = max_tx_rate;
7928
7929                                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
7930                                 dev_dbg(&vsi->back->pdev->dev,
7931                                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
7932                                         max_tx_rate,
7933                                         credits,
7934                                         vsi->seid);
7935                         } else {
7936                                 need_reset = true;
7937                                 goto exit;
7938                         }
7939                 }
7940                 ret = i40e_configure_queue_channels(vsi);
7941                 if (ret) {
7942                         vsi->num_queue_pairs = old_queue_pairs;
7943                         netdev_info(netdev,
7944                                     "Failed configuring queue channels\n");
7945                         need_reset = true;
7946                         goto exit;
7947                 }
7948         }
7949
7950 exit:
7951         /* Reset the configuration data to defaults, only TC0 is enabled */
7952         if (need_reset) {
7953                 i40e_vsi_set_default_tc_config(vsi);
7954                 need_reset = false;
7955         }
7956
7957         /* Unquiesce VSI */
7958         i40e_unquiesce_vsi(vsi);
7959         return ret;
7960 }
7961
7962 /**
7963  * i40e_set_cld_element - sets cloud filter element data
7964  * @filter: cloud filter rule
7965  * @cld: ptr to cloud filter element data
7966  *
7967  * This is helper function to copy data into cloud filter element
7968  **/
7969 static inline void
7970 i40e_set_cld_element(struct i40e_cloud_filter *filter,
7971                      struct i40e_aqc_cloud_filters_element_data *cld)
7972 {
7973         u32 ipa;
7974         int i;
7975
7976         memset(cld, 0, sizeof(*cld));
7977         ether_addr_copy(cld->outer_mac, filter->dst_mac);
7978         ether_addr_copy(cld->inner_mac, filter->src_mac);
7979
7980         if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
7981                 return;
7982
7983         if (filter->n_proto == ETH_P_IPV6) {
7984 #define IPV6_MAX_INDEX  (ARRAY_SIZE(filter->dst_ipv6) - 1)
7985                 for (i = 0; i < ARRAY_SIZE(filter->dst_ipv6); i++) {
7986                         ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
7987
7988                         *(__le32 *)&cld->ipaddr.raw_v6.data[i * 2] = cpu_to_le32(ipa);
7989                 }
7990         } else {
7991                 ipa = be32_to_cpu(filter->dst_ipv4);
7992
7993                 memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
7994         }
7995
7996         cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
7997
7998         /* tenant_id is not supported by FW now, once the support is enabled
7999          * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
8000          */
8001         if (filter->tenant_id)
8002                 return;
8003 }
8004
8005 /**
8006  * i40e_add_del_cloud_filter - Add/del cloud filter
8007  * @vsi: pointer to VSI
8008  * @filter: cloud filter rule
8009  * @add: if true, add, if false, delete
8010  *
8011  * Add or delete a cloud filter for a specific flow spec.
8012  * Returns 0 if the filter were successfully added.
8013  **/
8014 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
8015                               struct i40e_cloud_filter *filter, bool add)
8016 {
8017         struct i40e_aqc_cloud_filters_element_data cld_filter;
8018         struct i40e_pf *pf = vsi->back;
8019         int ret;
8020         static const u16 flag_table[128] = {
8021                 [I40E_CLOUD_FILTER_FLAGS_OMAC]  =
8022                         I40E_AQC_ADD_CLOUD_FILTER_OMAC,
8023                 [I40E_CLOUD_FILTER_FLAGS_IMAC]  =
8024                         I40E_AQC_ADD_CLOUD_FILTER_IMAC,
8025                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
8026                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
8027                 [I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
8028                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
8029                 [I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
8030                         I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
8031                 [I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
8032                         I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
8033                 [I40E_CLOUD_FILTER_FLAGS_IIP] =
8034                         I40E_AQC_ADD_CLOUD_FILTER_IIP,
8035         };
8036
8037         if (filter->flags >= ARRAY_SIZE(flag_table))
8038                 return I40E_ERR_CONFIG;
8039
8040         memset(&cld_filter, 0, sizeof(cld_filter));
8041
8042         /* copy element needed to add cloud filter from filter */
8043         i40e_set_cld_element(filter, &cld_filter);
8044
8045         if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
8046                 cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
8047                                              I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
8048
8049         if (filter->n_proto == ETH_P_IPV6)
8050                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8051                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8052         else
8053                 cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
8054                                                 I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8055
8056         if (add)
8057                 ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
8058                                                 &cld_filter, 1);
8059         else
8060                 ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
8061                                                 &cld_filter, 1);
8062         if (ret)
8063                 dev_dbg(&pf->pdev->dev,
8064                         "Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
8065                         add ? "add" : "delete", filter->dst_port, ret,
8066                         pf->hw.aq.asq_last_status);
8067         else
8068                 dev_info(&pf->pdev->dev,
8069                          "%s cloud filter for VSI: %d\n",
8070                          add ? "Added" : "Deleted", filter->seid);
8071         return ret;
8072 }
8073
8074 /**
8075  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
8076  * @vsi: pointer to VSI
8077  * @filter: cloud filter rule
8078  * @add: if true, add, if false, delete
8079  *
8080  * Add or delete a cloud filter for a specific flow spec using big buffer.
8081  * Returns 0 if the filter were successfully added.
8082  **/
8083 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
8084                                       struct i40e_cloud_filter *filter,
8085                                       bool add)
8086 {
8087         struct i40e_aqc_cloud_filters_element_bb cld_filter;
8088         struct i40e_pf *pf = vsi->back;
8089         int ret;
8090
8091         /* Both (src/dst) valid mac_addr are not supported */
8092         if ((is_valid_ether_addr(filter->dst_mac) &&
8093              is_valid_ether_addr(filter->src_mac)) ||
8094             (is_multicast_ether_addr(filter->dst_mac) &&
8095              is_multicast_ether_addr(filter->src_mac)))
8096                 return -EOPNOTSUPP;
8097
8098         /* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
8099          * ports are not supported via big buffer now.
8100          */
8101         if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
8102                 return -EOPNOTSUPP;
8103
8104         /* adding filter using src_port/src_ip is not supported at this stage */
8105         if (filter->src_port ||
8106             (filter->src_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8107             !ipv6_addr_any(&filter->ip.v6.src_ip6))
8108                 return -EOPNOTSUPP;
8109
8110         memset(&cld_filter, 0, sizeof(cld_filter));
8111
8112         /* copy element needed to add cloud filter from filter */
8113         i40e_set_cld_element(filter, &cld_filter.element);
8114
8115         if (is_valid_ether_addr(filter->dst_mac) ||
8116             is_valid_ether_addr(filter->src_mac) ||
8117             is_multicast_ether_addr(filter->dst_mac) ||
8118             is_multicast_ether_addr(filter->src_mac)) {
8119                 /* MAC + IP : unsupported mode */
8120                 if (filter->dst_ipv4)
8121                         return -EOPNOTSUPP;
8122
8123                 /* since we validated that L4 port must be valid before
8124                  * we get here, start with respective "flags" value
8125                  * and update if vlan is present or not
8126                  */
8127                 cld_filter.element.flags =
8128                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
8129
8130                 if (filter->vlan_id) {
8131                         cld_filter.element.flags =
8132                         cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
8133                 }
8134
8135         } else if ((filter->dst_ipv4 && filter->n_proto != ETH_P_IPV6) ||
8136                    !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
8137                 cld_filter.element.flags =
8138                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
8139                 if (filter->n_proto == ETH_P_IPV6)
8140                         cld_filter.element.flags |=
8141                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
8142                 else
8143                         cld_filter.element.flags |=
8144                                 cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
8145         } else {
8146                 dev_err(&pf->pdev->dev,
8147                         "either mac or ip has to be valid for cloud filter\n");
8148                 return -EINVAL;
8149         }
8150
8151         /* Now copy L4 port in Byte 6..7 in general fields */
8152         cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
8153                                                 be16_to_cpu(filter->dst_port);
8154
8155         if (add) {
8156                 /* Validate current device switch mode, change if necessary */
8157                 ret = i40e_validate_and_set_switch_mode(vsi);
8158                 if (ret) {
8159                         dev_err(&pf->pdev->dev,
8160                                 "failed to set switch mode, ret %d\n",
8161                                 ret);
8162                         return ret;
8163                 }
8164
8165                 ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
8166                                                    &cld_filter, 1);
8167         } else {
8168                 ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
8169                                                    &cld_filter, 1);
8170         }
8171
8172         if (ret)
8173                 dev_dbg(&pf->pdev->dev,
8174                         "Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
8175                         add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
8176         else
8177                 dev_info(&pf->pdev->dev,
8178                          "%s cloud filter for VSI: %d, L4 port: %d\n",
8179                          add ? "add" : "delete", filter->seid,
8180                          ntohs(filter->dst_port));
8181         return ret;
8182 }
8183
8184 /**
8185  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
8186  * @vsi: Pointer to VSI
8187  * @f: Pointer to struct flow_cls_offload
8188  * @filter: Pointer to cloud filter structure
8189  *
8190  **/
8191 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
8192                                  struct flow_cls_offload *f,
8193                                  struct i40e_cloud_filter *filter)
8194 {
8195         struct flow_rule *rule = flow_cls_offload_flow_rule(f);
8196         struct flow_dissector *dissector = rule->match.dissector;
8197         u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
8198         struct i40e_pf *pf = vsi->back;
8199         u8 field_flags = 0;
8200
8201         if (dissector->used_keys &
8202             ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
8203               BIT(FLOW_DISSECTOR_KEY_BASIC) |
8204               BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
8205               BIT(FLOW_DISSECTOR_KEY_VLAN) |
8206               BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
8207               BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
8208               BIT(FLOW_DISSECTOR_KEY_PORTS) |
8209               BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
8210                 dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
8211                         dissector->used_keys);
8212                 return -EOPNOTSUPP;
8213         }
8214
8215         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
8216                 struct flow_match_enc_keyid match;
8217
8218                 flow_rule_match_enc_keyid(rule, &match);
8219                 if (match.mask->keyid != 0)
8220                         field_flags |= I40E_CLOUD_FIELD_TEN_ID;
8221
8222                 filter->tenant_id = be32_to_cpu(match.key->keyid);
8223         }
8224
8225         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
8226                 struct flow_match_basic match;
8227
8228                 flow_rule_match_basic(rule, &match);
8229                 n_proto_key = ntohs(match.key->n_proto);
8230                 n_proto_mask = ntohs(match.mask->n_proto);
8231
8232                 if (n_proto_key == ETH_P_ALL) {
8233                         n_proto_key = 0;
8234                         n_proto_mask = 0;
8235                 }
8236                 filter->n_proto = n_proto_key & n_proto_mask;
8237                 filter->ip_proto = match.key->ip_proto;
8238         }
8239
8240         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
8241                 struct flow_match_eth_addrs match;
8242
8243                 flow_rule_match_eth_addrs(rule, &match);
8244
8245                 /* use is_broadcast and is_zero to check for all 0xf or 0 */
8246                 if (!is_zero_ether_addr(match.mask->dst)) {
8247                         if (is_broadcast_ether_addr(match.mask->dst)) {
8248                                 field_flags |= I40E_CLOUD_FIELD_OMAC;
8249                         } else {
8250                                 dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
8251                                         match.mask->dst);
8252                                 return I40E_ERR_CONFIG;
8253                         }
8254                 }
8255
8256                 if (!is_zero_ether_addr(match.mask->src)) {
8257                         if (is_broadcast_ether_addr(match.mask->src)) {
8258                                 field_flags |= I40E_CLOUD_FIELD_IMAC;
8259                         } else {
8260                                 dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
8261                                         match.mask->src);
8262                                 return I40E_ERR_CONFIG;
8263                         }
8264                 }
8265                 ether_addr_copy(filter->dst_mac, match.key->dst);
8266                 ether_addr_copy(filter->src_mac, match.key->src);
8267         }
8268
8269         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
8270                 struct flow_match_vlan match;
8271
8272                 flow_rule_match_vlan(rule, &match);
8273                 if (match.mask->vlan_id) {
8274                         if (match.mask->vlan_id == VLAN_VID_MASK) {
8275                                 field_flags |= I40E_CLOUD_FIELD_IVLAN;
8276
8277                         } else {
8278                                 dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
8279                                         match.mask->vlan_id);
8280                                 return I40E_ERR_CONFIG;
8281                         }
8282                 }
8283
8284                 filter->vlan_id = cpu_to_be16(match.key->vlan_id);
8285         }
8286
8287         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
8288                 struct flow_match_control match;
8289
8290                 flow_rule_match_control(rule, &match);
8291                 addr_type = match.key->addr_type;
8292         }
8293
8294         if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
8295                 struct flow_match_ipv4_addrs match;
8296
8297                 flow_rule_match_ipv4_addrs(rule, &match);
8298                 if (match.mask->dst) {
8299                         if (match.mask->dst == cpu_to_be32(0xffffffff)) {
8300                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8301                         } else {
8302                                 dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
8303                                         &match.mask->dst);
8304                                 return I40E_ERR_CONFIG;
8305                         }
8306                 }
8307
8308                 if (match.mask->src) {
8309                         if (match.mask->src == cpu_to_be32(0xffffffff)) {
8310                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8311                         } else {
8312                                 dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
8313                                         &match.mask->src);
8314                                 return I40E_ERR_CONFIG;
8315                         }
8316                 }
8317
8318                 if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
8319                         dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
8320                         return I40E_ERR_CONFIG;
8321                 }
8322                 filter->dst_ipv4 = match.key->dst;
8323                 filter->src_ipv4 = match.key->src;
8324         }
8325
8326         if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
8327                 struct flow_match_ipv6_addrs match;
8328
8329                 flow_rule_match_ipv6_addrs(rule, &match);
8330
8331                 /* src and dest IPV6 address should not be LOOPBACK
8332                  * (0:0:0:0:0:0:0:1), which can be represented as ::1
8333                  */
8334                 if (ipv6_addr_loopback(&match.key->dst) ||
8335                     ipv6_addr_loopback(&match.key->src)) {
8336                         dev_err(&pf->pdev->dev,
8337                                 "Bad ipv6, addr is LOOPBACK\n");
8338                         return I40E_ERR_CONFIG;
8339                 }
8340                 if (!ipv6_addr_any(&match.mask->dst) ||
8341                     !ipv6_addr_any(&match.mask->src))
8342                         field_flags |= I40E_CLOUD_FIELD_IIP;
8343
8344                 memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
8345                        sizeof(filter->src_ipv6));
8346                 memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
8347                        sizeof(filter->dst_ipv6));
8348         }
8349
8350         if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
8351                 struct flow_match_ports match;
8352
8353                 flow_rule_match_ports(rule, &match);
8354                 if (match.mask->src) {
8355                         if (match.mask->src == cpu_to_be16(0xffff)) {
8356                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8357                         } else {
8358                                 dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
8359                                         be16_to_cpu(match.mask->src));
8360                                 return I40E_ERR_CONFIG;
8361                         }
8362                 }
8363
8364                 if (match.mask->dst) {
8365                         if (match.mask->dst == cpu_to_be16(0xffff)) {
8366                                 field_flags |= I40E_CLOUD_FIELD_IIP;
8367                         } else {
8368                                 dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
8369                                         be16_to_cpu(match.mask->dst));
8370                                 return I40E_ERR_CONFIG;
8371                         }
8372                 }
8373
8374                 filter->dst_port = match.key->dst;
8375                 filter->src_port = match.key->src;
8376
8377                 switch (filter->ip_proto) {
8378                 case IPPROTO_TCP:
8379                 case IPPROTO_UDP:
8380                         break;
8381                 default:
8382                         dev_err(&pf->pdev->dev,
8383                                 "Only UDP and TCP transport are supported\n");
8384                         return -EINVAL;
8385                 }
8386         }
8387         filter->flags = field_flags;
8388         return 0;
8389 }
8390
8391 /**
8392  * i40e_handle_tclass: Forward to a traffic class on the device
8393  * @vsi: Pointer to VSI
8394  * @tc: traffic class index on the device
8395  * @filter: Pointer to cloud filter structure
8396  *
8397  **/
8398 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
8399                               struct i40e_cloud_filter *filter)
8400 {
8401         struct i40e_channel *ch, *ch_tmp;
8402
8403         /* direct to a traffic class on the same device */
8404         if (tc == 0) {
8405                 filter->seid = vsi->seid;
8406                 return 0;
8407         } else if (vsi->tc_config.enabled_tc & BIT(tc)) {
8408                 if (!filter->dst_port) {
8409                         dev_err(&vsi->back->pdev->dev,
8410                                 "Specify destination port to direct to traffic class that is not default\n");
8411                         return -EINVAL;
8412                 }
8413                 if (list_empty(&vsi->ch_list))
8414                         return -EINVAL;
8415                 list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
8416                                          list) {
8417                         if (ch->seid == vsi->tc_seid_map[tc])
8418                                 filter->seid = ch->seid;
8419                 }
8420                 return 0;
8421         }
8422         dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
8423         return -EINVAL;
8424 }
8425
8426 /**
8427  * i40e_configure_clsflower - Configure tc flower filters
8428  * @vsi: Pointer to VSI
8429  * @cls_flower: Pointer to struct flow_cls_offload
8430  *
8431  **/
8432 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
8433                                     struct flow_cls_offload *cls_flower)
8434 {
8435         int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
8436         struct i40e_cloud_filter *filter = NULL;
8437         struct i40e_pf *pf = vsi->back;
8438         int err = 0;
8439
8440         if (tc < 0) {
8441                 dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
8442                 return -EOPNOTSUPP;
8443         }
8444
8445         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
8446             test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
8447                 return -EBUSY;
8448
8449         if (pf->fdir_pf_active_filters ||
8450             (!hlist_empty(&pf->fdir_filter_list))) {
8451                 dev_err(&vsi->back->pdev->dev,
8452                         "Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
8453                 return -EINVAL;
8454         }
8455
8456         if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
8457                 dev_err(&vsi->back->pdev->dev,
8458                         "Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
8459                 vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8460                 vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8461         }
8462
8463         filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8464         if (!filter)
8465                 return -ENOMEM;
8466
8467         filter->cookie = cls_flower->cookie;
8468
8469         err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8470         if (err < 0)
8471                 goto err;
8472
8473         err = i40e_handle_tclass(vsi, tc, filter);
8474         if (err < 0)
8475                 goto err;
8476
8477         /* Add cloud filter */
8478         if (filter->dst_port)
8479                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8480         else
8481                 err = i40e_add_del_cloud_filter(vsi, filter, true);
8482
8483         if (err) {
8484                 dev_err(&pf->pdev->dev,
8485                         "Failed to add cloud filter, err %s\n",
8486                         i40e_stat_str(&pf->hw, err));
8487                 goto err;
8488         }
8489
8490         /* add filter to the ordered list */
8491         INIT_HLIST_NODE(&filter->cloud_node);
8492
8493         hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8494
8495         pf->num_cloud_filters++;
8496
8497         return err;
8498 err:
8499         kfree(filter);
8500         return err;
8501 }
8502
8503 /**
8504  * i40e_find_cloud_filter - Find the could filter in the list
8505  * @vsi: Pointer to VSI
8506  * @cookie: filter specific cookie
8507  *
8508  **/
8509 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8510                                                         unsigned long *cookie)
8511 {
8512         struct i40e_cloud_filter *filter = NULL;
8513         struct hlist_node *node2;
8514
8515         hlist_for_each_entry_safe(filter, node2,
8516                                   &vsi->back->cloud_filter_list, cloud_node)
8517                 if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8518                         return filter;
8519         return NULL;
8520 }
8521
8522 /**
8523  * i40e_delete_clsflower - Remove tc flower filters
8524  * @vsi: Pointer to VSI
8525  * @cls_flower: Pointer to struct flow_cls_offload
8526  *
8527  **/
8528 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8529                                  struct flow_cls_offload *cls_flower)
8530 {
8531         struct i40e_cloud_filter *filter = NULL;
8532         struct i40e_pf *pf = vsi->back;
8533         int err = 0;
8534
8535         filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8536
8537         if (!filter)
8538                 return -EINVAL;
8539
8540         hash_del(&filter->cloud_node);
8541
8542         if (filter->dst_port)
8543                 err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8544         else
8545                 err = i40e_add_del_cloud_filter(vsi, filter, false);
8546
8547         kfree(filter);
8548         if (err) {
8549                 dev_err(&pf->pdev->dev,
8550                         "Failed to delete cloud filter, err %s\n",
8551                         i40e_stat_str(&pf->hw, err));
8552                 return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8553         }
8554
8555         pf->num_cloud_filters--;
8556         if (!pf->num_cloud_filters)
8557                 if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8558                     !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8559                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8560                         pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8561                         pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8562                 }
8563         return 0;
8564 }
8565
8566 /**
8567  * i40e_setup_tc_cls_flower - flower classifier offloads
8568  * @np: net device to configure
8569  * @cls_flower: offload data
8570  **/
8571 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8572                                     struct flow_cls_offload *cls_flower)
8573 {
8574         struct i40e_vsi *vsi = np->vsi;
8575
8576         switch (cls_flower->command) {
8577         case FLOW_CLS_REPLACE:
8578                 return i40e_configure_clsflower(vsi, cls_flower);
8579         case FLOW_CLS_DESTROY:
8580                 return i40e_delete_clsflower(vsi, cls_flower);
8581         case FLOW_CLS_STATS:
8582                 return -EOPNOTSUPP;
8583         default:
8584                 return -EOPNOTSUPP;
8585         }
8586 }
8587
8588 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8589                                   void *cb_priv)
8590 {
8591         struct i40e_netdev_priv *np = cb_priv;
8592
8593         if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8594                 return -EOPNOTSUPP;
8595
8596         switch (type) {
8597         case TC_SETUP_CLSFLOWER:
8598                 return i40e_setup_tc_cls_flower(np, type_data);
8599
8600         default:
8601                 return -EOPNOTSUPP;
8602         }
8603 }
8604
8605 static LIST_HEAD(i40e_block_cb_list);
8606
8607 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8608                            void *type_data)
8609 {
8610         struct i40e_netdev_priv *np = netdev_priv(netdev);
8611
8612         switch (type) {
8613         case TC_SETUP_QDISC_MQPRIO:
8614                 return i40e_setup_tc(netdev, type_data);
8615         case TC_SETUP_BLOCK:
8616                 return flow_block_cb_setup_simple(type_data,
8617                                                   &i40e_block_cb_list,
8618                                                   i40e_setup_tc_block_cb,
8619                                                   np, np, true);
8620         default:
8621                 return -EOPNOTSUPP;
8622         }
8623 }
8624
8625 /**
8626  * i40e_open - Called when a network interface is made active
8627  * @netdev: network interface device structure
8628  *
8629  * The open entry point is called when a network interface is made
8630  * active by the system (IFF_UP).  At this point all resources needed
8631  * for transmit and receive operations are allocated, the interrupt
8632  * handler is registered with the OS, the netdev watchdog subtask is
8633  * enabled, and the stack is notified that the interface is ready.
8634  *
8635  * Returns 0 on success, negative value on failure
8636  **/
8637 int i40e_open(struct net_device *netdev)
8638 {
8639         struct i40e_netdev_priv *np = netdev_priv(netdev);
8640         struct i40e_vsi *vsi = np->vsi;
8641         struct i40e_pf *pf = vsi->back;
8642         int err;
8643
8644         /* disallow open during test or if eeprom is broken */
8645         if (test_bit(__I40E_TESTING, pf->state) ||
8646             test_bit(__I40E_BAD_EEPROM, pf->state))
8647                 return -EBUSY;
8648
8649         netif_carrier_off(netdev);
8650
8651         if (i40e_force_link_state(pf, true))
8652                 return -EAGAIN;
8653
8654         err = i40e_vsi_open(vsi);
8655         if (err)
8656                 return err;
8657
8658         /* configure global TSO hardware offload settings */
8659         wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8660                                                        TCP_FLAG_FIN) >> 16);
8661         wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8662                                                        TCP_FLAG_FIN |
8663                                                        TCP_FLAG_CWR) >> 16);
8664         wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8665         udp_tunnel_get_rx_info(netdev);
8666
8667         return 0;
8668 }
8669
8670 /**
8671  * i40e_vsi_open -
8672  * @vsi: the VSI to open
8673  *
8674  * Finish initialization of the VSI.
8675  *
8676  * Returns 0 on success, negative value on failure
8677  *
8678  * Note: expects to be called while under rtnl_lock()
8679  **/
8680 int i40e_vsi_open(struct i40e_vsi *vsi)
8681 {
8682         struct i40e_pf *pf = vsi->back;
8683         char int_name[I40E_INT_NAME_STR_LEN];
8684         int err;
8685
8686         /* allocate descriptors */
8687         err = i40e_vsi_setup_tx_resources(vsi);
8688         if (err)
8689                 goto err_setup_tx;
8690         err = i40e_vsi_setup_rx_resources(vsi);
8691         if (err)
8692                 goto err_setup_rx;
8693
8694         err = i40e_vsi_configure(vsi);
8695         if (err)
8696                 goto err_setup_rx;
8697
8698         if (vsi->netdev) {
8699                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
8700                          dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
8701                 err = i40e_vsi_request_irq(vsi, int_name);
8702                 if (err)
8703                         goto err_setup_rx;
8704
8705                 /* Notify the stack of the actual queue counts. */
8706                 err = netif_set_real_num_tx_queues(vsi->netdev,
8707                                                    vsi->num_queue_pairs);
8708                 if (err)
8709                         goto err_set_queues;
8710
8711                 err = netif_set_real_num_rx_queues(vsi->netdev,
8712                                                    vsi->num_queue_pairs);
8713                 if (err)
8714                         goto err_set_queues;
8715
8716         } else if (vsi->type == I40E_VSI_FDIR) {
8717                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
8718                          dev_driver_string(&pf->pdev->dev),
8719                          dev_name(&pf->pdev->dev));
8720                 err = i40e_vsi_request_irq(vsi, int_name);
8721                 if (err)
8722                         goto err_setup_rx;
8723
8724         } else {
8725                 err = -EINVAL;
8726                 goto err_setup_rx;
8727         }
8728
8729         err = i40e_up_complete(vsi);
8730         if (err)
8731                 goto err_up_complete;
8732
8733         return 0;
8734
8735 err_up_complete:
8736         i40e_down(vsi);
8737 err_set_queues:
8738         i40e_vsi_free_irq(vsi);
8739 err_setup_rx:
8740         i40e_vsi_free_rx_resources(vsi);
8741 err_setup_tx:
8742         i40e_vsi_free_tx_resources(vsi);
8743         if (vsi == pf->vsi[pf->lan_vsi])
8744                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
8745
8746         return err;
8747 }
8748
8749 /**
8750  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
8751  * @pf: Pointer to PF
8752  *
8753  * This function destroys the hlist where all the Flow Director
8754  * filters were saved.
8755  **/
8756 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
8757 {
8758         struct i40e_fdir_filter *filter;
8759         struct i40e_flex_pit *pit_entry, *tmp;
8760         struct hlist_node *node2;
8761
8762         hlist_for_each_entry_safe(filter, node2,
8763                                   &pf->fdir_filter_list, fdir_node) {
8764                 hlist_del(&filter->fdir_node);
8765                 kfree(filter);
8766         }
8767
8768         list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
8769                 list_del(&pit_entry->list);
8770                 kfree(pit_entry);
8771         }
8772         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
8773
8774         list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
8775                 list_del(&pit_entry->list);
8776                 kfree(pit_entry);
8777         }
8778         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
8779
8780         pf->fdir_pf_active_filters = 0;
8781         i40e_reset_fdir_filter_cnt(pf);
8782
8783         /* Reprogram the default input set for TCP/IPv4 */
8784         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
8785                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8786                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8787
8788         /* Reprogram the default input set for TCP/IPv6 */
8789         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_TCP,
8790                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
8791                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8792
8793         /* Reprogram the default input set for UDP/IPv4 */
8794         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
8795                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8796                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8797
8798         /* Reprogram the default input set for UDP/IPv6 */
8799         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_UDP,
8800                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
8801                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8802
8803         /* Reprogram the default input set for SCTP/IPv4 */
8804         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
8805                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8806                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8807
8808         /* Reprogram the default input set for SCTP/IPv6 */
8809         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_SCTP,
8810                                 I40E_L3_V6_SRC_MASK | I40E_L3_V6_DST_MASK |
8811                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8812
8813         /* Reprogram the default input set for Other/IPv4 */
8814         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
8815                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
8816
8817         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
8818                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
8819
8820         /* Reprogram the default input set for Other/IPv6 */
8821         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV6_OTHER,
8822                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
8823
8824         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV6,
8825                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
8826 }
8827
8828 /**
8829  * i40e_cloud_filter_exit - Cleans up the cloud filters
8830  * @pf: Pointer to PF
8831  *
8832  * This function destroys the hlist where all the cloud filters
8833  * were saved.
8834  **/
8835 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
8836 {
8837         struct i40e_cloud_filter *cfilter;
8838         struct hlist_node *node;
8839
8840         hlist_for_each_entry_safe(cfilter, node,
8841                                   &pf->cloud_filter_list, cloud_node) {
8842                 hlist_del(&cfilter->cloud_node);
8843                 kfree(cfilter);
8844         }
8845         pf->num_cloud_filters = 0;
8846
8847         if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8848             !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8849                 pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8850                 pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8851                 pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8852         }
8853 }
8854
8855 /**
8856  * i40e_close - Disables a network interface
8857  * @netdev: network interface device structure
8858  *
8859  * The close entry point is called when an interface is de-activated
8860  * by the OS.  The hardware is still under the driver's control, but
8861  * this netdev interface is disabled.
8862  *
8863  * Returns 0, this is not allowed to fail
8864  **/
8865 int i40e_close(struct net_device *netdev)
8866 {
8867         struct i40e_netdev_priv *np = netdev_priv(netdev);
8868         struct i40e_vsi *vsi = np->vsi;
8869
8870         i40e_vsi_close(vsi);
8871
8872         return 0;
8873 }
8874
8875 /**
8876  * i40e_do_reset - Start a PF or Core Reset sequence
8877  * @pf: board private structure
8878  * @reset_flags: which reset is requested
8879  * @lock_acquired: indicates whether or not the lock has been acquired
8880  * before this function was called.
8881  *
8882  * The essential difference in resets is that the PF Reset
8883  * doesn't clear the packet buffers, doesn't reset the PE
8884  * firmware, and doesn't bother the other PFs on the chip.
8885  **/
8886 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
8887 {
8888         u32 val;
8889
8890         /* do the biggest reset indicated */
8891         if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
8892
8893                 /* Request a Global Reset
8894                  *
8895                  * This will start the chip's countdown to the actual full
8896                  * chip reset event, and a warning interrupt to be sent
8897                  * to all PFs, including the requestor.  Our handler
8898                  * for the warning interrupt will deal with the shutdown
8899                  * and recovery of the switch setup.
8900                  */
8901                 dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
8902                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
8903                 val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
8904                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
8905
8906         } else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
8907
8908                 /* Request a Core Reset
8909                  *
8910                  * Same as Global Reset, except does *not* include the MAC/PHY
8911                  */
8912                 dev_dbg(&pf->pdev->dev, "CoreR requested\n");
8913                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
8914                 val |= I40E_GLGEN_RTRIG_CORER_MASK;
8915                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
8916                 i40e_flush(&pf->hw);
8917
8918         } else if (reset_flags & I40E_PF_RESET_FLAG) {
8919
8920                 /* Request a PF Reset
8921                  *
8922                  * Resets only the PF-specific registers
8923                  *
8924                  * This goes directly to the tear-down and rebuild of
8925                  * the switch, since we need to do all the recovery as
8926                  * for the Core Reset.
8927                  */
8928                 dev_dbg(&pf->pdev->dev, "PFR requested\n");
8929                 i40e_handle_reset_warning(pf, lock_acquired);
8930
8931         } else if (reset_flags & I40E_PF_RESET_AND_REBUILD_FLAG) {
8932                 /* Request a PF Reset
8933                  *
8934                  * Resets PF and reinitializes PFs VSI.
8935                  */
8936                 i40e_prep_for_reset(pf);
8937                 i40e_reset_and_rebuild(pf, true, lock_acquired);
8938                 dev_info(&pf->pdev->dev,
8939                          pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
8940                          "FW LLDP is disabled\n" :
8941                          "FW LLDP is enabled\n");
8942
8943         } else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
8944                 int v;
8945
8946                 /* Find the VSI(s) that requested a re-init */
8947                 dev_info(&pf->pdev->dev,
8948                          "VSI reinit requested\n");
8949                 for (v = 0; v < pf->num_alloc_vsi; v++) {
8950                         struct i40e_vsi *vsi = pf->vsi[v];
8951
8952                         if (vsi != NULL &&
8953                             test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
8954                                                vsi->state))
8955                                 i40e_vsi_reinit_locked(pf->vsi[v]);
8956                 }
8957         } else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
8958                 int v;
8959
8960                 /* Find the VSI(s) that needs to be brought down */
8961                 dev_info(&pf->pdev->dev, "VSI down requested\n");
8962                 for (v = 0; v < pf->num_alloc_vsi; v++) {
8963                         struct i40e_vsi *vsi = pf->vsi[v];
8964
8965                         if (vsi != NULL &&
8966                             test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
8967                                                vsi->state)) {
8968                                 set_bit(__I40E_VSI_DOWN, vsi->state);
8969                                 i40e_down(vsi);
8970                         }
8971                 }
8972         } else {
8973                 dev_info(&pf->pdev->dev,
8974                          "bad reset request 0x%08x\n", reset_flags);
8975         }
8976 }
8977
8978 #ifdef CONFIG_I40E_DCB
8979 /**
8980  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
8981  * @pf: board private structure
8982  * @old_cfg: current DCB config
8983  * @new_cfg: new DCB config
8984  **/
8985 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
8986                             struct i40e_dcbx_config *old_cfg,
8987                             struct i40e_dcbx_config *new_cfg)
8988 {
8989         bool need_reconfig = false;
8990
8991         /* Check if ETS configuration has changed */
8992         if (memcmp(&new_cfg->etscfg,
8993                    &old_cfg->etscfg,
8994                    sizeof(new_cfg->etscfg))) {
8995                 /* If Priority Table has changed reconfig is needed */
8996                 if (memcmp(&new_cfg->etscfg.prioritytable,
8997                            &old_cfg->etscfg.prioritytable,
8998                            sizeof(new_cfg->etscfg.prioritytable))) {
8999                         need_reconfig = true;
9000                         dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
9001                 }
9002
9003                 if (memcmp(&new_cfg->etscfg.tcbwtable,
9004                            &old_cfg->etscfg.tcbwtable,
9005                            sizeof(new_cfg->etscfg.tcbwtable)))
9006                         dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
9007
9008                 if (memcmp(&new_cfg->etscfg.tsatable,
9009                            &old_cfg->etscfg.tsatable,
9010                            sizeof(new_cfg->etscfg.tsatable)))
9011                         dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
9012         }
9013
9014         /* Check if PFC configuration has changed */
9015         if (memcmp(&new_cfg->pfc,
9016                    &old_cfg->pfc,
9017                    sizeof(new_cfg->pfc))) {
9018                 need_reconfig = true;
9019                 dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
9020         }
9021
9022         /* Check if APP Table has changed */
9023         if (memcmp(&new_cfg->app,
9024                    &old_cfg->app,
9025                    sizeof(new_cfg->app))) {
9026                 need_reconfig = true;
9027                 dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
9028         }
9029
9030         dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
9031         return need_reconfig;
9032 }
9033
9034 /**
9035  * i40e_handle_lldp_event - Handle LLDP Change MIB event
9036  * @pf: board private structure
9037  * @e: event info posted on ARQ
9038  **/
9039 static int i40e_handle_lldp_event(struct i40e_pf *pf,
9040                                   struct i40e_arq_event_info *e)
9041 {
9042         struct i40e_aqc_lldp_get_mib *mib =
9043                 (struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
9044         struct i40e_hw *hw = &pf->hw;
9045         struct i40e_dcbx_config tmp_dcbx_cfg;
9046         bool need_reconfig = false;
9047         int ret = 0;
9048         u8 type;
9049
9050         /* X710-T*L 2.5G and 5G speeds don't support DCB */
9051         if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9052             (hw->phy.link_info.link_speed &
9053              ~(I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB)) &&
9054              !(pf->flags & I40E_FLAG_DCB_CAPABLE))
9055                 /* let firmware decide if the DCB should be disabled */
9056                 pf->flags |= I40E_FLAG_DCB_CAPABLE;
9057
9058         /* Not DCB capable or capability disabled */
9059         if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
9060                 return ret;
9061
9062         /* Ignore if event is not for Nearest Bridge */
9063         type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
9064                 & I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
9065         dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
9066         if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
9067                 return ret;
9068
9069         /* Check MIB Type and return if event for Remote MIB update */
9070         type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
9071         dev_dbg(&pf->pdev->dev,
9072                 "LLDP event mib type %s\n", type ? "remote" : "local");
9073         if (type == I40E_AQ_LLDP_MIB_REMOTE) {
9074                 /* Update the remote cached instance and return */
9075                 ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
9076                                 I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
9077                                 &hw->remote_dcbx_config);
9078                 goto exit;
9079         }
9080
9081         /* Store the old configuration */
9082         tmp_dcbx_cfg = hw->local_dcbx_config;
9083
9084         /* Reset the old DCBx configuration data */
9085         memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
9086         /* Get updated DCBX data from firmware */
9087         ret = i40e_get_dcb_config(&pf->hw);
9088         if (ret) {
9089                 /* X710-T*L 2.5G and 5G speeds don't support DCB */
9090                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
9091                     (hw->phy.link_info.link_speed &
9092                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
9093                         dev_warn(&pf->pdev->dev,
9094                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
9095                         pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
9096                 } else {
9097                         dev_info(&pf->pdev->dev,
9098                                  "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
9099                                  i40e_stat_str(&pf->hw, ret),
9100                                  i40e_aq_str(&pf->hw,
9101                                              pf->hw.aq.asq_last_status));
9102                 }
9103                 goto exit;
9104         }
9105
9106         /* No change detected in DCBX configs */
9107         if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
9108                     sizeof(tmp_dcbx_cfg))) {
9109                 dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
9110                 goto exit;
9111         }
9112
9113         need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
9114                                                &hw->local_dcbx_config);
9115
9116         i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
9117
9118         if (!need_reconfig)
9119                 goto exit;
9120
9121         /* Enable DCB tagging only when more than one TC */
9122         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
9123                 pf->flags |= I40E_FLAG_DCB_ENABLED;
9124         else
9125                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9126
9127         set_bit(__I40E_PORT_SUSPENDED, pf->state);
9128         /* Reconfiguration needed quiesce all VSIs */
9129         i40e_pf_quiesce_all_vsi(pf);
9130
9131         /* Changes in configuration update VEB/VSI */
9132         i40e_dcb_reconfigure(pf);
9133
9134         ret = i40e_resume_port_tx(pf);
9135
9136         clear_bit(__I40E_PORT_SUSPENDED, pf->state);
9137         /* In case of error no point in resuming VSIs */
9138         if (ret)
9139                 goto exit;
9140
9141         /* Wait for the PF's queues to be disabled */
9142         ret = i40e_pf_wait_queues_disabled(pf);
9143         if (ret) {
9144                 /* Schedule PF reset to recover */
9145                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9146                 i40e_service_event_schedule(pf);
9147         } else {
9148                 i40e_pf_unquiesce_all_vsi(pf);
9149                 set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
9150                 set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
9151         }
9152
9153 exit:
9154         return ret;
9155 }
9156 #endif /* CONFIG_I40E_DCB */
9157
9158 /**
9159  * i40e_do_reset_safe - Protected reset path for userland calls.
9160  * @pf: board private structure
9161  * @reset_flags: which reset is requested
9162  *
9163  **/
9164 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
9165 {
9166         rtnl_lock();
9167         i40e_do_reset(pf, reset_flags, true);
9168         rtnl_unlock();
9169 }
9170
9171 /**
9172  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
9173  * @pf: board private structure
9174  * @e: event info posted on ARQ
9175  *
9176  * Handler for LAN Queue Overflow Event generated by the firmware for PF
9177  * and VF queues
9178  **/
9179 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
9180                                            struct i40e_arq_event_info *e)
9181 {
9182         struct i40e_aqc_lan_overflow *data =
9183                 (struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
9184         u32 queue = le32_to_cpu(data->prtdcb_rupto);
9185         u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
9186         struct i40e_hw *hw = &pf->hw;
9187         struct i40e_vf *vf;
9188         u16 vf_id;
9189
9190         dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
9191                 queue, qtx_ctl);
9192
9193         /* Queue belongs to VF, find the VF and issue VF reset */
9194         if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
9195             >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
9196                 vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
9197                          >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
9198                 vf_id -= hw->func_caps.vf_base_id;
9199                 vf = &pf->vf[vf_id];
9200                 i40e_vc_notify_vf_reset(vf);
9201                 /* Allow VF to process pending reset notification */
9202                 msleep(20);
9203                 i40e_reset_vf(vf, false);
9204         }
9205 }
9206
9207 /**
9208  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
9209  * @pf: board private structure
9210  **/
9211 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
9212 {
9213         u32 val, fcnt_prog;
9214
9215         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9216         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
9217         return fcnt_prog;
9218 }
9219
9220 /**
9221  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
9222  * @pf: board private structure
9223  **/
9224 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
9225 {
9226         u32 val, fcnt_prog;
9227
9228         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
9229         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
9230                     ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
9231                       I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
9232         return fcnt_prog;
9233 }
9234
9235 /**
9236  * i40e_get_global_fd_count - Get total FD filters programmed on device
9237  * @pf: board private structure
9238  **/
9239 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
9240 {
9241         u32 val, fcnt_prog;
9242
9243         val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
9244         fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
9245                     ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
9246                      I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
9247         return fcnt_prog;
9248 }
9249
9250 /**
9251  * i40e_reenable_fdir_sb - Restore FDir SB capability
9252  * @pf: board private structure
9253  **/
9254 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
9255 {
9256         if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
9257                 if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
9258                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9259                         dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
9260 }
9261
9262 /**
9263  * i40e_reenable_fdir_atr - Restore FDir ATR capability
9264  * @pf: board private structure
9265  **/
9266 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
9267 {
9268         if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
9269                 /* ATR uses the same filtering logic as SB rules. It only
9270                  * functions properly if the input set mask is at the default
9271                  * settings. It is safe to restore the default input set
9272                  * because there are no active TCPv4 filter rules.
9273                  */
9274                 i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
9275                                         I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
9276                                         I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
9277
9278                 if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9279                     (I40E_DEBUG_FD & pf->hw.debug_mask))
9280                         dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
9281         }
9282 }
9283
9284 /**
9285  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
9286  * @pf: board private structure
9287  * @filter: FDir filter to remove
9288  */
9289 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
9290                                        struct i40e_fdir_filter *filter)
9291 {
9292         /* Update counters */
9293         pf->fdir_pf_active_filters--;
9294         pf->fd_inv = 0;
9295
9296         switch (filter->flow_type) {
9297         case TCP_V4_FLOW:
9298                 pf->fd_tcp4_filter_cnt--;
9299                 break;
9300         case UDP_V4_FLOW:
9301                 pf->fd_udp4_filter_cnt--;
9302                 break;
9303         case SCTP_V4_FLOW:
9304                 pf->fd_sctp4_filter_cnt--;
9305                 break;
9306         case TCP_V6_FLOW:
9307                 pf->fd_tcp6_filter_cnt--;
9308                 break;
9309         case UDP_V6_FLOW:
9310                 pf->fd_udp6_filter_cnt--;
9311                 break;
9312         case SCTP_V6_FLOW:
9313                 pf->fd_udp6_filter_cnt--;
9314                 break;
9315         case IP_USER_FLOW:
9316                 switch (filter->ipl4_proto) {
9317                 case IPPROTO_TCP:
9318                         pf->fd_tcp4_filter_cnt--;
9319                         break;
9320                 case IPPROTO_UDP:
9321                         pf->fd_udp4_filter_cnt--;
9322                         break;
9323                 case IPPROTO_SCTP:
9324                         pf->fd_sctp4_filter_cnt--;
9325                         break;
9326                 case IPPROTO_IP:
9327                         pf->fd_ip4_filter_cnt--;
9328                         break;
9329                 }
9330                 break;
9331         case IPV6_USER_FLOW:
9332                 switch (filter->ipl4_proto) {
9333                 case IPPROTO_TCP:
9334                         pf->fd_tcp6_filter_cnt--;
9335                         break;
9336                 case IPPROTO_UDP:
9337                         pf->fd_udp6_filter_cnt--;
9338                         break;
9339                 case IPPROTO_SCTP:
9340                         pf->fd_sctp6_filter_cnt--;
9341                         break;
9342                 case IPPROTO_IP:
9343                         pf->fd_ip6_filter_cnt--;
9344                         break;
9345                 }
9346                 break;
9347         }
9348
9349         /* Remove the filter from the list and free memory */
9350         hlist_del(&filter->fdir_node);
9351         kfree(filter);
9352 }
9353
9354 /**
9355  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
9356  * @pf: board private structure
9357  **/
9358 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
9359 {
9360         struct i40e_fdir_filter *filter;
9361         u32 fcnt_prog, fcnt_avail;
9362         struct hlist_node *node;
9363
9364         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9365                 return;
9366
9367         /* Check if we have enough room to re-enable FDir SB capability. */
9368         fcnt_prog = i40e_get_global_fd_count(pf);
9369         fcnt_avail = pf->fdir_pf_filter_count;
9370         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
9371             (pf->fd_add_err == 0) ||
9372             (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
9373                 i40e_reenable_fdir_sb(pf);
9374
9375         /* We should wait for even more space before re-enabling ATR.
9376          * Additionally, we cannot enable ATR as long as we still have TCP SB
9377          * rules active.
9378          */
9379         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
9380             pf->fd_tcp4_filter_cnt == 0 && pf->fd_tcp6_filter_cnt == 0)
9381                 i40e_reenable_fdir_atr(pf);
9382
9383         /* if hw had a problem adding a filter, delete it */
9384         if (pf->fd_inv > 0) {
9385                 hlist_for_each_entry_safe(filter, node,
9386                                           &pf->fdir_filter_list, fdir_node)
9387                         if (filter->fd_id == pf->fd_inv)
9388                                 i40e_delete_invalid_filter(pf, filter);
9389         }
9390 }
9391
9392 #define I40E_MIN_FD_FLUSH_INTERVAL 10
9393 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
9394 /**
9395  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
9396  * @pf: board private structure
9397  **/
9398 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
9399 {
9400         unsigned long min_flush_time;
9401         int flush_wait_retry = 50;
9402         bool disable_atr = false;
9403         int fd_room;
9404         int reg;
9405
9406         if (!time_after(jiffies, pf->fd_flush_timestamp +
9407                                  (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
9408                 return;
9409
9410         /* If the flush is happening too quick and we have mostly SB rules we
9411          * should not re-enable ATR for some time.
9412          */
9413         min_flush_time = pf->fd_flush_timestamp +
9414                          (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
9415         fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
9416
9417         if (!(time_after(jiffies, min_flush_time)) &&
9418             (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
9419                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9420                         dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
9421                 disable_atr = true;
9422         }
9423
9424         pf->fd_flush_timestamp = jiffies;
9425         set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9426         /* flush all filters */
9427         wr32(&pf->hw, I40E_PFQF_CTL_1,
9428              I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
9429         i40e_flush(&pf->hw);
9430         pf->fd_flush_cnt++;
9431         pf->fd_add_err = 0;
9432         do {
9433                 /* Check FD flush status every 5-6msec */
9434                 usleep_range(5000, 6000);
9435                 reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
9436                 if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
9437                         break;
9438         } while (flush_wait_retry--);
9439         if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
9440                 dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
9441         } else {
9442                 /* replay sideband filters */
9443                 i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
9444                 if (!disable_atr && !pf->fd_tcp4_filter_cnt)
9445                         clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
9446                 clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
9447                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
9448                         dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
9449         }
9450 }
9451
9452 /**
9453  * i40e_get_current_atr_cnt - Get the count of total FD ATR filters programmed
9454  * @pf: board private structure
9455  **/
9456 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
9457 {
9458         return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
9459 }
9460
9461 /**
9462  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
9463  * @pf: board private structure
9464  **/
9465 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
9466 {
9467
9468         /* if interface is down do nothing */
9469         if (test_bit(__I40E_DOWN, pf->state))
9470                 return;
9471
9472         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
9473                 i40e_fdir_flush_and_replay(pf);
9474
9475         i40e_fdir_check_and_reenable(pf);
9476
9477 }
9478
9479 /**
9480  * i40e_vsi_link_event - notify VSI of a link event
9481  * @vsi: vsi to be notified
9482  * @link_up: link up or down
9483  **/
9484 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
9485 {
9486         if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
9487                 return;
9488
9489         switch (vsi->type) {
9490         case I40E_VSI_MAIN:
9491                 if (!vsi->netdev || !vsi->netdev_registered)
9492                         break;
9493
9494                 if (link_up) {
9495                         netif_carrier_on(vsi->netdev);
9496                         netif_tx_wake_all_queues(vsi->netdev);
9497                 } else {
9498                         netif_carrier_off(vsi->netdev);
9499                         netif_tx_stop_all_queues(vsi->netdev);
9500                 }
9501                 break;
9502
9503         case I40E_VSI_SRIOV:
9504         case I40E_VSI_VMDQ2:
9505         case I40E_VSI_CTRL:
9506         case I40E_VSI_IWARP:
9507         case I40E_VSI_MIRROR:
9508         default:
9509                 /* there is no notification for other VSIs */
9510                 break;
9511         }
9512 }
9513
9514 /**
9515  * i40e_veb_link_event - notify elements on the veb of a link event
9516  * @veb: veb to be notified
9517  * @link_up: link up or down
9518  **/
9519 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
9520 {
9521         struct i40e_pf *pf;
9522         int i;
9523
9524         if (!veb || !veb->pf)
9525                 return;
9526         pf = veb->pf;
9527
9528         /* depth first... */
9529         for (i = 0; i < I40E_MAX_VEB; i++)
9530                 if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9531                         i40e_veb_link_event(pf->veb[i], link_up);
9532
9533         /* ... now the local VSIs */
9534         for (i = 0; i < pf->num_alloc_vsi; i++)
9535                 if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9536                         i40e_vsi_link_event(pf->vsi[i], link_up);
9537 }
9538
9539 /**
9540  * i40e_link_event - Update netif_carrier status
9541  * @pf: board private structure
9542  **/
9543 static void i40e_link_event(struct i40e_pf *pf)
9544 {
9545         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9546         u8 new_link_speed, old_link_speed;
9547         i40e_status status;
9548         bool new_link, old_link;
9549 #ifdef CONFIG_I40E_DCB
9550         int err;
9551 #endif /* CONFIG_I40E_DCB */
9552
9553         /* set this to force the get_link_status call to refresh state */
9554         pf->hw.phy.get_link_info = true;
9555         old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9556         status = i40e_get_link_status(&pf->hw, &new_link);
9557
9558         /* On success, disable temp link polling */
9559         if (status == I40E_SUCCESS) {
9560                 clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9561         } else {
9562                 /* Enable link polling temporarily until i40e_get_link_status
9563                  * returns I40E_SUCCESS
9564                  */
9565                 set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9566                 dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9567                         status);
9568                 return;
9569         }
9570
9571         old_link_speed = pf->hw.phy.link_info_old.link_speed;
9572         new_link_speed = pf->hw.phy.link_info.link_speed;
9573
9574         if (new_link == old_link &&
9575             new_link_speed == old_link_speed &&
9576             (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9577              new_link == netif_carrier_ok(vsi->netdev)))
9578                 return;
9579
9580         i40e_print_link_message(vsi, new_link);
9581
9582         /* Notify the base of the switch tree connected to
9583          * the link.  Floating VEBs are not notified.
9584          */
9585         if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9586                 i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9587         else
9588                 i40e_vsi_link_event(vsi, new_link);
9589
9590         if (pf->vf)
9591                 i40e_vc_notify_link_state(pf);
9592
9593         if (pf->flags & I40E_FLAG_PTP)
9594                 i40e_ptp_set_increment(pf);
9595 #ifdef CONFIG_I40E_DCB
9596         if (new_link == old_link)
9597                 return;
9598         /* Not SW DCB so firmware will take care of default settings */
9599         if (pf->dcbx_cap & DCB_CAP_DCBX_LLD_MANAGED)
9600                 return;
9601
9602         /* We cover here only link down, as after link up in case of SW DCB
9603          * SW LLDP agent will take care of setting it up
9604          */
9605         if (!new_link) {
9606                 dev_dbg(&pf->pdev->dev, "Reconfig DCB to single TC as result of Link Down\n");
9607                 memset(&pf->tmp_cfg, 0, sizeof(pf->tmp_cfg));
9608                 err = i40e_dcb_sw_default_config(pf);
9609                 if (err) {
9610                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
9611                                        I40E_FLAG_DCB_ENABLED);
9612                 } else {
9613                         pf->dcbx_cap = DCB_CAP_DCBX_HOST |
9614                                        DCB_CAP_DCBX_VER_IEEE;
9615                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
9616                         pf->flags &= ~I40E_FLAG_DCB_ENABLED;
9617                 }
9618         }
9619 #endif /* CONFIG_I40E_DCB */
9620 }
9621
9622 /**
9623  * i40e_watchdog_subtask - periodic checks not using event driven response
9624  * @pf: board private structure
9625  **/
9626 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9627 {
9628         int i;
9629
9630         /* if interface is down do nothing */
9631         if (test_bit(__I40E_DOWN, pf->state) ||
9632             test_bit(__I40E_CONFIG_BUSY, pf->state))
9633                 return;
9634
9635         /* make sure we don't do these things too often */
9636         if (time_before(jiffies, (pf->service_timer_previous +
9637                                   pf->service_timer_period)))
9638                 return;
9639         pf->service_timer_previous = jiffies;
9640
9641         if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9642             test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9643                 i40e_link_event(pf);
9644
9645         /* Update the stats for active netdevs so the network stack
9646          * can look at updated numbers whenever it cares to
9647          */
9648         for (i = 0; i < pf->num_alloc_vsi; i++)
9649                 if (pf->vsi[i] && pf->vsi[i]->netdev)
9650                         i40e_update_stats(pf->vsi[i]);
9651
9652         if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9653                 /* Update the stats for the active switching components */
9654                 for (i = 0; i < I40E_MAX_VEB; i++)
9655                         if (pf->veb[i])
9656                                 i40e_update_veb_stats(pf->veb[i]);
9657         }
9658
9659         i40e_ptp_rx_hang(pf);
9660         i40e_ptp_tx_hang(pf);
9661 }
9662
9663 /**
9664  * i40e_reset_subtask - Set up for resetting the device and driver
9665  * @pf: board private structure
9666  **/
9667 static void i40e_reset_subtask(struct i40e_pf *pf)
9668 {
9669         u32 reset_flags = 0;
9670
9671         if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
9672                 reset_flags |= BIT(__I40E_REINIT_REQUESTED);
9673                 clear_bit(__I40E_REINIT_REQUESTED, pf->state);
9674         }
9675         if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
9676                 reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
9677                 clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9678         }
9679         if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
9680                 reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
9681                 clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
9682         }
9683         if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
9684                 reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
9685                 clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
9686         }
9687         if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
9688                 reset_flags |= BIT(__I40E_DOWN_REQUESTED);
9689                 clear_bit(__I40E_DOWN_REQUESTED, pf->state);
9690         }
9691
9692         /* If there's a recovery already waiting, it takes
9693          * precedence before starting a new reset sequence.
9694          */
9695         if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
9696                 i40e_prep_for_reset(pf);
9697                 i40e_reset(pf);
9698                 i40e_rebuild(pf, false, false);
9699         }
9700
9701         /* If we're already down or resetting, just bail */
9702         if (reset_flags &&
9703             !test_bit(__I40E_DOWN, pf->state) &&
9704             !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
9705                 i40e_do_reset(pf, reset_flags, false);
9706         }
9707 }
9708
9709 /**
9710  * i40e_handle_link_event - Handle link event
9711  * @pf: board private structure
9712  * @e: event info posted on ARQ
9713  **/
9714 static void i40e_handle_link_event(struct i40e_pf *pf,
9715                                    struct i40e_arq_event_info *e)
9716 {
9717         struct i40e_aqc_get_link_status *status =
9718                 (struct i40e_aqc_get_link_status *)&e->desc.params.raw;
9719
9720         /* Do a new status request to re-enable LSE reporting
9721          * and load new status information into the hw struct
9722          * This completely ignores any state information
9723          * in the ARQ event info, instead choosing to always
9724          * issue the AQ update link status command.
9725          */
9726         i40e_link_event(pf);
9727
9728         /* Check if module meets thermal requirements */
9729         if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
9730                 dev_err(&pf->pdev->dev,
9731                         "Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
9732                 dev_err(&pf->pdev->dev,
9733                         "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9734         } else {
9735                 /* check for unqualified module, if link is down, suppress
9736                  * the message if link was forced to be down.
9737                  */
9738                 if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
9739                     (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
9740                     (!(status->link_info & I40E_AQ_LINK_UP)) &&
9741                     (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
9742                         dev_err(&pf->pdev->dev,
9743                                 "Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
9744                         dev_err(&pf->pdev->dev,
9745                                 "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9746                 }
9747         }
9748 }
9749
9750 /**
9751  * i40e_clean_adminq_subtask - Clean the AdminQ rings
9752  * @pf: board private structure
9753  **/
9754 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
9755 {
9756         struct i40e_arq_event_info event;
9757         struct i40e_hw *hw = &pf->hw;
9758         u16 pending, i = 0;
9759         i40e_status ret;
9760         u16 opcode;
9761         u32 oldval;
9762         u32 val;
9763
9764         /* Do not run clean AQ when PF reset fails */
9765         if (test_bit(__I40E_RESET_FAILED, pf->state))
9766                 return;
9767
9768         /* check for error indications */
9769         val = rd32(&pf->hw, pf->hw.aq.arq.len);
9770         oldval = val;
9771         if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
9772                 if (hw->debug_mask & I40E_DEBUG_AQ)
9773                         dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
9774                 val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
9775         }
9776         if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
9777                 if (hw->debug_mask & I40E_DEBUG_AQ)
9778                         dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
9779                 val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
9780                 pf->arq_overflows++;
9781         }
9782         if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
9783                 if (hw->debug_mask & I40E_DEBUG_AQ)
9784                         dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
9785                 val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
9786         }
9787         if (oldval != val)
9788                 wr32(&pf->hw, pf->hw.aq.arq.len, val);
9789
9790         val = rd32(&pf->hw, pf->hw.aq.asq.len);
9791         oldval = val;
9792         if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
9793                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9794                         dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
9795                 val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
9796         }
9797         if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
9798                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9799                         dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
9800                 val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
9801         }
9802         if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
9803                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9804                         dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
9805                 val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
9806         }
9807         if (oldval != val)
9808                 wr32(&pf->hw, pf->hw.aq.asq.len, val);
9809
9810         event.buf_len = I40E_MAX_AQ_BUF_SIZE;
9811         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
9812         if (!event.msg_buf)
9813                 return;
9814
9815         do {
9816                 ret = i40e_clean_arq_element(hw, &event, &pending);
9817                 if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
9818                         break;
9819                 else if (ret) {
9820                         dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
9821                         break;
9822                 }
9823
9824                 opcode = le16_to_cpu(event.desc.opcode);
9825                 switch (opcode) {
9826
9827                 case i40e_aqc_opc_get_link_status:
9828                         rtnl_lock();
9829                         i40e_handle_link_event(pf, &event);
9830                         rtnl_unlock();
9831                         break;
9832                 case i40e_aqc_opc_send_msg_to_pf:
9833                         ret = i40e_vc_process_vf_msg(pf,
9834                                         le16_to_cpu(event.desc.retval),
9835                                         le32_to_cpu(event.desc.cookie_high),
9836                                         le32_to_cpu(event.desc.cookie_low),
9837                                         event.msg_buf,
9838                                         event.msg_len);
9839                         break;
9840                 case i40e_aqc_opc_lldp_update_mib:
9841                         dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
9842 #ifdef CONFIG_I40E_DCB
9843                         rtnl_lock();
9844                         i40e_handle_lldp_event(pf, &event);
9845                         rtnl_unlock();
9846 #endif /* CONFIG_I40E_DCB */
9847                         break;
9848                 case i40e_aqc_opc_event_lan_overflow:
9849                         dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
9850                         i40e_handle_lan_overflow_event(pf, &event);
9851                         break;
9852                 case i40e_aqc_opc_send_msg_to_peer:
9853                         dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
9854                         break;
9855                 case i40e_aqc_opc_nvm_erase:
9856                 case i40e_aqc_opc_nvm_update:
9857                 case i40e_aqc_opc_oem_post_update:
9858                         i40e_debug(&pf->hw, I40E_DEBUG_NVM,
9859                                    "ARQ NVM operation 0x%04x completed\n",
9860                                    opcode);
9861                         break;
9862                 default:
9863                         dev_info(&pf->pdev->dev,
9864                                  "ARQ: Unknown event 0x%04x ignored\n",
9865                                  opcode);
9866                         break;
9867                 }
9868         } while (i++ < pf->adminq_work_limit);
9869
9870         if (i < pf->adminq_work_limit)
9871                 clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
9872
9873         /* re-enable Admin queue interrupt cause */
9874         val = rd32(hw, I40E_PFINT_ICR0_ENA);
9875         val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
9876         wr32(hw, I40E_PFINT_ICR0_ENA, val);
9877         i40e_flush(hw);
9878
9879         kfree(event.msg_buf);
9880 }
9881
9882 /**
9883  * i40e_verify_eeprom - make sure eeprom is good to use
9884  * @pf: board private structure
9885  **/
9886 static void i40e_verify_eeprom(struct i40e_pf *pf)
9887 {
9888         int err;
9889
9890         err = i40e_diag_eeprom_test(&pf->hw);
9891         if (err) {
9892                 /* retry in case of garbage read */
9893                 err = i40e_diag_eeprom_test(&pf->hw);
9894                 if (err) {
9895                         dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
9896                                  err);
9897                         set_bit(__I40E_BAD_EEPROM, pf->state);
9898                 }
9899         }
9900
9901         if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
9902                 dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
9903                 clear_bit(__I40E_BAD_EEPROM, pf->state);
9904         }
9905 }
9906
9907 /**
9908  * i40e_enable_pf_switch_lb
9909  * @pf: pointer to the PF structure
9910  *
9911  * enable switch loop back or die - no point in a return value
9912  **/
9913 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
9914 {
9915         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9916         struct i40e_vsi_context ctxt;
9917         int ret;
9918
9919         ctxt.seid = pf->main_vsi_seid;
9920         ctxt.pf_num = pf->hw.pf_id;
9921         ctxt.vf_num = 0;
9922         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
9923         if (ret) {
9924                 dev_info(&pf->pdev->dev,
9925                          "couldn't get PF vsi config, err %s aq_err %s\n",
9926                          i40e_stat_str(&pf->hw, ret),
9927                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9928                 return;
9929         }
9930         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9931         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9932         ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9933
9934         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
9935         if (ret) {
9936                 dev_info(&pf->pdev->dev,
9937                          "update vsi switch failed, err %s aq_err %s\n",
9938                          i40e_stat_str(&pf->hw, ret),
9939                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9940         }
9941 }
9942
9943 /**
9944  * i40e_disable_pf_switch_lb
9945  * @pf: pointer to the PF structure
9946  *
9947  * disable switch loop back or die - no point in a return value
9948  **/
9949 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
9950 {
9951         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9952         struct i40e_vsi_context ctxt;
9953         int ret;
9954
9955         ctxt.seid = pf->main_vsi_seid;
9956         ctxt.pf_num = pf->hw.pf_id;
9957         ctxt.vf_num = 0;
9958         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
9959         if (ret) {
9960                 dev_info(&pf->pdev->dev,
9961                          "couldn't get PF vsi config, err %s aq_err %s\n",
9962                          i40e_stat_str(&pf->hw, ret),
9963                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9964                 return;
9965         }
9966         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9967         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9968         ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9969
9970         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
9971         if (ret) {
9972                 dev_info(&pf->pdev->dev,
9973                          "update vsi switch failed, err %s aq_err %s\n",
9974                          i40e_stat_str(&pf->hw, ret),
9975                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9976         }
9977 }
9978
9979 /**
9980  * i40e_config_bridge_mode - Configure the HW bridge mode
9981  * @veb: pointer to the bridge instance
9982  *
9983  * Configure the loop back mode for the LAN VSI that is downlink to the
9984  * specified HW bridge instance. It is expected this function is called
9985  * when a new HW bridge is instantiated.
9986  **/
9987 static void i40e_config_bridge_mode(struct i40e_veb *veb)
9988 {
9989         struct i40e_pf *pf = veb->pf;
9990
9991         if (pf->hw.debug_mask & I40E_DEBUG_LAN)
9992                 dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
9993                          veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
9994         if (veb->bridge_mode & BRIDGE_MODE_VEPA)
9995                 i40e_disable_pf_switch_lb(pf);
9996         else
9997                 i40e_enable_pf_switch_lb(pf);
9998 }
9999
10000 /**
10001  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
10002  * @veb: pointer to the VEB instance
10003  *
10004  * This is a recursive function that first builds the attached VSIs then
10005  * recurses in to build the next layer of VEB.  We track the connections
10006  * through our own index numbers because the seid's from the HW could
10007  * change across the reset.
10008  **/
10009 static int i40e_reconstitute_veb(struct i40e_veb *veb)
10010 {
10011         struct i40e_vsi *ctl_vsi = NULL;
10012         struct i40e_pf *pf = veb->pf;
10013         int v, veb_idx;
10014         int ret;
10015
10016         /* build VSI that owns this VEB, temporarily attached to base VEB */
10017         for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
10018                 if (pf->vsi[v] &&
10019                     pf->vsi[v]->veb_idx == veb->idx &&
10020                     pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
10021                         ctl_vsi = pf->vsi[v];
10022                         break;
10023                 }
10024         }
10025         if (!ctl_vsi) {
10026                 dev_info(&pf->pdev->dev,
10027                          "missing owner VSI for veb_idx %d\n", veb->idx);
10028                 ret = -ENOENT;
10029                 goto end_reconstitute;
10030         }
10031         if (ctl_vsi != pf->vsi[pf->lan_vsi])
10032                 ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10033         ret = i40e_add_vsi(ctl_vsi);
10034         if (ret) {
10035                 dev_info(&pf->pdev->dev,
10036                          "rebuild of veb_idx %d owner VSI failed: %d\n",
10037                          veb->idx, ret);
10038                 goto end_reconstitute;
10039         }
10040         i40e_vsi_reset_stats(ctl_vsi);
10041
10042         /* create the VEB in the switch and move the VSI onto the VEB */
10043         ret = i40e_add_veb(veb, ctl_vsi);
10044         if (ret)
10045                 goto end_reconstitute;
10046
10047         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
10048                 veb->bridge_mode = BRIDGE_MODE_VEB;
10049         else
10050                 veb->bridge_mode = BRIDGE_MODE_VEPA;
10051         i40e_config_bridge_mode(veb);
10052
10053         /* create the remaining VSIs attached to this VEB */
10054         for (v = 0; v < pf->num_alloc_vsi; v++) {
10055                 if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
10056                         continue;
10057
10058                 if (pf->vsi[v]->veb_idx == veb->idx) {
10059                         struct i40e_vsi *vsi = pf->vsi[v];
10060
10061                         vsi->uplink_seid = veb->seid;
10062                         ret = i40e_add_vsi(vsi);
10063                         if (ret) {
10064                                 dev_info(&pf->pdev->dev,
10065                                          "rebuild of vsi_idx %d failed: %d\n",
10066                                          v, ret);
10067                                 goto end_reconstitute;
10068                         }
10069                         i40e_vsi_reset_stats(vsi);
10070                 }
10071         }
10072
10073         /* create any VEBs attached to this VEB - RECURSION */
10074         for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10075                 if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
10076                         pf->veb[veb_idx]->uplink_seid = veb->seid;
10077                         ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
10078                         if (ret)
10079                                 break;
10080                 }
10081         }
10082
10083 end_reconstitute:
10084         return ret;
10085 }
10086
10087 /**
10088  * i40e_get_capabilities - get info about the HW
10089  * @pf: the PF struct
10090  * @list_type: AQ capability to be queried
10091  **/
10092 static int i40e_get_capabilities(struct i40e_pf *pf,
10093                                  enum i40e_admin_queue_opc list_type)
10094 {
10095         struct i40e_aqc_list_capabilities_element_resp *cap_buf;
10096         u16 data_size;
10097         int buf_len;
10098         int err;
10099
10100         buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
10101         do {
10102                 cap_buf = kzalloc(buf_len, GFP_KERNEL);
10103                 if (!cap_buf)
10104                         return -ENOMEM;
10105
10106                 /* this loads the data into the hw struct for us */
10107                 err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
10108                                                     &data_size, list_type,
10109                                                     NULL);
10110                 /* data loaded, buffer no longer needed */
10111                 kfree(cap_buf);
10112
10113                 if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
10114                         /* retry with a larger buffer */
10115                         buf_len = data_size;
10116                 } else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
10117                         dev_info(&pf->pdev->dev,
10118                                  "capability discovery failed, err %s aq_err %s\n",
10119                                  i40e_stat_str(&pf->hw, err),
10120                                  i40e_aq_str(&pf->hw,
10121                                              pf->hw.aq.asq_last_status));
10122                         return -ENODEV;
10123                 }
10124         } while (err);
10125
10126         if (pf->hw.debug_mask & I40E_DEBUG_USER) {
10127                 if (list_type == i40e_aqc_opc_list_func_capabilities) {
10128                         dev_info(&pf->pdev->dev,
10129                                  "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",
10130                                  pf->hw.pf_id, pf->hw.func_caps.num_vfs,
10131                                  pf->hw.func_caps.num_msix_vectors,
10132                                  pf->hw.func_caps.num_msix_vectors_vf,
10133                                  pf->hw.func_caps.fd_filters_guaranteed,
10134                                  pf->hw.func_caps.fd_filters_best_effort,
10135                                  pf->hw.func_caps.num_tx_qp,
10136                                  pf->hw.func_caps.num_vsis);
10137                 } else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
10138                         dev_info(&pf->pdev->dev,
10139                                  "switch_mode=0x%04x, function_valid=0x%08x\n",
10140                                  pf->hw.dev_caps.switch_mode,
10141                                  pf->hw.dev_caps.valid_functions);
10142                         dev_info(&pf->pdev->dev,
10143                                  "SR-IOV=%d, num_vfs for all function=%u\n",
10144                                  pf->hw.dev_caps.sr_iov_1_1,
10145                                  pf->hw.dev_caps.num_vfs);
10146                         dev_info(&pf->pdev->dev,
10147                                  "num_vsis=%u, num_rx:%u, num_tx=%u\n",
10148                                  pf->hw.dev_caps.num_vsis,
10149                                  pf->hw.dev_caps.num_rx_qp,
10150                                  pf->hw.dev_caps.num_tx_qp);
10151                 }
10152         }
10153         if (list_type == i40e_aqc_opc_list_func_capabilities) {
10154 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
10155                        + pf->hw.func_caps.num_vfs)
10156                 if (pf->hw.revision_id == 0 &&
10157                     pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
10158                         dev_info(&pf->pdev->dev,
10159                                  "got num_vsis %d, setting num_vsis to %d\n",
10160                                  pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
10161                         pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
10162                 }
10163         }
10164         return 0;
10165 }
10166
10167 static int i40e_vsi_clear(struct i40e_vsi *vsi);
10168
10169 /**
10170  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
10171  * @pf: board private structure
10172  **/
10173 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
10174 {
10175         struct i40e_vsi *vsi;
10176
10177         /* quick workaround for an NVM issue that leaves a critical register
10178          * uninitialized
10179          */
10180         if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
10181                 static const u32 hkey[] = {
10182                         0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
10183                         0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
10184                         0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
10185                         0x95b3a76d};
10186                 int i;
10187
10188                 for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
10189                         wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
10190         }
10191
10192         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
10193                 return;
10194
10195         /* find existing VSI and see if it needs configuring */
10196         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10197
10198         /* create a new VSI if none exists */
10199         if (!vsi) {
10200                 vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
10201                                      pf->vsi[pf->lan_vsi]->seid, 0);
10202                 if (!vsi) {
10203                         dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
10204                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
10205                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
10206                         return;
10207                 }
10208         }
10209
10210         i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
10211 }
10212
10213 /**
10214  * i40e_fdir_teardown - release the Flow Director resources
10215  * @pf: board private structure
10216  **/
10217 static void i40e_fdir_teardown(struct i40e_pf *pf)
10218 {
10219         struct i40e_vsi *vsi;
10220
10221         i40e_fdir_filter_exit(pf);
10222         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
10223         if (vsi)
10224                 i40e_vsi_release(vsi);
10225 }
10226
10227 /**
10228  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
10229  * @vsi: PF main vsi
10230  * @seid: seid of main or channel VSIs
10231  *
10232  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
10233  * existed before reset
10234  **/
10235 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
10236 {
10237         struct i40e_cloud_filter *cfilter;
10238         struct i40e_pf *pf = vsi->back;
10239         struct hlist_node *node;
10240         i40e_status ret;
10241
10242         /* Add cloud filters back if they exist */
10243         hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
10244                                   cloud_node) {
10245                 if (cfilter->seid != seid)
10246                         continue;
10247
10248                 if (cfilter->dst_port)
10249                         ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
10250                                                                 true);
10251                 else
10252                         ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
10253
10254                 if (ret) {
10255                         dev_dbg(&pf->pdev->dev,
10256                                 "Failed to rebuild cloud filter, err %s aq_err %s\n",
10257                                 i40e_stat_str(&pf->hw, ret),
10258                                 i40e_aq_str(&pf->hw,
10259                                             pf->hw.aq.asq_last_status));
10260                         return ret;
10261                 }
10262         }
10263         return 0;
10264 }
10265
10266 /**
10267  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
10268  * @vsi: PF main vsi
10269  *
10270  * Rebuilds channel VSIs if they existed before reset
10271  **/
10272 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
10273 {
10274         struct i40e_channel *ch, *ch_tmp;
10275         i40e_status ret;
10276
10277         if (list_empty(&vsi->ch_list))
10278                 return 0;
10279
10280         list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
10281                 if (!ch->initialized)
10282                         break;
10283                 /* Proceed with creation of channel (VMDq2) VSI */
10284                 ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
10285                 if (ret) {
10286                         dev_info(&vsi->back->pdev->dev,
10287                                  "failed to rebuild channels using uplink_seid %u\n",
10288                                  vsi->uplink_seid);
10289                         return ret;
10290                 }
10291                 /* Reconfigure TX queues using QTX_CTL register */
10292                 ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
10293                 if (ret) {
10294                         dev_info(&vsi->back->pdev->dev,
10295                                  "failed to configure TX rings for channel %u\n",
10296                                  ch->seid);
10297                         return ret;
10298                 }
10299                 /* update 'next_base_queue' */
10300                 vsi->next_base_queue = vsi->next_base_queue +
10301                                                         ch->num_queue_pairs;
10302                 if (ch->max_tx_rate) {
10303                         u64 credits = ch->max_tx_rate;
10304
10305                         if (i40e_set_bw_limit(vsi, ch->seid,
10306                                               ch->max_tx_rate))
10307                                 return -EINVAL;
10308
10309                         do_div(credits, I40E_BW_CREDIT_DIVISOR);
10310                         dev_dbg(&vsi->back->pdev->dev,
10311                                 "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10312                                 ch->max_tx_rate,
10313                                 credits,
10314                                 ch->seid);
10315                 }
10316                 ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
10317                 if (ret) {
10318                         dev_dbg(&vsi->back->pdev->dev,
10319                                 "Failed to rebuild cloud filters for channel VSI %u\n",
10320                                 ch->seid);
10321                         return ret;
10322                 }
10323         }
10324         return 0;
10325 }
10326
10327 /**
10328  * i40e_prep_for_reset - prep for the core to reset
10329  * @pf: board private structure
10330  *
10331  * Close up the VFs and other things in prep for PF Reset.
10332   **/
10333 static void i40e_prep_for_reset(struct i40e_pf *pf)
10334 {
10335         struct i40e_hw *hw = &pf->hw;
10336         i40e_status ret = 0;
10337         u32 v;
10338
10339         clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
10340         if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
10341                 return;
10342         if (i40e_check_asq_alive(&pf->hw))
10343                 i40e_vc_notify_reset(pf);
10344
10345         dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
10346
10347         /* quiesce the VSIs and their queues that are not already DOWN */
10348         i40e_pf_quiesce_all_vsi(pf);
10349
10350         for (v = 0; v < pf->num_alloc_vsi; v++) {
10351                 if (pf->vsi[v])
10352                         pf->vsi[v]->seid = 0;
10353         }
10354
10355         i40e_shutdown_adminq(&pf->hw);
10356
10357         /* call shutdown HMC */
10358         if (hw->hmc.hmc_obj) {
10359                 ret = i40e_shutdown_lan_hmc(hw);
10360                 if (ret)
10361                         dev_warn(&pf->pdev->dev,
10362                                  "shutdown_lan_hmc failed: %d\n", ret);
10363         }
10364
10365         /* Save the current PTP time so that we can restore the time after the
10366          * reset completes.
10367          */
10368         i40e_ptp_save_hw_time(pf);
10369 }
10370
10371 /**
10372  * i40e_send_version - update firmware with driver version
10373  * @pf: PF struct
10374  */
10375 static void i40e_send_version(struct i40e_pf *pf)
10376 {
10377         struct i40e_driver_version dv;
10378
10379         dv.major_version = 0xff;
10380         dv.minor_version = 0xff;
10381         dv.build_version = 0xff;
10382         dv.subbuild_version = 0;
10383         strlcpy(dv.driver_string, UTS_RELEASE, sizeof(dv.driver_string));
10384         i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
10385 }
10386
10387 /**
10388  * i40e_get_oem_version - get OEM specific version information
10389  * @hw: pointer to the hardware structure
10390  **/
10391 static void i40e_get_oem_version(struct i40e_hw *hw)
10392 {
10393         u16 block_offset = 0xffff;
10394         u16 block_length = 0;
10395         u16 capabilities = 0;
10396         u16 gen_snap = 0;
10397         u16 release = 0;
10398
10399 #define I40E_SR_NVM_OEM_VERSION_PTR             0x1B
10400 #define I40E_NVM_OEM_LENGTH_OFFSET              0x00
10401 #define I40E_NVM_OEM_CAPABILITIES_OFFSET        0x01
10402 #define I40E_NVM_OEM_GEN_OFFSET                 0x02
10403 #define I40E_NVM_OEM_RELEASE_OFFSET             0x03
10404 #define I40E_NVM_OEM_CAPABILITIES_MASK          0x000F
10405 #define I40E_NVM_OEM_LENGTH                     3
10406
10407         /* Check if pointer to OEM version block is valid. */
10408         i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
10409         if (block_offset == 0xffff)
10410                 return;
10411
10412         /* Check if OEM version block has correct length. */
10413         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
10414                            &block_length);
10415         if (block_length < I40E_NVM_OEM_LENGTH)
10416                 return;
10417
10418         /* Check if OEM version format is as expected. */
10419         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
10420                            &capabilities);
10421         if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
10422                 return;
10423
10424         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
10425                            &gen_snap);
10426         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
10427                            &release);
10428         hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
10429         hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
10430 }
10431
10432 /**
10433  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
10434  * @pf: board private structure
10435  **/
10436 static int i40e_reset(struct i40e_pf *pf)
10437 {
10438         struct i40e_hw *hw = &pf->hw;
10439         i40e_status ret;
10440
10441         ret = i40e_pf_reset(hw);
10442         if (ret) {
10443                 dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
10444                 set_bit(__I40E_RESET_FAILED, pf->state);
10445                 clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10446         } else {
10447                 pf->pfr_count++;
10448         }
10449         return ret;
10450 }
10451
10452 /**
10453  * i40e_rebuild - rebuild using a saved config
10454  * @pf: board private structure
10455  * @reinit: if the Main VSI needs to re-initialized.
10456  * @lock_acquired: indicates whether or not the lock has been acquired
10457  * before this function was called.
10458  **/
10459 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
10460 {
10461         int old_recovery_mode_bit = test_bit(__I40E_RECOVERY_MODE, pf->state);
10462         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
10463         struct i40e_hw *hw = &pf->hw;
10464         i40e_status ret;
10465         u32 val;
10466         int v;
10467
10468         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10469             i40e_check_recovery_mode(pf)) {
10470                 i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
10471         }
10472
10473         if (test_bit(__I40E_DOWN, pf->state) &&
10474             !test_bit(__I40E_RECOVERY_MODE, pf->state) &&
10475             !old_recovery_mode_bit)
10476                 goto clear_recovery;
10477         dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
10478
10479         /* rebuild the basics for the AdminQ, HMC, and initial HW switch */
10480         ret = i40e_init_adminq(&pf->hw);
10481         if (ret) {
10482                 dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
10483                          i40e_stat_str(&pf->hw, ret),
10484                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10485                 goto clear_recovery;
10486         }
10487         i40e_get_oem_version(&pf->hw);
10488
10489         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
10490             ((hw->aq.fw_maj_ver == 4 && hw->aq.fw_min_ver <= 33) ||
10491              hw->aq.fw_maj_ver < 4) && hw->mac.type == I40E_MAC_XL710) {
10492                 /* The following delay is necessary for 4.33 firmware and older
10493                  * to recover after EMP reset. 200 ms should suffice but we
10494                  * put here 300 ms to be sure that FW is ready to operate
10495                  * after reset.
10496                  */
10497                 mdelay(300);
10498         }
10499
10500         /* re-verify the eeprom if we just had an EMP reset */
10501         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
10502                 i40e_verify_eeprom(pf);
10503
10504         /* if we are going out of or into recovery mode we have to act
10505          * accordingly with regard to resources initialization
10506          * and deinitialization
10507          */
10508         if (test_bit(__I40E_RECOVERY_MODE, pf->state) ||
10509             old_recovery_mode_bit) {
10510                 if (i40e_get_capabilities(pf,
10511                                           i40e_aqc_opc_list_func_capabilities))
10512                         goto end_unlock;
10513
10514                 if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10515                         /* we're staying in recovery mode so we'll reinitialize
10516                          * misc vector here
10517                          */
10518                         if (i40e_setup_misc_vector_for_recovery_mode(pf))
10519                                 goto end_unlock;
10520                 } else {
10521                         if (!lock_acquired)
10522                                 rtnl_lock();
10523                         /* we're going out of recovery mode so we'll free
10524                          * the IRQ allocated specifically for recovery mode
10525                          * and restore the interrupt scheme
10526                          */
10527                         free_irq(pf->pdev->irq, pf);
10528                         i40e_clear_interrupt_scheme(pf);
10529                         if (i40e_restore_interrupt_scheme(pf))
10530                                 goto end_unlock;
10531                 }
10532
10533                 /* tell the firmware that we're starting */
10534                 i40e_send_version(pf);
10535
10536                 /* bail out in case recovery mode was detected, as there is
10537                  * no need for further configuration.
10538                  */
10539                 goto end_unlock;
10540         }
10541
10542         i40e_clear_pxe_mode(hw);
10543         ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10544         if (ret)
10545                 goto end_core_reset;
10546
10547         ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10548                                 hw->func_caps.num_rx_qp, 0, 0);
10549         if (ret) {
10550                 dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10551                 goto end_core_reset;
10552         }
10553         ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10554         if (ret) {
10555                 dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10556                 goto end_core_reset;
10557         }
10558
10559 #ifdef CONFIG_I40E_DCB
10560         /* Enable FW to write a default DCB config on link-up
10561          * unless I40E_FLAG_TC_MQPRIO was enabled or DCB
10562          * is not supported with new link speed
10563          */
10564         if (pf->flags & I40E_FLAG_TC_MQPRIO) {
10565                 i40e_aq_set_dcb_parameters(hw, false, NULL);
10566         } else {
10567                 if (I40E_IS_X710TL_DEVICE(hw->device_id) &&
10568                     (hw->phy.link_info.link_speed &
10569                      (I40E_LINK_SPEED_2_5GB | I40E_LINK_SPEED_5GB))) {
10570                         i40e_aq_set_dcb_parameters(hw, false, NULL);
10571                         dev_warn(&pf->pdev->dev,
10572                                  "DCB is not supported for X710-T*L 2.5/5G speeds\n");
10573                         pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10574                 } else {
10575                         i40e_aq_set_dcb_parameters(hw, true, NULL);
10576                         ret = i40e_init_pf_dcb(pf);
10577                         if (ret) {
10578                                 dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n",
10579                                          ret);
10580                                 pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10581                                 /* Continue without DCB enabled */
10582                         }
10583                 }
10584         }
10585
10586 #endif /* CONFIG_I40E_DCB */
10587         if (!lock_acquired)
10588                 rtnl_lock();
10589         ret = i40e_setup_pf_switch(pf, reinit, true);
10590         if (ret)
10591                 goto end_unlock;
10592
10593         /* The driver only wants link up/down and module qualification
10594          * reports from firmware.  Note the negative logic.
10595          */
10596         ret = i40e_aq_set_phy_int_mask(&pf->hw,
10597                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
10598                                          I40E_AQ_EVENT_MEDIA_NA |
10599                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10600         if (ret)
10601                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
10602                          i40e_stat_str(&pf->hw, ret),
10603                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10604
10605         /* Rebuild the VSIs and VEBs that existed before reset.
10606          * They are still in our local switch element arrays, so only
10607          * need to rebuild the switch model in the HW.
10608          *
10609          * If there were VEBs but the reconstitution failed, we'll try
10610          * to recover minimal use by getting the basic PF VSI working.
10611          */
10612         if (vsi->uplink_seid != pf->mac_seid) {
10613                 dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10614                 /* find the one VEB connected to the MAC, and find orphans */
10615                 for (v = 0; v < I40E_MAX_VEB; v++) {
10616                         if (!pf->veb[v])
10617                                 continue;
10618
10619                         if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10620                             pf->veb[v]->uplink_seid == 0) {
10621                                 ret = i40e_reconstitute_veb(pf->veb[v]);
10622
10623                                 if (!ret)
10624                                         continue;
10625
10626                                 /* If Main VEB failed, we're in deep doodoo,
10627                                  * so give up rebuilding the switch and set up
10628                                  * for minimal rebuild of PF VSI.
10629                                  * If orphan failed, we'll report the error
10630                                  * but try to keep going.
10631                                  */
10632                                 if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10633                                         dev_info(&pf->pdev->dev,
10634                                                  "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10635                                                  ret);
10636                                         vsi->uplink_seid = pf->mac_seid;
10637                                         break;
10638                                 } else if (pf->veb[v]->uplink_seid == 0) {
10639                                         dev_info(&pf->pdev->dev,
10640                                                  "rebuild of orphan VEB failed: %d\n",
10641                                                  ret);
10642                                 }
10643                         }
10644                 }
10645         }
10646
10647         if (vsi->uplink_seid == pf->mac_seid) {
10648                 dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
10649                 /* no VEB, so rebuild only the Main VSI */
10650                 ret = i40e_add_vsi(vsi);
10651                 if (ret) {
10652                         dev_info(&pf->pdev->dev,
10653                                  "rebuild of Main VSI failed: %d\n", ret);
10654                         goto end_unlock;
10655                 }
10656         }
10657
10658         if (vsi->mqprio_qopt.max_rate[0]) {
10659                 u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
10660                 u64 credits = 0;
10661
10662                 do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
10663                 ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
10664                 if (ret)
10665                         goto end_unlock;
10666
10667                 credits = max_tx_rate;
10668                 do_div(credits, I40E_BW_CREDIT_DIVISOR);
10669                 dev_dbg(&vsi->back->pdev->dev,
10670                         "Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10671                         max_tx_rate,
10672                         credits,
10673                         vsi->seid);
10674         }
10675
10676         ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
10677         if (ret)
10678                 goto end_unlock;
10679
10680         /* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
10681          * for this main VSI if they exist
10682          */
10683         ret = i40e_rebuild_channels(vsi);
10684         if (ret)
10685                 goto end_unlock;
10686
10687         /* Reconfigure hardware for allowing smaller MSS in the case
10688          * of TSO, so that we avoid the MDD being fired and causing
10689          * a reset in the case of small MSS+TSO.
10690          */
10691 #define I40E_REG_MSS          0x000E64DC
10692 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
10693 #define I40E_64BYTE_MSS       0x400000
10694         val = rd32(hw, I40E_REG_MSS);
10695         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
10696                 val &= ~I40E_REG_MSS_MIN_MASK;
10697                 val |= I40E_64BYTE_MSS;
10698                 wr32(hw, I40E_REG_MSS, val);
10699         }
10700
10701         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
10702                 msleep(75);
10703                 ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
10704                 if (ret)
10705                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
10706                                  i40e_stat_str(&pf->hw, ret),
10707                                  i40e_aq_str(&pf->hw,
10708                                              pf->hw.aq.asq_last_status));
10709         }
10710         /* reinit the misc interrupt */
10711         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
10712                 ret = i40e_setup_misc_vector(pf);
10713
10714         /* Add a filter to drop all Flow control frames from any VSI from being
10715          * transmitted. By doing so we stop a malicious VF from sending out
10716          * PAUSE or PFC frames and potentially controlling traffic for other
10717          * PF/VF VSIs.
10718          * The FW can still send Flow control frames if enabled.
10719          */
10720         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
10721                                                        pf->main_vsi_seid);
10722
10723         /* restart the VSIs that were rebuilt and running before the reset */
10724         i40e_pf_unquiesce_all_vsi(pf);
10725
10726         /* Release the RTNL lock before we start resetting VFs */
10727         if (!lock_acquired)
10728                 rtnl_unlock();
10729
10730         /* Restore promiscuous settings */
10731         ret = i40e_set_promiscuous(pf, pf->cur_promisc);
10732         if (ret)
10733                 dev_warn(&pf->pdev->dev,
10734                          "Failed to restore promiscuous setting: %s, err %s aq_err %s\n",
10735                          pf->cur_promisc ? "on" : "off",
10736                          i40e_stat_str(&pf->hw, ret),
10737                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10738
10739         i40e_reset_all_vfs(pf, true);
10740
10741         /* tell the firmware that we're starting */
10742         i40e_send_version(pf);
10743
10744         /* We've already released the lock, so don't do it again */
10745         goto end_core_reset;
10746
10747 end_unlock:
10748         if (!lock_acquired)
10749                 rtnl_unlock();
10750 end_core_reset:
10751         clear_bit(__I40E_RESET_FAILED, pf->state);
10752 clear_recovery:
10753         clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10754         clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
10755 }
10756
10757 /**
10758  * i40e_reset_and_rebuild - reset and rebuild using a saved config
10759  * @pf: board private structure
10760  * @reinit: if the Main VSI needs to re-initialized.
10761  * @lock_acquired: indicates whether or not the lock has been acquired
10762  * before this function was called.
10763  **/
10764 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
10765                                    bool lock_acquired)
10766 {
10767         int ret;
10768         /* Now we wait for GRST to settle out.
10769          * We don't have to delete the VEBs or VSIs from the hw switch
10770          * because the reset will make them disappear.
10771          */
10772         ret = i40e_reset(pf);
10773         if (!ret)
10774                 i40e_rebuild(pf, reinit, lock_acquired);
10775 }
10776
10777 /**
10778  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
10779  * @pf: board private structure
10780  *
10781  * Close up the VFs and other things in prep for a Core Reset,
10782  * then get ready to rebuild the world.
10783  * @lock_acquired: indicates whether or not the lock has been acquired
10784  * before this function was called.
10785  **/
10786 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
10787 {
10788         i40e_prep_for_reset(pf);
10789         i40e_reset_and_rebuild(pf, false, lock_acquired);
10790 }
10791
10792 /**
10793  * i40e_handle_mdd_event
10794  * @pf: pointer to the PF structure
10795  *
10796  * Called from the MDD irq handler to identify possibly malicious vfs
10797  **/
10798 static void i40e_handle_mdd_event(struct i40e_pf *pf)
10799 {
10800         struct i40e_hw *hw = &pf->hw;
10801         bool mdd_detected = false;
10802         struct i40e_vf *vf;
10803         u32 reg;
10804         int i;
10805
10806         if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
10807                 return;
10808
10809         /* find what triggered the MDD event */
10810         reg = rd32(hw, I40E_GL_MDET_TX);
10811         if (reg & I40E_GL_MDET_TX_VALID_MASK) {
10812                 u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
10813                                 I40E_GL_MDET_TX_PF_NUM_SHIFT;
10814                 u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
10815                                 I40E_GL_MDET_TX_VF_NUM_SHIFT;
10816                 u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
10817                                 I40E_GL_MDET_TX_EVENT_SHIFT;
10818                 u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
10819                                 I40E_GL_MDET_TX_QUEUE_SHIFT) -
10820                                 pf->hw.func_caps.base_queue;
10821                 if (netif_msg_tx_err(pf))
10822                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
10823                                  event, queue, pf_num, vf_num);
10824                 wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
10825                 mdd_detected = true;
10826         }
10827         reg = rd32(hw, I40E_GL_MDET_RX);
10828         if (reg & I40E_GL_MDET_RX_VALID_MASK) {
10829                 u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
10830                                 I40E_GL_MDET_RX_FUNCTION_SHIFT;
10831                 u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
10832                                 I40E_GL_MDET_RX_EVENT_SHIFT;
10833                 u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
10834                                 I40E_GL_MDET_RX_QUEUE_SHIFT) -
10835                                 pf->hw.func_caps.base_queue;
10836                 if (netif_msg_rx_err(pf))
10837                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
10838                                  event, queue, func);
10839                 wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
10840                 mdd_detected = true;
10841         }
10842
10843         if (mdd_detected) {
10844                 reg = rd32(hw, I40E_PF_MDET_TX);
10845                 if (reg & I40E_PF_MDET_TX_VALID_MASK) {
10846                         wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
10847                         dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
10848                 }
10849                 reg = rd32(hw, I40E_PF_MDET_RX);
10850                 if (reg & I40E_PF_MDET_RX_VALID_MASK) {
10851                         wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
10852                         dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
10853                 }
10854         }
10855
10856         /* see if one of the VFs needs its hand slapped */
10857         for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
10858                 vf = &(pf->vf[i]);
10859                 reg = rd32(hw, I40E_VP_MDET_TX(i));
10860                 if (reg & I40E_VP_MDET_TX_VALID_MASK) {
10861                         wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
10862                         vf->num_mdd_events++;
10863                         dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
10864                                  i);
10865                         dev_info(&pf->pdev->dev,
10866                                  "Use PF Control I/F to re-enable the VF\n");
10867                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
10868                 }
10869
10870                 reg = rd32(hw, I40E_VP_MDET_RX(i));
10871                 if (reg & I40E_VP_MDET_RX_VALID_MASK) {
10872                         wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
10873                         vf->num_mdd_events++;
10874                         dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
10875                                  i);
10876                         dev_info(&pf->pdev->dev,
10877                                  "Use PF Control I/F to re-enable the VF\n");
10878                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
10879                 }
10880         }
10881
10882         /* re-enable mdd interrupt cause */
10883         clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
10884         reg = rd32(hw, I40E_PFINT_ICR0_ENA);
10885         reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
10886         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
10887         i40e_flush(hw);
10888 }
10889
10890 /**
10891  * i40e_service_task - Run the driver's async subtasks
10892  * @work: pointer to work_struct containing our data
10893  **/
10894 static void i40e_service_task(struct work_struct *work)
10895 {
10896         struct i40e_pf *pf = container_of(work,
10897                                           struct i40e_pf,
10898                                           service_task);
10899         unsigned long start_time = jiffies;
10900
10901         /* don't bother with service tasks if a reset is in progress */
10902         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
10903             test_bit(__I40E_SUSPENDED, pf->state))
10904                 return;
10905
10906         if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
10907                 return;
10908
10909         if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10910                 i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
10911                 i40e_sync_filters_subtask(pf);
10912                 i40e_reset_subtask(pf);
10913                 i40e_handle_mdd_event(pf);
10914                 i40e_vc_process_vflr_event(pf);
10915                 i40e_watchdog_subtask(pf);
10916                 i40e_fdir_reinit_subtask(pf);
10917                 if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
10918                         /* Client subtask will reopen next time through. */
10919                         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
10920                                                            true);
10921                 } else {
10922                         i40e_client_subtask(pf);
10923                         if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
10924                                                pf->state))
10925                                 i40e_notify_client_of_l2_param_changes(
10926                                                                 pf->vsi[pf->lan_vsi]);
10927                 }
10928                 i40e_sync_filters_subtask(pf);
10929         } else {
10930                 i40e_reset_subtask(pf);
10931         }
10932
10933         i40e_clean_adminq_subtask(pf);
10934
10935         /* flush memory to make sure state is correct before next watchdog */
10936         smp_mb__before_atomic();
10937         clear_bit(__I40E_SERVICE_SCHED, pf->state);
10938
10939         /* If the tasks have taken longer than one timer cycle or there
10940          * is more work to be done, reschedule the service task now
10941          * rather than wait for the timer to tick again.
10942          */
10943         if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
10944             test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)             ||
10945             test_bit(__I40E_MDD_EVENT_PENDING, pf->state)                ||
10946             test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
10947                 i40e_service_event_schedule(pf);
10948 }
10949
10950 /**
10951  * i40e_service_timer - timer callback
10952  * @t: timer list pointer
10953  **/
10954 static void i40e_service_timer(struct timer_list *t)
10955 {
10956         struct i40e_pf *pf = from_timer(pf, t, service_timer);
10957
10958         mod_timer(&pf->service_timer,
10959                   round_jiffies(jiffies + pf->service_timer_period));
10960         i40e_service_event_schedule(pf);
10961 }
10962
10963 /**
10964  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
10965  * @vsi: the VSI being configured
10966  **/
10967 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
10968 {
10969         struct i40e_pf *pf = vsi->back;
10970
10971         switch (vsi->type) {
10972         case I40E_VSI_MAIN:
10973                 vsi->alloc_queue_pairs = pf->num_lan_qps;
10974                 if (!vsi->num_tx_desc)
10975                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10976                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
10977                 if (!vsi->num_rx_desc)
10978                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10979                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
10980                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
10981                         vsi->num_q_vectors = pf->num_lan_msix;
10982                 else
10983                         vsi->num_q_vectors = 1;
10984
10985                 break;
10986
10987         case I40E_VSI_FDIR:
10988                 vsi->alloc_queue_pairs = 1;
10989                 vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
10990                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
10991                 vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
10992                                          I40E_REQ_DESCRIPTOR_MULTIPLE);
10993                 vsi->num_q_vectors = pf->num_fdsb_msix;
10994                 break;
10995
10996         case I40E_VSI_VMDQ2:
10997                 vsi->alloc_queue_pairs = pf->num_vmdq_qps;
10998                 if (!vsi->num_tx_desc)
10999                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11000                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11001                 if (!vsi->num_rx_desc)
11002                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11003                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11004                 vsi->num_q_vectors = pf->num_vmdq_msix;
11005                 break;
11006
11007         case I40E_VSI_SRIOV:
11008                 vsi->alloc_queue_pairs = pf->num_vf_qps;
11009                 if (!vsi->num_tx_desc)
11010                         vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11011                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11012                 if (!vsi->num_rx_desc)
11013                         vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
11014                                                  I40E_REQ_DESCRIPTOR_MULTIPLE);
11015                 break;
11016
11017         default:
11018                 WARN_ON(1);
11019                 return -ENODATA;
11020         }
11021
11022         if (is_kdump_kernel()) {
11023                 vsi->num_tx_desc = I40E_MIN_NUM_DESCRIPTORS;
11024                 vsi->num_rx_desc = I40E_MIN_NUM_DESCRIPTORS;
11025         }
11026
11027         return 0;
11028 }
11029
11030 /**
11031  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
11032  * @vsi: VSI pointer
11033  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
11034  *
11035  * On error: returns error code (negative)
11036  * On success: returns 0
11037  **/
11038 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
11039 {
11040         struct i40e_ring **next_rings;
11041         int size;
11042         int ret = 0;
11043
11044         /* allocate memory for both Tx, XDP Tx and Rx ring pointers */
11045         size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
11046                (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
11047         vsi->tx_rings = kzalloc(size, GFP_KERNEL);
11048         if (!vsi->tx_rings)
11049                 return -ENOMEM;
11050         next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
11051         if (i40e_enabled_xdp_vsi(vsi)) {
11052                 vsi->xdp_rings = next_rings;
11053                 next_rings += vsi->alloc_queue_pairs;
11054         }
11055         vsi->rx_rings = next_rings;
11056
11057         if (alloc_qvectors) {
11058                 /* allocate memory for q_vector pointers */
11059                 size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
11060                 vsi->q_vectors = kzalloc(size, GFP_KERNEL);
11061                 if (!vsi->q_vectors) {
11062                         ret = -ENOMEM;
11063                         goto err_vectors;
11064                 }
11065         }
11066         return ret;
11067
11068 err_vectors:
11069         kfree(vsi->tx_rings);
11070         return ret;
11071 }
11072
11073 /**
11074  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
11075  * @pf: board private structure
11076  * @type: type of VSI
11077  *
11078  * On error: returns error code (negative)
11079  * On success: returns vsi index in PF (positive)
11080  **/
11081 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
11082 {
11083         int ret = -ENODEV;
11084         struct i40e_vsi *vsi;
11085         int vsi_idx;
11086         int i;
11087
11088         /* Need to protect the allocation of the VSIs at the PF level */
11089         mutex_lock(&pf->switch_mutex);
11090
11091         /* VSI list may be fragmented if VSI creation/destruction has
11092          * been happening.  We can afford to do a quick scan to look
11093          * for any free VSIs in the list.
11094          *
11095          * find next empty vsi slot, looping back around if necessary
11096          */
11097         i = pf->next_vsi;
11098         while (i < pf->num_alloc_vsi && pf->vsi[i])
11099                 i++;
11100         if (i >= pf->num_alloc_vsi) {
11101                 i = 0;
11102                 while (i < pf->next_vsi && pf->vsi[i])
11103                         i++;
11104         }
11105
11106         if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
11107                 vsi_idx = i;             /* Found one! */
11108         } else {
11109                 ret = -ENODEV;
11110                 goto unlock_pf;  /* out of VSI slots! */
11111         }
11112         pf->next_vsi = ++i;
11113
11114         vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
11115         if (!vsi) {
11116                 ret = -ENOMEM;
11117                 goto unlock_pf;
11118         }
11119         vsi->type = type;
11120         vsi->back = pf;
11121         set_bit(__I40E_VSI_DOWN, vsi->state);
11122         vsi->flags = 0;
11123         vsi->idx = vsi_idx;
11124         vsi->int_rate_limit = 0;
11125         vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
11126                                 pf->rss_table_size : 64;
11127         vsi->netdev_registered = false;
11128         vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
11129         hash_init(vsi->mac_filter_hash);
11130         vsi->irqs_ready = false;
11131
11132         if (type == I40E_VSI_MAIN) {
11133                 vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
11134                 if (!vsi->af_xdp_zc_qps)
11135                         goto err_rings;
11136         }
11137
11138         ret = i40e_set_num_rings_in_vsi(vsi);
11139         if (ret)
11140                 goto err_rings;
11141
11142         ret = i40e_vsi_alloc_arrays(vsi, true);
11143         if (ret)
11144                 goto err_rings;
11145
11146         /* Setup default MSIX irq handler for VSI */
11147         i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
11148
11149         /* Initialize VSI lock */
11150         spin_lock_init(&vsi->mac_filter_hash_lock);
11151         pf->vsi[vsi_idx] = vsi;
11152         ret = vsi_idx;
11153         goto unlock_pf;
11154
11155 err_rings:
11156         bitmap_free(vsi->af_xdp_zc_qps);
11157         pf->next_vsi = i - 1;
11158         kfree(vsi);
11159 unlock_pf:
11160         mutex_unlock(&pf->switch_mutex);
11161         return ret;
11162 }
11163
11164 /**
11165  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
11166  * @vsi: VSI pointer
11167  * @free_qvectors: a bool to specify if q_vectors need to be freed.
11168  *
11169  * On error: returns error code (negative)
11170  * On success: returns 0
11171  **/
11172 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
11173 {
11174         /* free the ring and vector containers */
11175         if (free_qvectors) {
11176                 kfree(vsi->q_vectors);
11177                 vsi->q_vectors = NULL;
11178         }
11179         kfree(vsi->tx_rings);
11180         vsi->tx_rings = NULL;
11181         vsi->rx_rings = NULL;
11182         vsi->xdp_rings = NULL;
11183 }
11184
11185 /**
11186  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
11187  * and lookup table
11188  * @vsi: Pointer to VSI structure
11189  */
11190 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
11191 {
11192         if (!vsi)
11193                 return;
11194
11195         kfree(vsi->rss_hkey_user);
11196         vsi->rss_hkey_user = NULL;
11197
11198         kfree(vsi->rss_lut_user);
11199         vsi->rss_lut_user = NULL;
11200 }
11201
11202 /**
11203  * i40e_vsi_clear - Deallocate the VSI provided
11204  * @vsi: the VSI being un-configured
11205  **/
11206 static int i40e_vsi_clear(struct i40e_vsi *vsi)
11207 {
11208         struct i40e_pf *pf;
11209
11210         if (!vsi)
11211                 return 0;
11212
11213         if (!vsi->back)
11214                 goto free_vsi;
11215         pf = vsi->back;
11216
11217         mutex_lock(&pf->switch_mutex);
11218         if (!pf->vsi[vsi->idx]) {
11219                 dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
11220                         vsi->idx, vsi->idx, vsi->type);
11221                 goto unlock_vsi;
11222         }
11223
11224         if (pf->vsi[vsi->idx] != vsi) {
11225                 dev_err(&pf->pdev->dev,
11226                         "pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
11227                         pf->vsi[vsi->idx]->idx,
11228                         pf->vsi[vsi->idx]->type,
11229                         vsi->idx, vsi->type);
11230                 goto unlock_vsi;
11231         }
11232
11233         /* updates the PF for this cleared vsi */
11234         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
11235         i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
11236
11237         bitmap_free(vsi->af_xdp_zc_qps);
11238         i40e_vsi_free_arrays(vsi, true);
11239         i40e_clear_rss_config_user(vsi);
11240
11241         pf->vsi[vsi->idx] = NULL;
11242         if (vsi->idx < pf->next_vsi)
11243                 pf->next_vsi = vsi->idx;
11244
11245 unlock_vsi:
11246         mutex_unlock(&pf->switch_mutex);
11247 free_vsi:
11248         kfree(vsi);
11249
11250         return 0;
11251 }
11252
11253 /**
11254  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
11255  * @vsi: the VSI being cleaned
11256  **/
11257 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
11258 {
11259         int i;
11260
11261         if (vsi->tx_rings && vsi->tx_rings[0]) {
11262                 for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11263                         kfree_rcu(vsi->tx_rings[i], rcu);
11264                         WRITE_ONCE(vsi->tx_rings[i], NULL);
11265                         WRITE_ONCE(vsi->rx_rings[i], NULL);
11266                         if (vsi->xdp_rings)
11267                                 WRITE_ONCE(vsi->xdp_rings[i], NULL);
11268                 }
11269         }
11270 }
11271
11272 /**
11273  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
11274  * @vsi: the VSI being configured
11275  **/
11276 static int i40e_alloc_rings(struct i40e_vsi *vsi)
11277 {
11278         int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
11279         struct i40e_pf *pf = vsi->back;
11280         struct i40e_ring *ring;
11281
11282         /* Set basic values in the rings to be used later during open() */
11283         for (i = 0; i < vsi->alloc_queue_pairs; i++) {
11284                 /* allocate space for both Tx and Rx in one shot */
11285                 ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
11286                 if (!ring)
11287                         goto err_out;
11288
11289                 ring->queue_index = i;
11290                 ring->reg_idx = vsi->base_queue + i;
11291                 ring->ring_active = false;
11292                 ring->vsi = vsi;
11293                 ring->netdev = vsi->netdev;
11294                 ring->dev = &pf->pdev->dev;
11295                 ring->count = vsi->num_tx_desc;
11296                 ring->size = 0;
11297                 ring->dcb_tc = 0;
11298                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11299                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11300                 ring->itr_setting = pf->tx_itr_default;
11301                 WRITE_ONCE(vsi->tx_rings[i], ring++);
11302
11303                 if (!i40e_enabled_xdp_vsi(vsi))
11304                         goto setup_rx;
11305
11306                 ring->queue_index = vsi->alloc_queue_pairs + i;
11307                 ring->reg_idx = vsi->base_queue + ring->queue_index;
11308                 ring->ring_active = false;
11309                 ring->vsi = vsi;
11310                 ring->netdev = NULL;
11311                 ring->dev = &pf->pdev->dev;
11312                 ring->count = vsi->num_tx_desc;
11313                 ring->size = 0;
11314                 ring->dcb_tc = 0;
11315                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
11316                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
11317                 set_ring_xdp(ring);
11318                 ring->itr_setting = pf->tx_itr_default;
11319                 WRITE_ONCE(vsi->xdp_rings[i], ring++);
11320
11321 setup_rx:
11322                 ring->queue_index = i;
11323                 ring->reg_idx = vsi->base_queue + i;
11324                 ring->ring_active = false;
11325                 ring->vsi = vsi;
11326                 ring->netdev = vsi->netdev;
11327                 ring->dev = &pf->pdev->dev;
11328                 ring->count = vsi->num_rx_desc;
11329                 ring->size = 0;
11330                 ring->dcb_tc = 0;
11331                 ring->itr_setting = pf->rx_itr_default;
11332                 WRITE_ONCE(vsi->rx_rings[i], ring);
11333         }
11334
11335         return 0;
11336
11337 err_out:
11338         i40e_vsi_clear_rings(vsi);
11339         return -ENOMEM;
11340 }
11341
11342 /**
11343  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
11344  * @pf: board private structure
11345  * @vectors: the number of MSI-X vectors to request
11346  *
11347  * Returns the number of vectors reserved, or error
11348  **/
11349 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
11350 {
11351         vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
11352                                         I40E_MIN_MSIX, vectors);
11353         if (vectors < 0) {
11354                 dev_info(&pf->pdev->dev,
11355                          "MSI-X vector reservation failed: %d\n", vectors);
11356                 vectors = 0;
11357         }
11358
11359         return vectors;
11360 }
11361
11362 /**
11363  * i40e_init_msix - Setup the MSIX capability
11364  * @pf: board private structure
11365  *
11366  * Work with the OS to set up the MSIX vectors needed.
11367  *
11368  * Returns the number of vectors reserved or negative on failure
11369  **/
11370 static int i40e_init_msix(struct i40e_pf *pf)
11371 {
11372         struct i40e_hw *hw = &pf->hw;
11373         int cpus, extra_vectors;
11374         int vectors_left;
11375         int v_budget, i;
11376         int v_actual;
11377         int iwarp_requested = 0;
11378
11379         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
11380                 return -ENODEV;
11381
11382         /* The number of vectors we'll request will be comprised of:
11383          *   - Add 1 for "other" cause for Admin Queue events, etc.
11384          *   - The number of LAN queue pairs
11385          *      - Queues being used for RSS.
11386          *              We don't need as many as max_rss_size vectors.
11387          *              use rss_size instead in the calculation since that
11388          *              is governed by number of cpus in the system.
11389          *      - assumes symmetric Tx/Rx pairing
11390          *   - The number of VMDq pairs
11391          *   - The CPU count within the NUMA node if iWARP is enabled
11392          * Once we count this up, try the request.
11393          *
11394          * If we can't get what we want, we'll simplify to nearly nothing
11395          * and try again.  If that still fails, we punt.
11396          */
11397         vectors_left = hw->func_caps.num_msix_vectors;
11398         v_budget = 0;
11399
11400         /* reserve one vector for miscellaneous handler */
11401         if (vectors_left) {
11402                 v_budget++;
11403                 vectors_left--;
11404         }
11405
11406         /* reserve some vectors for the main PF traffic queues. Initially we
11407          * only reserve at most 50% of the available vectors, in the case that
11408          * the number of online CPUs is large. This ensures that we can enable
11409          * extra features as well. Once we've enabled the other features, we
11410          * will use any remaining vectors to reach as close as we can to the
11411          * number of online CPUs.
11412          */
11413         cpus = num_online_cpus();
11414         pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
11415         vectors_left -= pf->num_lan_msix;
11416
11417         /* reserve one vector for sideband flow director */
11418         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11419                 if (vectors_left) {
11420                         pf->num_fdsb_msix = 1;
11421                         v_budget++;
11422                         vectors_left--;
11423                 } else {
11424                         pf->num_fdsb_msix = 0;
11425                 }
11426         }
11427
11428         /* can we reserve enough for iWARP? */
11429         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11430                 iwarp_requested = pf->num_iwarp_msix;
11431
11432                 if (!vectors_left)
11433                         pf->num_iwarp_msix = 0;
11434                 else if (vectors_left < pf->num_iwarp_msix)
11435                         pf->num_iwarp_msix = 1;
11436                 v_budget += pf->num_iwarp_msix;
11437                 vectors_left -= pf->num_iwarp_msix;
11438         }
11439
11440         /* any vectors left over go for VMDq support */
11441         if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
11442                 if (!vectors_left) {
11443                         pf->num_vmdq_msix = 0;
11444                         pf->num_vmdq_qps = 0;
11445                 } else {
11446                         int vmdq_vecs_wanted =
11447                                 pf->num_vmdq_vsis * pf->num_vmdq_qps;
11448                         int vmdq_vecs =
11449                                 min_t(int, vectors_left, vmdq_vecs_wanted);
11450
11451                         /* if we're short on vectors for what's desired, we limit
11452                          * the queues per vmdq.  If this is still more than are
11453                          * available, the user will need to change the number of
11454                          * queues/vectors used by the PF later with the ethtool
11455                          * channels command
11456                          */
11457                         if (vectors_left < vmdq_vecs_wanted) {
11458                                 pf->num_vmdq_qps = 1;
11459                                 vmdq_vecs_wanted = pf->num_vmdq_vsis;
11460                                 vmdq_vecs = min_t(int,
11461                                                   vectors_left,
11462                                                   vmdq_vecs_wanted);
11463                         }
11464                         pf->num_vmdq_msix = pf->num_vmdq_qps;
11465
11466                         v_budget += vmdq_vecs;
11467                         vectors_left -= vmdq_vecs;
11468                 }
11469         }
11470
11471         /* On systems with a large number of SMP cores, we previously limited
11472          * the number of vectors for num_lan_msix to be at most 50% of the
11473          * available vectors, to allow for other features. Now, we add back
11474          * the remaining vectors. However, we ensure that the total
11475          * num_lan_msix will not exceed num_online_cpus(). To do this, we
11476          * calculate the number of vectors we can add without going over the
11477          * cap of CPUs. For systems with a small number of CPUs this will be
11478          * zero.
11479          */
11480         extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11481         pf->num_lan_msix += extra_vectors;
11482         vectors_left -= extra_vectors;
11483
11484         WARN(vectors_left < 0,
11485              "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11486
11487         v_budget += pf->num_lan_msix;
11488         pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11489                                    GFP_KERNEL);
11490         if (!pf->msix_entries)
11491                 return -ENOMEM;
11492
11493         for (i = 0; i < v_budget; i++)
11494                 pf->msix_entries[i].entry = i;
11495         v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11496
11497         if (v_actual < I40E_MIN_MSIX) {
11498                 pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11499                 kfree(pf->msix_entries);
11500                 pf->msix_entries = NULL;
11501                 pci_disable_msix(pf->pdev);
11502                 return -ENODEV;
11503
11504         } else if (v_actual == I40E_MIN_MSIX) {
11505                 /* Adjust for minimal MSIX use */
11506                 pf->num_vmdq_vsis = 0;
11507                 pf->num_vmdq_qps = 0;
11508                 pf->num_lan_qps = 1;
11509                 pf->num_lan_msix = 1;
11510
11511         } else if (v_actual != v_budget) {
11512                 /* If we have limited resources, we will start with no vectors
11513                  * for the special features and then allocate vectors to some
11514                  * of these features based on the policy and at the end disable
11515                  * the features that did not get any vectors.
11516                  */
11517                 int vec;
11518
11519                 dev_info(&pf->pdev->dev,
11520                          "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11521                          v_actual, v_budget);
11522                 /* reserve the misc vector */
11523                 vec = v_actual - 1;
11524
11525                 /* Scale vector usage down */
11526                 pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11527                 pf->num_vmdq_vsis = 1;
11528                 pf->num_vmdq_qps = 1;
11529
11530                 /* partition out the remaining vectors */
11531                 switch (vec) {
11532                 case 2:
11533                         pf->num_lan_msix = 1;
11534                         break;
11535                 case 3:
11536                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11537                                 pf->num_lan_msix = 1;
11538                                 pf->num_iwarp_msix = 1;
11539                         } else {
11540                                 pf->num_lan_msix = 2;
11541                         }
11542                         break;
11543                 default:
11544                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11545                                 pf->num_iwarp_msix = min_t(int, (vec / 3),
11546                                                  iwarp_requested);
11547                                 pf->num_vmdq_vsis = min_t(int, (vec / 3),
11548                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11549                         } else {
11550                                 pf->num_vmdq_vsis = min_t(int, (vec / 2),
11551                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
11552                         }
11553                         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11554                                 pf->num_fdsb_msix = 1;
11555                                 vec--;
11556                         }
11557                         pf->num_lan_msix = min_t(int,
11558                                (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11559                                                               pf->num_lan_msix);
11560                         pf->num_lan_qps = pf->num_lan_msix;
11561                         break;
11562                 }
11563         }
11564
11565         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11566             (pf->num_fdsb_msix == 0)) {
11567                 dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11568                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11569                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11570         }
11571         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11572             (pf->num_vmdq_msix == 0)) {
11573                 dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11574                 pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11575         }
11576
11577         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11578             (pf->num_iwarp_msix == 0)) {
11579                 dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11580                 pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11581         }
11582         i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11583                    "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11584                    pf->num_lan_msix,
11585                    pf->num_vmdq_msix * pf->num_vmdq_vsis,
11586                    pf->num_fdsb_msix,
11587                    pf->num_iwarp_msix);
11588
11589         return v_actual;
11590 }
11591
11592 /**
11593  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11594  * @vsi: the VSI being configured
11595  * @v_idx: index of the vector in the vsi struct
11596  *
11597  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11598  **/
11599 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx)
11600 {
11601         struct i40e_q_vector *q_vector;
11602
11603         /* allocate q_vector */
11604         q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11605         if (!q_vector)
11606                 return -ENOMEM;
11607
11608         q_vector->vsi = vsi;
11609         q_vector->v_idx = v_idx;
11610         cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11611
11612         if (vsi->netdev)
11613                 netif_napi_add(vsi->netdev, &q_vector->napi,
11614                                i40e_napi_poll, NAPI_POLL_WEIGHT);
11615
11616         /* tie q_vector and vsi together */
11617         vsi->q_vectors[v_idx] = q_vector;
11618
11619         return 0;
11620 }
11621
11622 /**
11623  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11624  * @vsi: the VSI being configured
11625  *
11626  * We allocate one q_vector per queue interrupt.  If allocation fails we
11627  * return -ENOMEM.
11628  **/
11629 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11630 {
11631         struct i40e_pf *pf = vsi->back;
11632         int err, v_idx, num_q_vectors;
11633
11634         /* if not MSIX, give the one vector only to the LAN VSI */
11635         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11636                 num_q_vectors = vsi->num_q_vectors;
11637         else if (vsi == pf->vsi[pf->lan_vsi])
11638                 num_q_vectors = 1;
11639         else
11640                 return -EINVAL;
11641
11642         for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
11643                 err = i40e_vsi_alloc_q_vector(vsi, v_idx);
11644                 if (err)
11645                         goto err_out;
11646         }
11647
11648         return 0;
11649
11650 err_out:
11651         while (v_idx--)
11652                 i40e_free_q_vector(vsi, v_idx);
11653
11654         return err;
11655 }
11656
11657 /**
11658  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
11659  * @pf: board private structure to initialize
11660  **/
11661 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
11662 {
11663         int vectors = 0;
11664         ssize_t size;
11665
11666         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11667                 vectors = i40e_init_msix(pf);
11668                 if (vectors < 0) {
11669                         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED   |
11670                                        I40E_FLAG_IWARP_ENABLED  |
11671                                        I40E_FLAG_RSS_ENABLED    |
11672                                        I40E_FLAG_DCB_CAPABLE    |
11673                                        I40E_FLAG_DCB_ENABLED    |
11674                                        I40E_FLAG_SRIOV_ENABLED  |
11675                                        I40E_FLAG_FD_SB_ENABLED  |
11676                                        I40E_FLAG_FD_ATR_ENABLED |
11677                                        I40E_FLAG_VMDQ_ENABLED);
11678                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11679
11680                         /* rework the queue expectations without MSIX */
11681                         i40e_determine_queue_usage(pf);
11682                 }
11683         }
11684
11685         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11686             (pf->flags & I40E_FLAG_MSI_ENABLED)) {
11687                 dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
11688                 vectors = pci_enable_msi(pf->pdev);
11689                 if (vectors < 0) {
11690                         dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
11691                                  vectors);
11692                         pf->flags &= ~I40E_FLAG_MSI_ENABLED;
11693                 }
11694                 vectors = 1;  /* one MSI or Legacy vector */
11695         }
11696
11697         if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
11698                 dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
11699
11700         /* set up vector assignment tracking */
11701         size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
11702         pf->irq_pile = kzalloc(size, GFP_KERNEL);
11703         if (!pf->irq_pile)
11704                 return -ENOMEM;
11705
11706         pf->irq_pile->num_entries = vectors;
11707         pf->irq_pile->search_hint = 0;
11708
11709         /* track first vector for misc interrupts, ignore return */
11710         (void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
11711
11712         return 0;
11713 }
11714
11715 /**
11716  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
11717  * @pf: private board data structure
11718  *
11719  * Restore the interrupt scheme that was cleared when we suspended the
11720  * device. This should be called during resume to re-allocate the q_vectors
11721  * and reacquire IRQs.
11722  */
11723 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
11724 {
11725         int err, i;
11726
11727         /* We cleared the MSI and MSI-X flags when disabling the old interrupt
11728          * scheme. We need to re-enabled them here in order to attempt to
11729          * re-acquire the MSI or MSI-X vectors
11730          */
11731         pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
11732
11733         err = i40e_init_interrupt_scheme(pf);
11734         if (err)
11735                 return err;
11736
11737         /* Now that we've re-acquired IRQs, we need to remap the vectors and
11738          * rings together again.
11739          */
11740         for (i = 0; i < pf->num_alloc_vsi; i++) {
11741                 if (pf->vsi[i]) {
11742                         err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
11743                         if (err)
11744                                 goto err_unwind;
11745                         i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
11746                 }
11747         }
11748
11749         err = i40e_setup_misc_vector(pf);
11750         if (err)
11751                 goto err_unwind;
11752
11753         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
11754                 i40e_client_update_msix_info(pf);
11755
11756         return 0;
11757
11758 err_unwind:
11759         while (i--) {
11760                 if (pf->vsi[i])
11761                         i40e_vsi_free_q_vectors(pf->vsi[i]);
11762         }
11763
11764         return err;
11765 }
11766
11767 /**
11768  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
11769  * non queue events in recovery mode
11770  * @pf: board private structure
11771  *
11772  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
11773  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
11774  * This is handled differently than in recovery mode since no Tx/Rx resources
11775  * are being allocated.
11776  **/
11777 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
11778 {
11779         int err;
11780
11781         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11782                 err = i40e_setup_misc_vector(pf);
11783
11784                 if (err) {
11785                         dev_info(&pf->pdev->dev,
11786                                  "MSI-X misc vector request failed, error %d\n",
11787                                  err);
11788                         return err;
11789                 }
11790         } else {
11791                 u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
11792
11793                 err = request_irq(pf->pdev->irq, i40e_intr, flags,
11794                                   pf->int_name, pf);
11795
11796                 if (err) {
11797                         dev_info(&pf->pdev->dev,
11798                                  "MSI/legacy misc vector request failed, error %d\n",
11799                                  err);
11800                         return err;
11801                 }
11802                 i40e_enable_misc_int_causes(pf);
11803                 i40e_irq_dynamic_enable_icr0(pf);
11804         }
11805
11806         return 0;
11807 }
11808
11809 /**
11810  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
11811  * @pf: board private structure
11812  *
11813  * This sets up the handler for MSIX 0, which is used to manage the
11814  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
11815  * when in MSI or Legacy interrupt mode.
11816  **/
11817 static int i40e_setup_misc_vector(struct i40e_pf *pf)
11818 {
11819         struct i40e_hw *hw = &pf->hw;
11820         int err = 0;
11821
11822         /* Only request the IRQ once, the first time through. */
11823         if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
11824                 err = request_irq(pf->msix_entries[0].vector,
11825                                   i40e_intr, 0, pf->int_name, pf);
11826                 if (err) {
11827                         clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
11828                         dev_info(&pf->pdev->dev,
11829                                  "request_irq for %s failed: %d\n",
11830                                  pf->int_name, err);
11831                         return -EFAULT;
11832                 }
11833         }
11834
11835         i40e_enable_misc_int_causes(pf);
11836
11837         /* associate no queues to the misc vector */
11838         wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
11839         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K >> 1);
11840
11841         i40e_flush(hw);
11842
11843         i40e_irq_dynamic_enable_icr0(pf);
11844
11845         return err;
11846 }
11847
11848 /**
11849  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
11850  * @vsi: Pointer to vsi structure
11851  * @seed: Buffter to store the hash keys
11852  * @lut: Buffer to store the lookup table entries
11853  * @lut_size: Size of buffer to store the lookup table entries
11854  *
11855  * Return 0 on success, negative on failure
11856  */
11857 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
11858                            u8 *lut, u16 lut_size)
11859 {
11860         struct i40e_pf *pf = vsi->back;
11861         struct i40e_hw *hw = &pf->hw;
11862         int ret = 0;
11863
11864         if (seed) {
11865                 ret = i40e_aq_get_rss_key(hw, vsi->id,
11866                         (struct i40e_aqc_get_set_rss_key_data *)seed);
11867                 if (ret) {
11868                         dev_info(&pf->pdev->dev,
11869                                  "Cannot get RSS key, err %s aq_err %s\n",
11870                                  i40e_stat_str(&pf->hw, ret),
11871                                  i40e_aq_str(&pf->hw,
11872                                              pf->hw.aq.asq_last_status));
11873                         return ret;
11874                 }
11875         }
11876
11877         if (lut) {
11878                 bool pf_lut = vsi->type == I40E_VSI_MAIN;
11879
11880                 ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
11881                 if (ret) {
11882                         dev_info(&pf->pdev->dev,
11883                                  "Cannot get RSS lut, err %s aq_err %s\n",
11884                                  i40e_stat_str(&pf->hw, ret),
11885                                  i40e_aq_str(&pf->hw,
11886                                              pf->hw.aq.asq_last_status));
11887                         return ret;
11888                 }
11889         }
11890
11891         return ret;
11892 }
11893
11894 /**
11895  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
11896  * @vsi: Pointer to vsi structure
11897  * @seed: RSS hash seed
11898  * @lut: Lookup table
11899  * @lut_size: Lookup table size
11900  *
11901  * Returns 0 on success, negative on failure
11902  **/
11903 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
11904                                const u8 *lut, u16 lut_size)
11905 {
11906         struct i40e_pf *pf = vsi->back;
11907         struct i40e_hw *hw = &pf->hw;
11908         u16 vf_id = vsi->vf_id;
11909         u8 i;
11910
11911         /* Fill out hash function seed */
11912         if (seed) {
11913                 u32 *seed_dw = (u32 *)seed;
11914
11915                 if (vsi->type == I40E_VSI_MAIN) {
11916                         for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
11917                                 wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
11918                 } else if (vsi->type == I40E_VSI_SRIOV) {
11919                         for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
11920                                 wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
11921                 } else {
11922                         dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
11923                 }
11924         }
11925
11926         if (lut) {
11927                 u32 *lut_dw = (u32 *)lut;
11928
11929                 if (vsi->type == I40E_VSI_MAIN) {
11930                         if (lut_size != I40E_HLUT_ARRAY_SIZE)
11931                                 return -EINVAL;
11932                         for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
11933                                 wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
11934                 } else if (vsi->type == I40E_VSI_SRIOV) {
11935                         if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
11936                                 return -EINVAL;
11937                         for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
11938                                 wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
11939                 } else {
11940                         dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
11941                 }
11942         }
11943         i40e_flush(hw);
11944
11945         return 0;
11946 }
11947
11948 /**
11949  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
11950  * @vsi: Pointer to VSI structure
11951  * @seed: Buffer to store the keys
11952  * @lut: Buffer to store the lookup table entries
11953  * @lut_size: Size of buffer to store the lookup table entries
11954  *
11955  * Returns 0 on success, negative on failure
11956  */
11957 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
11958                             u8 *lut, u16 lut_size)
11959 {
11960         struct i40e_pf *pf = vsi->back;
11961         struct i40e_hw *hw = &pf->hw;
11962         u16 i;
11963
11964         if (seed) {
11965                 u32 *seed_dw = (u32 *)seed;
11966
11967                 for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
11968                         seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
11969         }
11970         if (lut) {
11971                 u32 *lut_dw = (u32 *)lut;
11972
11973                 if (lut_size != I40E_HLUT_ARRAY_SIZE)
11974                         return -EINVAL;
11975                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
11976                         lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
11977         }
11978
11979         return 0;
11980 }
11981
11982 /**
11983  * i40e_config_rss - Configure RSS keys and lut
11984  * @vsi: Pointer to VSI structure
11985  * @seed: RSS hash seed
11986  * @lut: Lookup table
11987  * @lut_size: Lookup table size
11988  *
11989  * Returns 0 on success, negative on failure
11990  */
11991 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
11992 {
11993         struct i40e_pf *pf = vsi->back;
11994
11995         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
11996                 return i40e_config_rss_aq(vsi, seed, lut, lut_size);
11997         else
11998                 return i40e_config_rss_reg(vsi, seed, lut, lut_size);
11999 }
12000
12001 /**
12002  * i40e_get_rss - Get RSS keys and lut
12003  * @vsi: Pointer to VSI structure
12004  * @seed: Buffer to store the keys
12005  * @lut: Buffer to store the lookup table entries
12006  * @lut_size: Size of buffer to store the lookup table entries
12007  *
12008  * Returns 0 on success, negative on failure
12009  */
12010 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
12011 {
12012         struct i40e_pf *pf = vsi->back;
12013
12014         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
12015                 return i40e_get_rss_aq(vsi, seed, lut, lut_size);
12016         else
12017                 return i40e_get_rss_reg(vsi, seed, lut, lut_size);
12018 }
12019
12020 /**
12021  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
12022  * @pf: Pointer to board private structure
12023  * @lut: Lookup table
12024  * @rss_table_size: Lookup table size
12025  * @rss_size: Range of queue number for hashing
12026  */
12027 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
12028                        u16 rss_table_size, u16 rss_size)
12029 {
12030         u16 i;
12031
12032         for (i = 0; i < rss_table_size; i++)
12033                 lut[i] = i % rss_size;
12034 }
12035
12036 /**
12037  * i40e_pf_config_rss - Prepare for RSS if used
12038  * @pf: board private structure
12039  **/
12040 static int i40e_pf_config_rss(struct i40e_pf *pf)
12041 {
12042         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12043         u8 seed[I40E_HKEY_ARRAY_SIZE];
12044         u8 *lut;
12045         struct i40e_hw *hw = &pf->hw;
12046         u32 reg_val;
12047         u64 hena;
12048         int ret;
12049
12050         /* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
12051         hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
12052                 ((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
12053         hena |= i40e_pf_get_default_rss_hena(pf);
12054
12055         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
12056         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
12057
12058         /* Determine the RSS table size based on the hardware capabilities */
12059         reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
12060         reg_val = (pf->rss_table_size == 512) ?
12061                         (reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
12062                         (reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
12063         i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
12064
12065         /* Determine the RSS size of the VSI */
12066         if (!vsi->rss_size) {
12067                 u16 qcount;
12068                 /* If the firmware does something weird during VSI init, we
12069                  * could end up with zero TCs. Check for that to avoid
12070                  * divide-by-zero. It probably won't pass traffic, but it also
12071                  * won't panic.
12072                  */
12073                 qcount = vsi->num_queue_pairs /
12074                          (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
12075                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12076         }
12077         if (!vsi->rss_size)
12078                 return -EINVAL;
12079
12080         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
12081         if (!lut)
12082                 return -ENOMEM;
12083
12084         /* Use user configured lut if there is one, otherwise use default */
12085         if (vsi->rss_lut_user)
12086                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
12087         else
12088                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
12089
12090         /* Use user configured hash key if there is one, otherwise
12091          * use default.
12092          */
12093         if (vsi->rss_hkey_user)
12094                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
12095         else
12096                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
12097         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
12098         kfree(lut);
12099
12100         return ret;
12101 }
12102
12103 /**
12104  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
12105  * @pf: board private structure
12106  * @queue_count: the requested queue count for rss.
12107  *
12108  * returns 0 if rss is not enabled, if enabled returns the final rss queue
12109  * count which may be different from the requested queue count.
12110  * Note: expects to be called while under rtnl_lock()
12111  **/
12112 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
12113 {
12114         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
12115         int new_rss_size;
12116
12117         if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
12118                 return 0;
12119
12120         queue_count = min_t(int, queue_count, num_online_cpus());
12121         new_rss_size = min_t(int, queue_count, pf->rss_size_max);
12122
12123         if (queue_count != vsi->num_queue_pairs) {
12124                 u16 qcount;
12125
12126                 vsi->req_queue_pairs = queue_count;
12127                 i40e_prep_for_reset(pf);
12128
12129                 pf->alloc_rss_size = new_rss_size;
12130
12131                 i40e_reset_and_rebuild(pf, true, true);
12132
12133                 /* Discard the user configured hash keys and lut, if less
12134                  * queues are enabled.
12135                  */
12136                 if (queue_count < vsi->rss_size) {
12137                         i40e_clear_rss_config_user(vsi);
12138                         dev_dbg(&pf->pdev->dev,
12139                                 "discard user configured hash keys and lut\n");
12140                 }
12141
12142                 /* Reset vsi->rss_size, as number of enabled queues changed */
12143                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
12144                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
12145
12146                 i40e_pf_config_rss(pf);
12147         }
12148         dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
12149                  vsi->req_queue_pairs, pf->rss_size_max);
12150         return pf->alloc_rss_size;
12151 }
12152
12153 /**
12154  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
12155  * @pf: board private structure
12156  **/
12157 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
12158 {
12159         i40e_status status;
12160         bool min_valid, max_valid;
12161         u32 max_bw, min_bw;
12162
12163         status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
12164                                            &min_valid, &max_valid);
12165
12166         if (!status) {
12167                 if (min_valid)
12168                         pf->min_bw = min_bw;
12169                 if (max_valid)
12170                         pf->max_bw = max_bw;
12171         }
12172
12173         return status;
12174 }
12175
12176 /**
12177  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
12178  * @pf: board private structure
12179  **/
12180 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
12181 {
12182         struct i40e_aqc_configure_partition_bw_data bw_data;
12183         i40e_status status;
12184
12185         memset(&bw_data, 0, sizeof(bw_data));
12186
12187         /* Set the valid bit for this PF */
12188         bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
12189         bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
12190         bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
12191
12192         /* Set the new bandwidths */
12193         status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
12194
12195         return status;
12196 }
12197
12198 /**
12199  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
12200  * @pf: board private structure
12201  **/
12202 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
12203 {
12204         /* Commit temporary BW setting to permanent NVM image */
12205         enum i40e_admin_queue_err last_aq_status;
12206         i40e_status ret;
12207         u16 nvm_word;
12208
12209         if (pf->hw.partition_id != 1) {
12210                 dev_info(&pf->pdev->dev,
12211                          "Commit BW only works on partition 1! This is partition %d",
12212                          pf->hw.partition_id);
12213                 ret = I40E_NOT_SUPPORTED;
12214                 goto bw_commit_out;
12215         }
12216
12217         /* Acquire NVM for read access */
12218         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
12219         last_aq_status = pf->hw.aq.asq_last_status;
12220         if (ret) {
12221                 dev_info(&pf->pdev->dev,
12222                          "Cannot acquire NVM for read access, err %s aq_err %s\n",
12223                          i40e_stat_str(&pf->hw, ret),
12224                          i40e_aq_str(&pf->hw, last_aq_status));
12225                 goto bw_commit_out;
12226         }
12227
12228         /* Read word 0x10 of NVM - SW compatibility word 1 */
12229         ret = i40e_aq_read_nvm(&pf->hw,
12230                                I40E_SR_NVM_CONTROL_WORD,
12231                                0x10, sizeof(nvm_word), &nvm_word,
12232                                false, NULL);
12233         /* Save off last admin queue command status before releasing
12234          * the NVM
12235          */
12236         last_aq_status = pf->hw.aq.asq_last_status;
12237         i40e_release_nvm(&pf->hw);
12238         if (ret) {
12239                 dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
12240                          i40e_stat_str(&pf->hw, ret),
12241                          i40e_aq_str(&pf->hw, last_aq_status));
12242                 goto bw_commit_out;
12243         }
12244
12245         /* Wait a bit for NVM release to complete */
12246         msleep(50);
12247
12248         /* Acquire NVM for write access */
12249         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
12250         last_aq_status = pf->hw.aq.asq_last_status;
12251         if (ret) {
12252                 dev_info(&pf->pdev->dev,
12253                          "Cannot acquire NVM for write access, err %s aq_err %s\n",
12254                          i40e_stat_str(&pf->hw, ret),
12255                          i40e_aq_str(&pf->hw, last_aq_status));
12256                 goto bw_commit_out;
12257         }
12258         /* Write it back out unchanged to initiate update NVM,
12259          * which will force a write of the shadow (alt) RAM to
12260          * the NVM - thus storing the bandwidth values permanently.
12261          */
12262         ret = i40e_aq_update_nvm(&pf->hw,
12263                                  I40E_SR_NVM_CONTROL_WORD,
12264                                  0x10, sizeof(nvm_word),
12265                                  &nvm_word, true, 0, NULL);
12266         /* Save off last admin queue command status before releasing
12267          * the NVM
12268          */
12269         last_aq_status = pf->hw.aq.asq_last_status;
12270         i40e_release_nvm(&pf->hw);
12271         if (ret)
12272                 dev_info(&pf->pdev->dev,
12273                          "BW settings NOT SAVED, err %s aq_err %s\n",
12274                          i40e_stat_str(&pf->hw, ret),
12275                          i40e_aq_str(&pf->hw, last_aq_status));
12276 bw_commit_out:
12277
12278         return ret;
12279 }
12280
12281 /**
12282  * i40e_is_total_port_shutdown_enabled - read NVM and return value
12283  * if total port shutdown feature is enabled for this PF
12284  * @pf: board private structure
12285  **/
12286 static bool i40e_is_total_port_shutdown_enabled(struct i40e_pf *pf)
12287 {
12288 #define I40E_TOTAL_PORT_SHUTDOWN_ENABLED        BIT(4)
12289 #define I40E_FEATURES_ENABLE_PTR                0x2A
12290 #define I40E_CURRENT_SETTING_PTR                0x2B
12291 #define I40E_LINK_BEHAVIOR_WORD_OFFSET          0x2D
12292 #define I40E_LINK_BEHAVIOR_WORD_LENGTH          0x1
12293 #define I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED    BIT(0)
12294 #define I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH      4
12295         i40e_status read_status = I40E_SUCCESS;
12296         u16 sr_emp_sr_settings_ptr = 0;
12297         u16 features_enable = 0;
12298         u16 link_behavior = 0;
12299         bool ret = false;
12300
12301         read_status = i40e_read_nvm_word(&pf->hw,
12302                                          I40E_SR_EMP_SR_SETTINGS_PTR,
12303                                          &sr_emp_sr_settings_ptr);
12304         if (read_status)
12305                 goto err_nvm;
12306         read_status = i40e_read_nvm_word(&pf->hw,
12307                                          sr_emp_sr_settings_ptr +
12308                                          I40E_FEATURES_ENABLE_PTR,
12309                                          &features_enable);
12310         if (read_status)
12311                 goto err_nvm;
12312         if (I40E_TOTAL_PORT_SHUTDOWN_ENABLED & features_enable) {
12313                 read_status = i40e_read_nvm_module_data(&pf->hw,
12314                                                         I40E_SR_EMP_SR_SETTINGS_PTR,
12315                                                         I40E_CURRENT_SETTING_PTR,
12316                                                         I40E_LINK_BEHAVIOR_WORD_OFFSET,
12317                                                         I40E_LINK_BEHAVIOR_WORD_LENGTH,
12318                                                         &link_behavior);
12319                 if (read_status)
12320                         goto err_nvm;
12321                 link_behavior >>= (pf->hw.port * I40E_LINK_BEHAVIOR_PORT_BIT_LENGTH);
12322                 ret = I40E_LINK_BEHAVIOR_OS_FORCED_ENABLED & link_behavior;
12323         }
12324         return ret;
12325
12326 err_nvm:
12327         dev_warn(&pf->pdev->dev,
12328                  "total-port-shutdown feature is off due to read nvm error: %s\n",
12329                  i40e_stat_str(&pf->hw, read_status));
12330         return ret;
12331 }
12332
12333 /**
12334  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
12335  * @pf: board private structure to initialize
12336  *
12337  * i40e_sw_init initializes the Adapter private data structure.
12338  * Fields are initialized based on PCI device information and
12339  * OS network device settings (MTU size).
12340  **/
12341 static int i40e_sw_init(struct i40e_pf *pf)
12342 {
12343         int err = 0;
12344         int size;
12345         u16 pow;
12346
12347         /* Set default capability flags */
12348         pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
12349                     I40E_FLAG_MSI_ENABLED     |
12350                     I40E_FLAG_MSIX_ENABLED;
12351
12352         /* Set default ITR */
12353         pf->rx_itr_default = I40E_ITR_RX_DEF;
12354         pf->tx_itr_default = I40E_ITR_TX_DEF;
12355
12356         /* Depending on PF configurations, it is possible that the RSS
12357          * maximum might end up larger than the available queues
12358          */
12359         pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
12360         pf->alloc_rss_size = 1;
12361         pf->rss_table_size = pf->hw.func_caps.rss_table_size;
12362         pf->rss_size_max = min_t(int, pf->rss_size_max,
12363                                  pf->hw.func_caps.num_tx_qp);
12364
12365         /* find the next higher power-of-2 of num cpus */
12366         pow = roundup_pow_of_two(num_online_cpus());
12367         pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
12368
12369         if (pf->hw.func_caps.rss) {
12370                 pf->flags |= I40E_FLAG_RSS_ENABLED;
12371                 pf->alloc_rss_size = min_t(int, pf->rss_size_max,
12372                                            num_online_cpus());
12373         }
12374
12375         /* MFP mode enabled */
12376         if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
12377                 pf->flags |= I40E_FLAG_MFP_ENABLED;
12378                 dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
12379                 if (i40e_get_partition_bw_setting(pf)) {
12380                         dev_warn(&pf->pdev->dev,
12381                                  "Could not get partition bw settings\n");
12382                 } else {
12383                         dev_info(&pf->pdev->dev,
12384                                  "Partition BW Min = %8.8x, Max = %8.8x\n",
12385                                  pf->min_bw, pf->max_bw);
12386
12387                         /* nudge the Tx scheduler */
12388                         i40e_set_partition_bw_setting(pf);
12389                 }
12390         }
12391
12392         if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
12393             (pf->hw.func_caps.fd_filters_best_effort > 0)) {
12394                 pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
12395                 pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
12396                 if (pf->flags & I40E_FLAG_MFP_ENABLED &&
12397                     pf->hw.num_partitions > 1)
12398                         dev_info(&pf->pdev->dev,
12399                                  "Flow Director Sideband mode Disabled in MFP mode\n");
12400                 else
12401                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12402                 pf->fdir_pf_filter_count =
12403                                  pf->hw.func_caps.fd_filters_guaranteed;
12404                 pf->hw.fdir_shared_filter_count =
12405                                  pf->hw.func_caps.fd_filters_best_effort;
12406         }
12407
12408         if (pf->hw.mac.type == I40E_MAC_X722) {
12409                 pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
12410                                     I40E_HW_128_QP_RSS_CAPABLE |
12411                                     I40E_HW_ATR_EVICT_CAPABLE |
12412                                     I40E_HW_WB_ON_ITR_CAPABLE |
12413                                     I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
12414                                     I40E_HW_NO_PCI_LINK_CHECK |
12415                                     I40E_HW_USE_SET_LLDP_MIB |
12416                                     I40E_HW_GENEVE_OFFLOAD_CAPABLE |
12417                                     I40E_HW_PTP_L4_CAPABLE |
12418                                     I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
12419                                     I40E_HW_OUTER_UDP_CSUM_CAPABLE);
12420
12421 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
12422                 if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
12423                     I40E_FDEVICT_PCTYPE_DEFAULT) {
12424                         dev_warn(&pf->pdev->dev,
12425                                  "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
12426                         pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
12427                 }
12428         } else if ((pf->hw.aq.api_maj_ver > 1) ||
12429                    ((pf->hw.aq.api_maj_ver == 1) &&
12430                     (pf->hw.aq.api_min_ver > 4))) {
12431                 /* Supported in FW API version higher than 1.4 */
12432                 pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
12433         }
12434
12435         /* Enable HW ATR eviction if possible */
12436         if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
12437                 pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
12438
12439         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12440             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
12441             (pf->hw.aq.fw_maj_ver < 4))) {
12442                 pf->hw_features |= I40E_HW_RESTART_AUTONEG;
12443                 /* No DCB support  for FW < v4.33 */
12444                 pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
12445         }
12446
12447         /* Disable FW LLDP if FW < v4.3 */
12448         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12449             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
12450             (pf->hw.aq.fw_maj_ver < 4)))
12451                 pf->hw_features |= I40E_HW_STOP_FW_LLDP;
12452
12453         /* Use the FW Set LLDP MIB API if FW > v4.40 */
12454         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
12455             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
12456             (pf->hw.aq.fw_maj_ver >= 5)))
12457                 pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
12458
12459         /* Enable PTP L4 if FW > v6.0 */
12460         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12461             pf->hw.aq.fw_maj_ver >= 6)
12462                 pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
12463
12464         if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
12465                 pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
12466                 pf->flags |= I40E_FLAG_VMDQ_ENABLED;
12467                 pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
12468         }
12469
12470         if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
12471                 pf->flags |= I40E_FLAG_IWARP_ENABLED;
12472                 /* IWARP needs one extra vector for CQP just like MISC.*/
12473                 pf->num_iwarp_msix = (int)num_online_cpus() + 1;
12474         }
12475         /* Stopping FW LLDP engine is supported on XL710 and X722
12476          * starting from FW versions determined in i40e_init_adminq.
12477          * Stopping the FW LLDP engine is not supported on XL710
12478          * if NPAR is functioning so unset this hw flag in this case.
12479          */
12480         if (pf->hw.mac.type == I40E_MAC_XL710 &&
12481             pf->hw.func_caps.npar_enable &&
12482             (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
12483                 pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
12484
12485 #ifdef CONFIG_PCI_IOV
12486         if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
12487                 pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
12488                 pf->flags |= I40E_FLAG_SRIOV_ENABLED;
12489                 pf->num_req_vfs = min_t(int,
12490                                         pf->hw.func_caps.num_vfs,
12491                                         I40E_MAX_VF_COUNT);
12492         }
12493 #endif /* CONFIG_PCI_IOV */
12494         pf->eeprom_version = 0xDEAD;
12495         pf->lan_veb = I40E_NO_VEB;
12496         pf->lan_vsi = I40E_NO_VSI;
12497
12498         /* By default FW has this off for performance reasons */
12499         pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
12500
12501         /* set up queue assignment tracking */
12502         size = sizeof(struct i40e_lump_tracking)
12503                 + (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
12504         pf->qp_pile = kzalloc(size, GFP_KERNEL);
12505         if (!pf->qp_pile) {
12506                 err = -ENOMEM;
12507                 goto sw_init_done;
12508         }
12509         pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
12510         pf->qp_pile->search_hint = 0;
12511
12512         pf->tx_timeout_recovery_level = 1;
12513
12514         if (pf->hw.mac.type != I40E_MAC_X722 &&
12515             i40e_is_total_port_shutdown_enabled(pf)) {
12516                 /* Link down on close must be on when total port shutdown
12517                  * is enabled for a given port
12518                  */
12519                 pf->flags |= (I40E_FLAG_TOTAL_PORT_SHUTDOWN_ENABLED |
12520                               I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED);
12521                 dev_info(&pf->pdev->dev,
12522                          "total-port-shutdown was enabled, link-down-on-close is forced on\n");
12523         }
12524         mutex_init(&pf->switch_mutex);
12525
12526 sw_init_done:
12527         return err;
12528 }
12529
12530 /**
12531  * i40e_set_ntuple - set the ntuple feature flag and take action
12532  * @pf: board private structure to initialize
12533  * @features: the feature set that the stack is suggesting
12534  *
12535  * returns a bool to indicate if reset needs to happen
12536  **/
12537 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12538 {
12539         bool need_reset = false;
12540
12541         /* Check if Flow Director n-tuple support was enabled or disabled.  If
12542          * the state changed, we need to reset.
12543          */
12544         if (features & NETIF_F_NTUPLE) {
12545                 /* Enable filters and mark for reset */
12546                 if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12547                         need_reset = true;
12548                 /* enable FD_SB only if there is MSI-X vector and no cloud
12549                  * filters exist
12550                  */
12551                 if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12552                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12553                         pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12554                 }
12555         } else {
12556                 /* turn off filters, mark for reset and clear SW filter list */
12557                 if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12558                         need_reset = true;
12559                         i40e_fdir_filter_exit(pf);
12560                 }
12561                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12562                 clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12563                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12564
12565                 /* reset fd counters */
12566                 pf->fd_add_err = 0;
12567                 pf->fd_atr_cnt = 0;
12568                 /* if ATR was auto disabled it can be re-enabled. */
12569                 if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12570                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12571                             (I40E_DEBUG_FD & pf->hw.debug_mask))
12572                                 dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12573         }
12574         return need_reset;
12575 }
12576
12577 /**
12578  * i40e_clear_rss_lut - clear the rx hash lookup table
12579  * @vsi: the VSI being configured
12580  **/
12581 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12582 {
12583         struct i40e_pf *pf = vsi->back;
12584         struct i40e_hw *hw = &pf->hw;
12585         u16 vf_id = vsi->vf_id;
12586         u8 i;
12587
12588         if (vsi->type == I40E_VSI_MAIN) {
12589                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12590                         wr32(hw, I40E_PFQF_HLUT(i), 0);
12591         } else if (vsi->type == I40E_VSI_SRIOV) {
12592                 for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12593                         i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12594         } else {
12595                 dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12596         }
12597 }
12598
12599 /**
12600  * i40e_set_features - set the netdev feature flags
12601  * @netdev: ptr to the netdev being adjusted
12602  * @features: the feature set that the stack is suggesting
12603  * Note: expects to be called while under rtnl_lock()
12604  **/
12605 static int i40e_set_features(struct net_device *netdev,
12606                              netdev_features_t features)
12607 {
12608         struct i40e_netdev_priv *np = netdev_priv(netdev);
12609         struct i40e_vsi *vsi = np->vsi;
12610         struct i40e_pf *pf = vsi->back;
12611         bool need_reset;
12612
12613         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12614                 i40e_pf_config_rss(pf);
12615         else if (!(features & NETIF_F_RXHASH) &&
12616                  netdev->features & NETIF_F_RXHASH)
12617                 i40e_clear_rss_lut(vsi);
12618
12619         if (features & NETIF_F_HW_VLAN_CTAG_RX)
12620                 i40e_vlan_stripping_enable(vsi);
12621         else
12622                 i40e_vlan_stripping_disable(vsi);
12623
12624         if (!(features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12625                 dev_err(&pf->pdev->dev,
12626                         "Offloaded tc filters active, can't turn hw_tc_offload off");
12627                 return -EINVAL;
12628         }
12629
12630         if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12631                 i40e_del_all_macvlans(vsi);
12632
12633         need_reset = i40e_set_ntuple(pf, features);
12634
12635         if (need_reset)
12636                 i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12637
12638         return 0;
12639 }
12640
12641 static int i40e_udp_tunnel_set_port(struct net_device *netdev,
12642                                     unsigned int table, unsigned int idx,
12643                                     struct udp_tunnel_info *ti)
12644 {
12645         struct i40e_netdev_priv *np = netdev_priv(netdev);
12646         struct i40e_hw *hw = &np->vsi->back->hw;
12647         u8 type, filter_index;
12648         i40e_status ret;
12649
12650         type = ti->type == UDP_TUNNEL_TYPE_VXLAN ? I40E_AQC_TUNNEL_TYPE_VXLAN :
12651                                                    I40E_AQC_TUNNEL_TYPE_NGE;
12652
12653         ret = i40e_aq_add_udp_tunnel(hw, ntohs(ti->port), type, &filter_index,
12654                                      NULL);
12655         if (ret) {
12656                 netdev_info(netdev, "add UDP port failed, err %s aq_err %s\n",
12657                             i40e_stat_str(hw, ret),
12658                             i40e_aq_str(hw, hw->aq.asq_last_status));
12659                 return -EIO;
12660         }
12661
12662         udp_tunnel_nic_set_port_priv(netdev, table, idx, filter_index);
12663         return 0;
12664 }
12665
12666 static int i40e_udp_tunnel_unset_port(struct net_device *netdev,
12667                                       unsigned int table, unsigned int idx,
12668                                       struct udp_tunnel_info *ti)
12669 {
12670         struct i40e_netdev_priv *np = netdev_priv(netdev);
12671         struct i40e_hw *hw = &np->vsi->back->hw;
12672         i40e_status ret;
12673
12674         ret = i40e_aq_del_udp_tunnel(hw, ti->hw_priv, NULL);
12675         if (ret) {
12676                 netdev_info(netdev, "delete UDP port failed, err %s aq_err %s\n",
12677                             i40e_stat_str(hw, ret),
12678                             i40e_aq_str(hw, hw->aq.asq_last_status));
12679                 return -EIO;
12680         }
12681
12682         return 0;
12683 }
12684
12685 static int i40e_get_phys_port_id(struct net_device *netdev,
12686                                  struct netdev_phys_item_id *ppid)
12687 {
12688         struct i40e_netdev_priv *np = netdev_priv(netdev);
12689         struct i40e_pf *pf = np->vsi->back;
12690         struct i40e_hw *hw = &pf->hw;
12691
12692         if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
12693                 return -EOPNOTSUPP;
12694
12695         ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
12696         memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
12697
12698         return 0;
12699 }
12700
12701 /**
12702  * i40e_ndo_fdb_add - add an entry to the hardware database
12703  * @ndm: the input from the stack
12704  * @tb: pointer to array of nladdr (unused)
12705  * @dev: the net device pointer
12706  * @addr: the MAC address entry being added
12707  * @vid: VLAN ID
12708  * @flags: instructions from stack about fdb operation
12709  * @extack: netlink extended ack, unused currently
12710  */
12711 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
12712                             struct net_device *dev,
12713                             const unsigned char *addr, u16 vid,
12714                             u16 flags,
12715                             struct netlink_ext_ack *extack)
12716 {
12717         struct i40e_netdev_priv *np = netdev_priv(dev);
12718         struct i40e_pf *pf = np->vsi->back;
12719         int err = 0;
12720
12721         if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
12722                 return -EOPNOTSUPP;
12723
12724         if (vid) {
12725                 pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
12726                 return -EINVAL;
12727         }
12728
12729         /* Hardware does not support aging addresses so if a
12730          * ndm_state is given only allow permanent addresses
12731          */
12732         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
12733                 netdev_info(dev, "FDB only supports static addresses\n");
12734                 return -EINVAL;
12735         }
12736
12737         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
12738                 err = dev_uc_add_excl(dev, addr);
12739         else if (is_multicast_ether_addr(addr))
12740                 err = dev_mc_add_excl(dev, addr);
12741         else
12742                 err = -EINVAL;
12743
12744         /* Only return duplicate errors if NLM_F_EXCL is set */
12745         if (err == -EEXIST && !(flags & NLM_F_EXCL))
12746                 err = 0;
12747
12748         return err;
12749 }
12750
12751 /**
12752  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
12753  * @dev: the netdev being configured
12754  * @nlh: RTNL message
12755  * @flags: bridge flags
12756  * @extack: netlink extended ack
12757  *
12758  * Inserts a new hardware bridge if not already created and
12759  * enables the bridging mode requested (VEB or VEPA). If the
12760  * hardware bridge has already been inserted and the request
12761  * is to change the mode then that requires a PF reset to
12762  * allow rebuild of the components with required hardware
12763  * bridge mode enabled.
12764  *
12765  * Note: expects to be called while under rtnl_lock()
12766  **/
12767 static int i40e_ndo_bridge_setlink(struct net_device *dev,
12768                                    struct nlmsghdr *nlh,
12769                                    u16 flags,
12770                                    struct netlink_ext_ack *extack)
12771 {
12772         struct i40e_netdev_priv *np = netdev_priv(dev);
12773         struct i40e_vsi *vsi = np->vsi;
12774         struct i40e_pf *pf = vsi->back;
12775         struct i40e_veb *veb = NULL;
12776         struct nlattr *attr, *br_spec;
12777         int i, rem;
12778
12779         /* Only for PF VSI for now */
12780         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
12781                 return -EOPNOTSUPP;
12782
12783         /* Find the HW bridge for PF VSI */
12784         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
12785                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
12786                         veb = pf->veb[i];
12787         }
12788
12789         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
12790
12791         nla_for_each_nested(attr, br_spec, rem) {
12792                 __u16 mode;
12793
12794                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
12795                         continue;
12796
12797                 mode = nla_get_u16(attr);
12798                 if ((mode != BRIDGE_MODE_VEPA) &&
12799                     (mode != BRIDGE_MODE_VEB))
12800                         return -EINVAL;
12801
12802                 /* Insert a new HW bridge */
12803                 if (!veb) {
12804                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
12805                                              vsi->tc_config.enabled_tc);
12806                         if (veb) {
12807                                 veb->bridge_mode = mode;
12808                                 i40e_config_bridge_mode(veb);
12809                         } else {
12810                                 /* No Bridge HW offload available */
12811                                 return -ENOENT;
12812                         }
12813                         break;
12814                 } else if (mode != veb->bridge_mode) {
12815                         /* Existing HW bridge but different mode needs reset */
12816                         veb->bridge_mode = mode;
12817                         /* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
12818                         if (mode == BRIDGE_MODE_VEB)
12819                                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
12820                         else
12821                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
12822                         i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12823                         break;
12824                 }
12825         }
12826
12827         return 0;
12828 }
12829
12830 /**
12831  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
12832  * @skb: skb buff
12833  * @pid: process id
12834  * @seq: RTNL message seq #
12835  * @dev: the netdev being configured
12836  * @filter_mask: unused
12837  * @nlflags: netlink flags passed in
12838  *
12839  * Return the mode in which the hardware bridge is operating in
12840  * i.e VEB or VEPA.
12841  **/
12842 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
12843                                    struct net_device *dev,
12844                                    u32 __always_unused filter_mask,
12845                                    int nlflags)
12846 {
12847         struct i40e_netdev_priv *np = netdev_priv(dev);
12848         struct i40e_vsi *vsi = np->vsi;
12849         struct i40e_pf *pf = vsi->back;
12850         struct i40e_veb *veb = NULL;
12851         int i;
12852
12853         /* Only for PF VSI for now */
12854         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
12855                 return -EOPNOTSUPP;
12856
12857         /* Find the HW bridge for the PF VSI */
12858         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
12859                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
12860                         veb = pf->veb[i];
12861         }
12862
12863         if (!veb)
12864                 return 0;
12865
12866         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
12867                                        0, 0, nlflags, filter_mask, NULL);
12868 }
12869
12870 /**
12871  * i40e_features_check - Validate encapsulated packet conforms to limits
12872  * @skb: skb buff
12873  * @dev: This physical port's netdev
12874  * @features: Offload features that the stack believes apply
12875  **/
12876 static netdev_features_t i40e_features_check(struct sk_buff *skb,
12877                                              struct net_device *dev,
12878                                              netdev_features_t features)
12879 {
12880         size_t len;
12881
12882         /* No point in doing any of this if neither checksum nor GSO are
12883          * being requested for this frame.  We can rule out both by just
12884          * checking for CHECKSUM_PARTIAL
12885          */
12886         if (skb->ip_summed != CHECKSUM_PARTIAL)
12887                 return features;
12888
12889         /* We cannot support GSO if the MSS is going to be less than
12890          * 64 bytes.  If it is then we need to drop support for GSO.
12891          */
12892         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
12893                 features &= ~NETIF_F_GSO_MASK;
12894
12895         /* MACLEN can support at most 63 words */
12896         len = skb_network_header(skb) - skb->data;
12897         if (len & ~(63 * 2))
12898                 goto out_err;
12899
12900         /* IPLEN and EIPLEN can support at most 127 dwords */
12901         len = skb_transport_header(skb) - skb_network_header(skb);
12902         if (len & ~(127 * 4))
12903                 goto out_err;
12904
12905         if (skb->encapsulation) {
12906                 /* L4TUNLEN can support 127 words */
12907                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
12908                 if (len & ~(127 * 2))
12909                         goto out_err;
12910
12911                 /* IPLEN can support at most 127 dwords */
12912                 len = skb_inner_transport_header(skb) -
12913                       skb_inner_network_header(skb);
12914                 if (len & ~(127 * 4))
12915                         goto out_err;
12916         }
12917
12918         /* No need to validate L4LEN as TCP is the only protocol with a
12919          * a flexible value and we support all possible values supported
12920          * by TCP, which is at most 15 dwords
12921          */
12922
12923         return features;
12924 out_err:
12925         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
12926 }
12927
12928 /**
12929  * i40e_xdp_setup - add/remove an XDP program
12930  * @vsi: VSI to changed
12931  * @prog: XDP program
12932  * @extack: netlink extended ack
12933  **/
12934 static int i40e_xdp_setup(struct i40e_vsi *vsi, struct bpf_prog *prog,
12935                           struct netlink_ext_ack *extack)
12936 {
12937         int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
12938         struct i40e_pf *pf = vsi->back;
12939         struct bpf_prog *old_prog;
12940         bool need_reset;
12941         int i;
12942
12943         /* Don't allow frames that span over multiple buffers */
12944         if (frame_size > vsi->rx_buf_len) {
12945                 NL_SET_ERR_MSG_MOD(extack, "MTU too large to enable XDP");
12946                 return -EINVAL;
12947         }
12948
12949         /* When turning XDP on->off/off->on we reset and rebuild the rings. */
12950         need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
12951
12952         if (need_reset)
12953                 i40e_prep_for_reset(pf);
12954
12955         old_prog = xchg(&vsi->xdp_prog, prog);
12956
12957         if (need_reset) {
12958                 if (!prog)
12959                         /* Wait until ndo_xsk_wakeup completes. */
12960                         synchronize_rcu();
12961                 i40e_reset_and_rebuild(pf, true, true);
12962         }
12963
12964         for (i = 0; i < vsi->num_queue_pairs; i++)
12965                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
12966
12967         if (old_prog)
12968                 bpf_prog_put(old_prog);
12969
12970         /* Kick start the NAPI context if there is an AF_XDP socket open
12971          * on that queue id. This so that receiving will start.
12972          */
12973         if (need_reset && prog)
12974                 for (i = 0; i < vsi->num_queue_pairs; i++)
12975                         if (vsi->xdp_rings[i]->xsk_pool)
12976                                 (void)i40e_xsk_wakeup(vsi->netdev, i,
12977                                                       XDP_WAKEUP_RX);
12978
12979         return 0;
12980 }
12981
12982 /**
12983  * i40e_enter_busy_conf - Enters busy config state
12984  * @vsi: vsi
12985  *
12986  * Returns 0 on success, <0 for failure.
12987  **/
12988 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
12989 {
12990         struct i40e_pf *pf = vsi->back;
12991         int timeout = 50;
12992
12993         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
12994                 timeout--;
12995                 if (!timeout)
12996                         return -EBUSY;
12997                 usleep_range(1000, 2000);
12998         }
12999
13000         return 0;
13001 }
13002
13003 /**
13004  * i40e_exit_busy_conf - Exits busy config state
13005  * @vsi: vsi
13006  **/
13007 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
13008 {
13009         struct i40e_pf *pf = vsi->back;
13010
13011         clear_bit(__I40E_CONFIG_BUSY, pf->state);
13012 }
13013
13014 /**
13015  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
13016  * @vsi: vsi
13017  * @queue_pair: queue pair
13018  **/
13019 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
13020 {
13021         memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
13022                sizeof(vsi->rx_rings[queue_pair]->rx_stats));
13023         memset(&vsi->tx_rings[queue_pair]->stats, 0,
13024                sizeof(vsi->tx_rings[queue_pair]->stats));
13025         if (i40e_enabled_xdp_vsi(vsi)) {
13026                 memset(&vsi->xdp_rings[queue_pair]->stats, 0,
13027                        sizeof(vsi->xdp_rings[queue_pair]->stats));
13028         }
13029 }
13030
13031 /**
13032  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
13033  * @vsi: vsi
13034  * @queue_pair: queue pair
13035  **/
13036 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
13037 {
13038         i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
13039         if (i40e_enabled_xdp_vsi(vsi)) {
13040                 /* Make sure that in-progress ndo_xdp_xmit calls are
13041                  * completed.
13042                  */
13043                 synchronize_rcu();
13044                 i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
13045         }
13046         i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
13047 }
13048
13049 /**
13050  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
13051  * @vsi: vsi
13052  * @queue_pair: queue pair
13053  * @enable: true for enable, false for disable
13054  **/
13055 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
13056                                         bool enable)
13057 {
13058         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13059         struct i40e_q_vector *q_vector = rxr->q_vector;
13060
13061         if (!vsi->netdev)
13062                 return;
13063
13064         /* All rings in a qp belong to the same qvector. */
13065         if (q_vector->rx.ring || q_vector->tx.ring) {
13066                 if (enable)
13067                         napi_enable(&q_vector->napi);
13068                 else
13069                         napi_disable(&q_vector->napi);
13070         }
13071 }
13072
13073 /**
13074  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
13075  * @vsi: vsi
13076  * @queue_pair: queue pair
13077  * @enable: true for enable, false for disable
13078  *
13079  * Returns 0 on success, <0 on failure.
13080  **/
13081 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
13082                                         bool enable)
13083 {
13084         struct i40e_pf *pf = vsi->back;
13085         int pf_q, ret = 0;
13086
13087         pf_q = vsi->base_queue + queue_pair;
13088         ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
13089                                      false /*is xdp*/, enable);
13090         if (ret) {
13091                 dev_info(&pf->pdev->dev,
13092                          "VSI seid %d Tx ring %d %sable timeout\n",
13093                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13094                 return ret;
13095         }
13096
13097         i40e_control_rx_q(pf, pf_q, enable);
13098         ret = i40e_pf_rxq_wait(pf, pf_q, enable);
13099         if (ret) {
13100                 dev_info(&pf->pdev->dev,
13101                          "VSI seid %d Rx ring %d %sable timeout\n",
13102                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13103                 return ret;
13104         }
13105
13106         /* Due to HW errata, on Rx disable only, the register can
13107          * indicate done before it really is. Needs 50ms to be sure
13108          */
13109         if (!enable)
13110                 mdelay(50);
13111
13112         if (!i40e_enabled_xdp_vsi(vsi))
13113                 return ret;
13114
13115         ret = i40e_control_wait_tx_q(vsi->seid, pf,
13116                                      pf_q + vsi->alloc_queue_pairs,
13117                                      true /*is xdp*/, enable);
13118         if (ret) {
13119                 dev_info(&pf->pdev->dev,
13120                          "VSI seid %d XDP Tx ring %d %sable timeout\n",
13121                          vsi->seid, pf_q, (enable ? "en" : "dis"));
13122         }
13123
13124         return ret;
13125 }
13126
13127 /**
13128  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
13129  * @vsi: vsi
13130  * @queue_pair: queue_pair
13131  **/
13132 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
13133 {
13134         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13135         struct i40e_pf *pf = vsi->back;
13136         struct i40e_hw *hw = &pf->hw;
13137
13138         /* All rings in a qp belong to the same qvector. */
13139         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
13140                 i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
13141         else
13142                 i40e_irq_dynamic_enable_icr0(pf);
13143
13144         i40e_flush(hw);
13145 }
13146
13147 /**
13148  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
13149  * @vsi: vsi
13150  * @queue_pair: queue_pair
13151  **/
13152 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
13153 {
13154         struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
13155         struct i40e_pf *pf = vsi->back;
13156         struct i40e_hw *hw = &pf->hw;
13157
13158         /* For simplicity, instead of removing the qp interrupt causes
13159          * from the interrupt linked list, we simply disable the interrupt, and
13160          * leave the list intact.
13161          *
13162          * All rings in a qp belong to the same qvector.
13163          */
13164         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
13165                 u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
13166
13167                 wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
13168                 i40e_flush(hw);
13169                 synchronize_irq(pf->msix_entries[intpf].vector);
13170         } else {
13171                 /* Legacy and MSI mode - this stops all interrupt handling */
13172                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
13173                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
13174                 i40e_flush(hw);
13175                 synchronize_irq(pf->pdev->irq);
13176         }
13177 }
13178
13179 /**
13180  * i40e_queue_pair_disable - Disables a queue pair
13181  * @vsi: vsi
13182  * @queue_pair: queue pair
13183  *
13184  * Returns 0 on success, <0 on failure.
13185  **/
13186 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
13187 {
13188         int err;
13189
13190         err = i40e_enter_busy_conf(vsi);
13191         if (err)
13192                 return err;
13193
13194         i40e_queue_pair_disable_irq(vsi, queue_pair);
13195         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
13196         i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
13197         i40e_queue_pair_clean_rings(vsi, queue_pair);
13198         i40e_queue_pair_reset_stats(vsi, queue_pair);
13199
13200         return err;
13201 }
13202
13203 /**
13204  * i40e_queue_pair_enable - Enables a queue pair
13205  * @vsi: vsi
13206  * @queue_pair: queue pair
13207  *
13208  * Returns 0 on success, <0 on failure.
13209  **/
13210 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
13211 {
13212         int err;
13213
13214         err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
13215         if (err)
13216                 return err;
13217
13218         if (i40e_enabled_xdp_vsi(vsi)) {
13219                 err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
13220                 if (err)
13221                         return err;
13222         }
13223
13224         err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
13225         if (err)
13226                 return err;
13227
13228         err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
13229         i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
13230         i40e_queue_pair_enable_irq(vsi, queue_pair);
13231
13232         i40e_exit_busy_conf(vsi);
13233
13234         return err;
13235 }
13236
13237 /**
13238  * i40e_xdp - implements ndo_bpf for i40e
13239  * @dev: netdevice
13240  * @xdp: XDP command
13241  **/
13242 static int i40e_xdp(struct net_device *dev,
13243                     struct netdev_bpf *xdp)
13244 {
13245         struct i40e_netdev_priv *np = netdev_priv(dev);
13246         struct i40e_vsi *vsi = np->vsi;
13247
13248         if (vsi->type != I40E_VSI_MAIN)
13249                 return -EINVAL;
13250
13251         switch (xdp->command) {
13252         case XDP_SETUP_PROG:
13253                 return i40e_xdp_setup(vsi, xdp->prog, xdp->extack);
13254         case XDP_SETUP_XSK_POOL:
13255                 return i40e_xsk_pool_setup(vsi, xdp->xsk.pool,
13256                                            xdp->xsk.queue_id);
13257         default:
13258                 return -EINVAL;
13259         }
13260 }
13261
13262 static const struct net_device_ops i40e_netdev_ops = {
13263         .ndo_open               = i40e_open,
13264         .ndo_stop               = i40e_close,
13265         .ndo_start_xmit         = i40e_lan_xmit_frame,
13266         .ndo_get_stats64        = i40e_get_netdev_stats_struct,
13267         .ndo_set_rx_mode        = i40e_set_rx_mode,
13268         .ndo_validate_addr      = eth_validate_addr,
13269         .ndo_set_mac_address    = i40e_set_mac,
13270         .ndo_change_mtu         = i40e_change_mtu,
13271         .ndo_eth_ioctl          = i40e_ioctl,
13272         .ndo_tx_timeout         = i40e_tx_timeout,
13273         .ndo_vlan_rx_add_vid    = i40e_vlan_rx_add_vid,
13274         .ndo_vlan_rx_kill_vid   = i40e_vlan_rx_kill_vid,
13275 #ifdef CONFIG_NET_POLL_CONTROLLER
13276         .ndo_poll_controller    = i40e_netpoll,
13277 #endif
13278         .ndo_setup_tc           = __i40e_setup_tc,
13279         .ndo_select_queue       = i40e_lan_select_queue,
13280         .ndo_set_features       = i40e_set_features,
13281         .ndo_set_vf_mac         = i40e_ndo_set_vf_mac,
13282         .ndo_set_vf_vlan        = i40e_ndo_set_vf_port_vlan,
13283         .ndo_get_vf_stats       = i40e_get_vf_stats,
13284         .ndo_set_vf_rate        = i40e_ndo_set_vf_bw,
13285         .ndo_get_vf_config      = i40e_ndo_get_vf_config,
13286         .ndo_set_vf_link_state  = i40e_ndo_set_vf_link_state,
13287         .ndo_set_vf_spoofchk    = i40e_ndo_set_vf_spoofchk,
13288         .ndo_set_vf_trust       = i40e_ndo_set_vf_trust,
13289         .ndo_get_phys_port_id   = i40e_get_phys_port_id,
13290         .ndo_fdb_add            = i40e_ndo_fdb_add,
13291         .ndo_features_check     = i40e_features_check,
13292         .ndo_bridge_getlink     = i40e_ndo_bridge_getlink,
13293         .ndo_bridge_setlink     = i40e_ndo_bridge_setlink,
13294         .ndo_bpf                = i40e_xdp,
13295         .ndo_xdp_xmit           = i40e_xdp_xmit,
13296         .ndo_xsk_wakeup         = i40e_xsk_wakeup,
13297         .ndo_dfwd_add_station   = i40e_fwd_add,
13298         .ndo_dfwd_del_station   = i40e_fwd_del,
13299 };
13300
13301 /**
13302  * i40e_config_netdev - Setup the netdev flags
13303  * @vsi: the VSI being configured
13304  *
13305  * Returns 0 on success, negative value on failure
13306  **/
13307 static int i40e_config_netdev(struct i40e_vsi *vsi)
13308 {
13309         struct i40e_pf *pf = vsi->back;
13310         struct i40e_hw *hw = &pf->hw;
13311         struct i40e_netdev_priv *np;
13312         struct net_device *netdev;
13313         u8 broadcast[ETH_ALEN];
13314         u8 mac_addr[ETH_ALEN];
13315         int etherdev_size;
13316         netdev_features_t hw_enc_features;
13317         netdev_features_t hw_features;
13318
13319         etherdev_size = sizeof(struct i40e_netdev_priv);
13320         netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
13321         if (!netdev)
13322                 return -ENOMEM;
13323
13324         vsi->netdev = netdev;
13325         np = netdev_priv(netdev);
13326         np->vsi = vsi;
13327
13328         hw_enc_features = NETIF_F_SG                    |
13329                           NETIF_F_IP_CSUM               |
13330                           NETIF_F_IPV6_CSUM             |
13331                           NETIF_F_HIGHDMA               |
13332                           NETIF_F_SOFT_FEATURES         |
13333                           NETIF_F_TSO                   |
13334                           NETIF_F_TSO_ECN               |
13335                           NETIF_F_TSO6                  |
13336                           NETIF_F_GSO_GRE               |
13337                           NETIF_F_GSO_GRE_CSUM          |
13338                           NETIF_F_GSO_PARTIAL           |
13339                           NETIF_F_GSO_IPXIP4            |
13340                           NETIF_F_GSO_IPXIP6            |
13341                           NETIF_F_GSO_UDP_TUNNEL        |
13342                           NETIF_F_GSO_UDP_TUNNEL_CSUM   |
13343                           NETIF_F_GSO_UDP_L4            |
13344                           NETIF_F_SCTP_CRC              |
13345                           NETIF_F_RXHASH                |
13346                           NETIF_F_RXCSUM                |
13347                           0;
13348
13349         if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
13350                 netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
13351
13352         netdev->udp_tunnel_nic_info = &pf->udp_tunnel_nic;
13353
13354         netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
13355
13356         netdev->hw_enc_features |= hw_enc_features;
13357
13358         /* record features VLANs can make use of */
13359         netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
13360
13361         /* enable macvlan offloads */
13362         netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
13363
13364         hw_features = hw_enc_features           |
13365                       NETIF_F_HW_VLAN_CTAG_TX   |
13366                       NETIF_F_HW_VLAN_CTAG_RX;
13367
13368         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
13369                 hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
13370
13371         netdev->hw_features |= hw_features;
13372
13373         netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
13374         netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
13375
13376         if (vsi->type == I40E_VSI_MAIN) {
13377                 SET_NETDEV_DEV(netdev, &pf->pdev->dev);
13378                 ether_addr_copy(mac_addr, hw->mac.perm_addr);
13379                 /* The following steps are necessary for two reasons. First,
13380                  * some older NVM configurations load a default MAC-VLAN
13381                  * filter that will accept any tagged packet, and we want to
13382                  * replace this with a normal filter. Additionally, it is
13383                  * possible our MAC address was provided by the platform using
13384                  * Open Firmware or similar.
13385                  *
13386                  * Thus, we need to remove the default filter and install one
13387                  * specific to the MAC address.
13388                  */
13389                 i40e_rm_default_mac_filter(vsi, mac_addr);
13390                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13391                 i40e_add_mac_filter(vsi, mac_addr);
13392                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13393         } else {
13394                 /* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
13395                  * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
13396                  * the end, which is 4 bytes long, so force truncation of the
13397                  * original name by IFNAMSIZ - 4
13398                  */
13399                 snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
13400                          IFNAMSIZ - 4,
13401                          pf->vsi[pf->lan_vsi]->netdev->name);
13402                 eth_random_addr(mac_addr);
13403
13404                 spin_lock_bh(&vsi->mac_filter_hash_lock);
13405                 i40e_add_mac_filter(vsi, mac_addr);
13406                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
13407         }
13408
13409         /* Add the broadcast filter so that we initially will receive
13410          * broadcast packets. Note that when a new VLAN is first added the
13411          * driver will convert all filters marked I40E_VLAN_ANY into VLAN
13412          * specific filters as part of transitioning into "vlan" operation.
13413          * When more VLANs are added, the driver will copy each existing MAC
13414          * filter and add it for the new VLAN.
13415          *
13416          * Broadcast filters are handled specially by
13417          * i40e_sync_filters_subtask, as the driver must to set the broadcast
13418          * promiscuous bit instead of adding this directly as a MAC/VLAN
13419          * filter. The subtask will update the correct broadcast promiscuous
13420          * bits as VLANs become active or inactive.
13421          */
13422         eth_broadcast_addr(broadcast);
13423         spin_lock_bh(&vsi->mac_filter_hash_lock);
13424         i40e_add_mac_filter(vsi, broadcast);
13425         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13426
13427         ether_addr_copy(netdev->dev_addr, mac_addr);
13428         ether_addr_copy(netdev->perm_addr, mac_addr);
13429
13430         /* i40iw_net_event() reads 16 bytes from neigh->primary_key */
13431         netdev->neigh_priv_len = sizeof(u32) * 4;
13432
13433         netdev->priv_flags |= IFF_UNICAST_FLT;
13434         netdev->priv_flags |= IFF_SUPP_NOFCS;
13435         /* Setup netdev TC information */
13436         i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
13437
13438         netdev->netdev_ops = &i40e_netdev_ops;
13439         netdev->watchdog_timeo = 5 * HZ;
13440         i40e_set_ethtool_ops(netdev);
13441
13442         /* MTU range: 68 - 9706 */
13443         netdev->min_mtu = ETH_MIN_MTU;
13444         netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13445
13446         return 0;
13447 }
13448
13449 /**
13450  * i40e_vsi_delete - Delete a VSI from the switch
13451  * @vsi: the VSI being removed
13452  *
13453  * Returns 0 on success, negative value on failure
13454  **/
13455 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13456 {
13457         /* remove default VSI is not allowed */
13458         if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13459                 return;
13460
13461         i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13462 }
13463
13464 /**
13465  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13466  * @vsi: the VSI being queried
13467  *
13468  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13469  **/
13470 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13471 {
13472         struct i40e_veb *veb;
13473         struct i40e_pf *pf = vsi->back;
13474
13475         /* Uplink is not a bridge so default to VEB */
13476         if (vsi->veb_idx >= I40E_MAX_VEB)
13477                 return 1;
13478
13479         veb = pf->veb[vsi->veb_idx];
13480         if (!veb) {
13481                 dev_info(&pf->pdev->dev,
13482                          "There is no veb associated with the bridge\n");
13483                 return -ENOENT;
13484         }
13485
13486         /* Uplink is a bridge in VEPA mode */
13487         if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13488                 return 0;
13489         } else {
13490                 /* Uplink is a bridge in VEB mode */
13491                 return 1;
13492         }
13493
13494         /* VEPA is now default bridge, so return 0 */
13495         return 0;
13496 }
13497
13498 /**
13499  * i40e_add_vsi - Add a VSI to the switch
13500  * @vsi: the VSI being configured
13501  *
13502  * This initializes a VSI context depending on the VSI type to be added and
13503  * passes it down to the add_vsi aq command.
13504  **/
13505 static int i40e_add_vsi(struct i40e_vsi *vsi)
13506 {
13507         int ret = -ENODEV;
13508         struct i40e_pf *pf = vsi->back;
13509         struct i40e_hw *hw = &pf->hw;
13510         struct i40e_vsi_context ctxt;
13511         struct i40e_mac_filter *f;
13512         struct hlist_node *h;
13513         int bkt;
13514
13515         u8 enabled_tc = 0x1; /* TC0 enabled */
13516         int f_count = 0;
13517
13518         memset(&ctxt, 0, sizeof(ctxt));
13519         switch (vsi->type) {
13520         case I40E_VSI_MAIN:
13521                 /* The PF's main VSI is already setup as part of the
13522                  * device initialization, so we'll not bother with
13523                  * the add_vsi call, but we will retrieve the current
13524                  * VSI context.
13525                  */
13526                 ctxt.seid = pf->main_vsi_seid;
13527                 ctxt.pf_num = pf->hw.pf_id;
13528                 ctxt.vf_num = 0;
13529                 ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13530                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13531                 if (ret) {
13532                         dev_info(&pf->pdev->dev,
13533                                  "couldn't get PF vsi config, err %s aq_err %s\n",
13534                                  i40e_stat_str(&pf->hw, ret),
13535                                  i40e_aq_str(&pf->hw,
13536                                              pf->hw.aq.asq_last_status));
13537                         return -ENOENT;
13538                 }
13539                 vsi->info = ctxt.info;
13540                 vsi->info.valid_sections = 0;
13541
13542                 vsi->seid = ctxt.seid;
13543                 vsi->id = ctxt.vsi_number;
13544
13545                 enabled_tc = i40e_pf_get_tc_map(pf);
13546
13547                 /* Source pruning is enabled by default, so the flag is
13548                  * negative logic - if it's set, we need to fiddle with
13549                  * the VSI to disable source pruning.
13550                  */
13551                 if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13552                         memset(&ctxt, 0, sizeof(ctxt));
13553                         ctxt.seid = pf->main_vsi_seid;
13554                         ctxt.pf_num = pf->hw.pf_id;
13555                         ctxt.vf_num = 0;
13556                         ctxt.info.valid_sections |=
13557                                      cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13558                         ctxt.info.switch_id =
13559                                    cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13560                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13561                         if (ret) {
13562                                 dev_info(&pf->pdev->dev,
13563                                          "update vsi failed, err %s aq_err %s\n",
13564                                          i40e_stat_str(&pf->hw, ret),
13565                                          i40e_aq_str(&pf->hw,
13566                                                      pf->hw.aq.asq_last_status));
13567                                 ret = -ENOENT;
13568                                 goto err;
13569                         }
13570                 }
13571
13572                 /* MFP mode setup queue map and update VSI */
13573                 if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
13574                     !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13575                         memset(&ctxt, 0, sizeof(ctxt));
13576                         ctxt.seid = pf->main_vsi_seid;
13577                         ctxt.pf_num = pf->hw.pf_id;
13578                         ctxt.vf_num = 0;
13579                         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13580                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13581                         if (ret) {
13582                                 dev_info(&pf->pdev->dev,
13583                                          "update vsi failed, err %s aq_err %s\n",
13584                                          i40e_stat_str(&pf->hw, ret),
13585                                          i40e_aq_str(&pf->hw,
13586                                                     pf->hw.aq.asq_last_status));
13587                                 ret = -ENOENT;
13588                                 goto err;
13589                         }
13590                         /* update the local VSI info queue map */
13591                         i40e_vsi_update_queue_map(vsi, &ctxt);
13592                         vsi->info.valid_sections = 0;
13593                 } else {
13594                         /* Default/Main VSI is only enabled for TC0
13595                          * reconfigure it to enable all TCs that are
13596                          * available on the port in SFP mode.
13597                          * For MFP case the iSCSI PF would use this
13598                          * flow to enable LAN+iSCSI TC.
13599                          */
13600                         ret = i40e_vsi_config_tc(vsi, enabled_tc);
13601                         if (ret) {
13602                                 /* Single TC condition is not fatal,
13603                                  * message and continue
13604                                  */
13605                                 dev_info(&pf->pdev->dev,
13606                                          "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
13607                                          enabled_tc,
13608                                          i40e_stat_str(&pf->hw, ret),
13609                                          i40e_aq_str(&pf->hw,
13610                                                     pf->hw.aq.asq_last_status));
13611                         }
13612                 }
13613                 break;
13614
13615         case I40E_VSI_FDIR:
13616                 ctxt.pf_num = hw->pf_id;
13617                 ctxt.vf_num = 0;
13618                 ctxt.uplink_seid = vsi->uplink_seid;
13619                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13620                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13621                 if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
13622                     (i40e_is_vsi_uplink_mode_veb(vsi))) {
13623                         ctxt.info.valid_sections |=
13624                              cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13625                         ctxt.info.switch_id =
13626                            cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13627                 }
13628                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13629                 break;
13630
13631         case I40E_VSI_VMDQ2:
13632                 ctxt.pf_num = hw->pf_id;
13633                 ctxt.vf_num = 0;
13634                 ctxt.uplink_seid = vsi->uplink_seid;
13635                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13636                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13637
13638                 /* This VSI is connected to VEB so the switch_id
13639                  * should be set to zero by default.
13640                  */
13641                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13642                         ctxt.info.valid_sections |=
13643                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13644                         ctxt.info.switch_id =
13645                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13646                 }
13647
13648                 /* Setup the VSI tx/rx queue map for TC0 only for now */
13649                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13650                 break;
13651
13652         case I40E_VSI_SRIOV:
13653                 ctxt.pf_num = hw->pf_id;
13654                 ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
13655                 ctxt.uplink_seid = vsi->uplink_seid;
13656                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13657                 ctxt.flags = I40E_AQ_VSI_TYPE_VF;
13658
13659                 /* This VSI is connected to VEB so the switch_id
13660                  * should be set to zero by default.
13661                  */
13662                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13663                         ctxt.info.valid_sections |=
13664                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13665                         ctxt.info.switch_id =
13666                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13667                 }
13668
13669                 if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
13670                         ctxt.info.valid_sections |=
13671                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
13672                         ctxt.info.queueing_opt_flags |=
13673                                 (I40E_AQ_VSI_QUE_OPT_TCP_ENA |
13674                                  I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
13675                 }
13676
13677                 ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
13678                 ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
13679                 if (pf->vf[vsi->vf_id].spoofchk) {
13680                         ctxt.info.valid_sections |=
13681                                 cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
13682                         ctxt.info.sec_flags |=
13683                                 (I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
13684                                  I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
13685                 }
13686                 /* Setup the VSI tx/rx queue map for TC0 only for now */
13687                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13688                 break;
13689
13690         case I40E_VSI_IWARP:
13691                 /* send down message to iWARP */
13692                 break;
13693
13694         default:
13695                 return -ENODEV;
13696         }
13697
13698         if (vsi->type != I40E_VSI_MAIN) {
13699                 ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
13700                 if (ret) {
13701                         dev_info(&vsi->back->pdev->dev,
13702                                  "add vsi failed, err %s aq_err %s\n",
13703                                  i40e_stat_str(&pf->hw, ret),
13704                                  i40e_aq_str(&pf->hw,
13705                                              pf->hw.aq.asq_last_status));
13706                         ret = -ENOENT;
13707                         goto err;
13708                 }
13709                 vsi->info = ctxt.info;
13710                 vsi->info.valid_sections = 0;
13711                 vsi->seid = ctxt.seid;
13712                 vsi->id = ctxt.vsi_number;
13713         }
13714
13715         vsi->active_filters = 0;
13716         clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
13717         spin_lock_bh(&vsi->mac_filter_hash_lock);
13718         /* If macvlan filters already exist, force them to get loaded */
13719         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
13720                 f->state = I40E_FILTER_NEW;
13721                 f_count++;
13722         }
13723         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13724
13725         if (f_count) {
13726                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
13727                 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
13728         }
13729
13730         /* Update VSI BW information */
13731         ret = i40e_vsi_get_bw_info(vsi);
13732         if (ret) {
13733                 dev_info(&pf->pdev->dev,
13734                          "couldn't get vsi bw info, err %s aq_err %s\n",
13735                          i40e_stat_str(&pf->hw, ret),
13736                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13737                 /* VSI is already added so not tearing that up */
13738                 ret = 0;
13739         }
13740
13741 err:
13742         return ret;
13743 }
13744
13745 /**
13746  * i40e_vsi_release - Delete a VSI and free its resources
13747  * @vsi: the VSI being removed
13748  *
13749  * Returns 0 on success or < 0 on error
13750  **/
13751 int i40e_vsi_release(struct i40e_vsi *vsi)
13752 {
13753         struct i40e_mac_filter *f;
13754         struct hlist_node *h;
13755         struct i40e_veb *veb = NULL;
13756         struct i40e_pf *pf;
13757         u16 uplink_seid;
13758         int i, n, bkt;
13759
13760         pf = vsi->back;
13761
13762         /* release of a VEB-owner or last VSI is not allowed */
13763         if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
13764                 dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
13765                          vsi->seid, vsi->uplink_seid);
13766                 return -ENODEV;
13767         }
13768         if (vsi == pf->vsi[pf->lan_vsi] &&
13769             !test_bit(__I40E_DOWN, pf->state)) {
13770                 dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
13771                 return -ENODEV;
13772         }
13773
13774         uplink_seid = vsi->uplink_seid;
13775         if (vsi->type != I40E_VSI_SRIOV) {
13776                 if (vsi->netdev_registered) {
13777                         vsi->netdev_registered = false;
13778                         if (vsi->netdev) {
13779                                 /* results in a call to i40e_close() */
13780                                 unregister_netdev(vsi->netdev);
13781                         }
13782                 } else {
13783                         i40e_vsi_close(vsi);
13784                 }
13785                 i40e_vsi_disable_irq(vsi);
13786         }
13787
13788         spin_lock_bh(&vsi->mac_filter_hash_lock);
13789
13790         /* clear the sync flag on all filters */
13791         if (vsi->netdev) {
13792                 __dev_uc_unsync(vsi->netdev, NULL);
13793                 __dev_mc_unsync(vsi->netdev, NULL);
13794         }
13795
13796         /* make sure any remaining filters are marked for deletion */
13797         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
13798                 __i40e_del_filter(vsi, f);
13799
13800         spin_unlock_bh(&vsi->mac_filter_hash_lock);
13801
13802         i40e_sync_vsi_filters(vsi);
13803
13804         i40e_vsi_delete(vsi);
13805         i40e_vsi_free_q_vectors(vsi);
13806         if (vsi->netdev) {
13807                 free_netdev(vsi->netdev);
13808                 vsi->netdev = NULL;
13809         }
13810         i40e_vsi_clear_rings(vsi);
13811         i40e_vsi_clear(vsi);
13812
13813         /* If this was the last thing on the VEB, except for the
13814          * controlling VSI, remove the VEB, which puts the controlling
13815          * VSI onto the next level down in the switch.
13816          *
13817          * Well, okay, there's one more exception here: don't remove
13818          * the orphan VEBs yet.  We'll wait for an explicit remove request
13819          * from up the network stack.
13820          */
13821         for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
13822                 if (pf->vsi[i] &&
13823                     pf->vsi[i]->uplink_seid == uplink_seid &&
13824                     (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
13825                         n++;      /* count the VSIs */
13826                 }
13827         }
13828         for (i = 0; i < I40E_MAX_VEB; i++) {
13829                 if (!pf->veb[i])
13830                         continue;
13831                 if (pf->veb[i]->uplink_seid == uplink_seid)
13832                         n++;     /* count the VEBs */
13833                 if (pf->veb[i]->seid == uplink_seid)
13834                         veb = pf->veb[i];
13835         }
13836         if (n == 0 && veb && veb->uplink_seid != 0)
13837                 i40e_veb_release(veb);
13838
13839         return 0;
13840 }
13841
13842 /**
13843  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
13844  * @vsi: ptr to the VSI
13845  *
13846  * This should only be called after i40e_vsi_mem_alloc() which allocates the
13847  * corresponding SW VSI structure and initializes num_queue_pairs for the
13848  * newly allocated VSI.
13849  *
13850  * Returns 0 on success or negative on failure
13851  **/
13852 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
13853 {
13854         int ret = -ENOENT;
13855         struct i40e_pf *pf = vsi->back;
13856
13857         if (vsi->q_vectors[0]) {
13858                 dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
13859                          vsi->seid);
13860                 return -EEXIST;
13861         }
13862
13863         if (vsi->base_vector) {
13864                 dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
13865                          vsi->seid, vsi->base_vector);
13866                 return -EEXIST;
13867         }
13868
13869         ret = i40e_vsi_alloc_q_vectors(vsi);
13870         if (ret) {
13871                 dev_info(&pf->pdev->dev,
13872                          "failed to allocate %d q_vector for VSI %d, ret=%d\n",
13873                          vsi->num_q_vectors, vsi->seid, ret);
13874                 vsi->num_q_vectors = 0;
13875                 goto vector_setup_out;
13876         }
13877
13878         /* In Legacy mode, we do not have to get any other vector since we
13879          * piggyback on the misc/ICR0 for queue interrupts.
13880         */
13881         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
13882                 return ret;
13883         if (vsi->num_q_vectors)
13884                 vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
13885                                                  vsi->num_q_vectors, vsi->idx);
13886         if (vsi->base_vector < 0) {
13887                 dev_info(&pf->pdev->dev,
13888                          "failed to get tracking for %d vectors for VSI %d, err=%d\n",
13889                          vsi->num_q_vectors, vsi->seid, vsi->base_vector);
13890                 i40e_vsi_free_q_vectors(vsi);
13891                 ret = -ENOENT;
13892                 goto vector_setup_out;
13893         }
13894
13895 vector_setup_out:
13896         return ret;
13897 }
13898
13899 /**
13900  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
13901  * @vsi: pointer to the vsi.
13902  *
13903  * This re-allocates a vsi's queue resources.
13904  *
13905  * Returns pointer to the successfully allocated and configured VSI sw struct
13906  * on success, otherwise returns NULL on failure.
13907  **/
13908 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
13909 {
13910         u16 alloc_queue_pairs;
13911         struct i40e_pf *pf;
13912         u8 enabled_tc;
13913         int ret;
13914
13915         if (!vsi)
13916                 return NULL;
13917
13918         pf = vsi->back;
13919
13920         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
13921         i40e_vsi_clear_rings(vsi);
13922
13923         i40e_vsi_free_arrays(vsi, false);
13924         i40e_set_num_rings_in_vsi(vsi);
13925         ret = i40e_vsi_alloc_arrays(vsi, false);
13926         if (ret)
13927                 goto err_vsi;
13928
13929         alloc_queue_pairs = vsi->alloc_queue_pairs *
13930                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
13931
13932         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
13933         if (ret < 0) {
13934                 dev_info(&pf->pdev->dev,
13935                          "failed to get tracking for %d queues for VSI %d err %d\n",
13936                          alloc_queue_pairs, vsi->seid, ret);
13937                 goto err_vsi;
13938         }
13939         vsi->base_queue = ret;
13940
13941         /* Update the FW view of the VSI. Force a reset of TC and queue
13942          * layout configurations.
13943          */
13944         enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
13945         pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
13946         pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
13947         i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
13948         if (vsi->type == I40E_VSI_MAIN)
13949                 i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
13950
13951         /* assign it some queues */
13952         ret = i40e_alloc_rings(vsi);
13953         if (ret)
13954                 goto err_rings;
13955
13956         /* map all of the rings to the q_vectors */
13957         i40e_vsi_map_rings_to_vectors(vsi);
13958         return vsi;
13959
13960 err_rings:
13961         i40e_vsi_free_q_vectors(vsi);
13962         if (vsi->netdev_registered) {
13963                 vsi->netdev_registered = false;
13964                 unregister_netdev(vsi->netdev);
13965                 free_netdev(vsi->netdev);
13966                 vsi->netdev = NULL;
13967         }
13968         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
13969 err_vsi:
13970         i40e_vsi_clear(vsi);
13971         return NULL;
13972 }
13973
13974 /**
13975  * i40e_vsi_setup - Set up a VSI by a given type
13976  * @pf: board private structure
13977  * @type: VSI type
13978  * @uplink_seid: the switch element to link to
13979  * @param1: usage depends upon VSI type. For VF types, indicates VF id
13980  *
13981  * This allocates the sw VSI structure and its queue resources, then add a VSI
13982  * to the identified VEB.
13983  *
13984  * Returns pointer to the successfully allocated and configure VSI sw struct on
13985  * success, otherwise returns NULL on failure.
13986  **/
13987 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
13988                                 u16 uplink_seid, u32 param1)
13989 {
13990         struct i40e_vsi *vsi = NULL;
13991         struct i40e_veb *veb = NULL;
13992         u16 alloc_queue_pairs;
13993         int ret, i;
13994         int v_idx;
13995
13996         /* The requested uplink_seid must be either
13997          *     - the PF's port seid
13998          *              no VEB is needed because this is the PF
13999          *              or this is a Flow Director special case VSI
14000          *     - seid of an existing VEB
14001          *     - seid of a VSI that owns an existing VEB
14002          *     - seid of a VSI that doesn't own a VEB
14003          *              a new VEB is created and the VSI becomes the owner
14004          *     - seid of the PF VSI, which is what creates the first VEB
14005          *              this is a special case of the previous
14006          *
14007          * Find which uplink_seid we were given and create a new VEB if needed
14008          */
14009         for (i = 0; i < I40E_MAX_VEB; i++) {
14010                 if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
14011                         veb = pf->veb[i];
14012                         break;
14013                 }
14014         }
14015
14016         if (!veb && uplink_seid != pf->mac_seid) {
14017
14018                 for (i = 0; i < pf->num_alloc_vsi; i++) {
14019                         if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
14020                                 vsi = pf->vsi[i];
14021                                 break;
14022                         }
14023                 }
14024                 if (!vsi) {
14025                         dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
14026                                  uplink_seid);
14027                         return NULL;
14028                 }
14029
14030                 if (vsi->uplink_seid == pf->mac_seid)
14031                         veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
14032                                              vsi->tc_config.enabled_tc);
14033                 else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
14034                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
14035                                              vsi->tc_config.enabled_tc);
14036                 if (veb) {
14037                         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
14038                                 dev_info(&vsi->back->pdev->dev,
14039                                          "New VSI creation error, uplink seid of LAN VSI expected.\n");
14040                                 return NULL;
14041                         }
14042                         /* We come up by default in VEPA mode if SRIOV is not
14043                          * already enabled, in which case we can't force VEPA
14044                          * mode.
14045                          */
14046                         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
14047                                 veb->bridge_mode = BRIDGE_MODE_VEPA;
14048                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
14049                         }
14050                         i40e_config_bridge_mode(veb);
14051                 }
14052                 for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
14053                         if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
14054                                 veb = pf->veb[i];
14055                 }
14056                 if (!veb) {
14057                         dev_info(&pf->pdev->dev, "couldn't add VEB\n");
14058                         return NULL;
14059                 }
14060
14061                 vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14062                 uplink_seid = veb->seid;
14063         }
14064
14065         /* get vsi sw struct */
14066         v_idx = i40e_vsi_mem_alloc(pf, type);
14067         if (v_idx < 0)
14068                 goto err_alloc;
14069         vsi = pf->vsi[v_idx];
14070         if (!vsi)
14071                 goto err_alloc;
14072         vsi->type = type;
14073         vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
14074
14075         if (type == I40E_VSI_MAIN)
14076                 pf->lan_vsi = v_idx;
14077         else if (type == I40E_VSI_SRIOV)
14078                 vsi->vf_id = param1;
14079         /* assign it some queues */
14080         alloc_queue_pairs = vsi->alloc_queue_pairs *
14081                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
14082
14083         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
14084         if (ret < 0) {
14085                 dev_info(&pf->pdev->dev,
14086                          "failed to get tracking for %d queues for VSI %d err=%d\n",
14087                          alloc_queue_pairs, vsi->seid, ret);
14088                 goto err_vsi;
14089         }
14090         vsi->base_queue = ret;
14091
14092         /* get a VSI from the hardware */
14093         vsi->uplink_seid = uplink_seid;
14094         ret = i40e_add_vsi(vsi);
14095         if (ret)
14096                 goto err_vsi;
14097
14098         switch (vsi->type) {
14099         /* setup the netdev if needed */
14100         case I40E_VSI_MAIN:
14101         case I40E_VSI_VMDQ2:
14102                 ret = i40e_config_netdev(vsi);
14103                 if (ret)
14104                         goto err_netdev;
14105                 ret = register_netdev(vsi->netdev);
14106                 if (ret)
14107                         goto err_netdev;
14108                 vsi->netdev_registered = true;
14109                 netif_carrier_off(vsi->netdev);
14110 #ifdef CONFIG_I40E_DCB
14111                 /* Setup DCB netlink interface */
14112                 i40e_dcbnl_setup(vsi);
14113 #endif /* CONFIG_I40E_DCB */
14114                 fallthrough;
14115         case I40E_VSI_FDIR:
14116                 /* set up vectors and rings if needed */
14117                 ret = i40e_vsi_setup_vectors(vsi);
14118                 if (ret)
14119                         goto err_msix;
14120
14121                 ret = i40e_alloc_rings(vsi);
14122                 if (ret)
14123                         goto err_rings;
14124
14125                 /* map all of the rings to the q_vectors */
14126                 i40e_vsi_map_rings_to_vectors(vsi);
14127
14128                 i40e_vsi_reset_stats(vsi);
14129                 break;
14130         default:
14131                 /* no netdev or rings for the other VSI types */
14132                 break;
14133         }
14134
14135         if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
14136             (vsi->type == I40E_VSI_VMDQ2)) {
14137                 ret = i40e_vsi_config_rss(vsi);
14138         }
14139         return vsi;
14140
14141 err_rings:
14142         i40e_vsi_free_q_vectors(vsi);
14143 err_msix:
14144         if (vsi->netdev_registered) {
14145                 vsi->netdev_registered = false;
14146                 unregister_netdev(vsi->netdev);
14147                 free_netdev(vsi->netdev);
14148                 vsi->netdev = NULL;
14149         }
14150 err_netdev:
14151         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
14152 err_vsi:
14153         i40e_vsi_clear(vsi);
14154 err_alloc:
14155         return NULL;
14156 }
14157
14158 /**
14159  * i40e_veb_get_bw_info - Query VEB BW information
14160  * @veb: the veb to query
14161  *
14162  * Query the Tx scheduler BW configuration data for given VEB
14163  **/
14164 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
14165 {
14166         struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
14167         struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
14168         struct i40e_pf *pf = veb->pf;
14169         struct i40e_hw *hw = &pf->hw;
14170         u32 tc_bw_max;
14171         int ret = 0;
14172         int i;
14173
14174         ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
14175                                                   &bw_data, NULL);
14176         if (ret) {
14177                 dev_info(&pf->pdev->dev,
14178                          "query veb bw config failed, err %s aq_err %s\n",
14179                          i40e_stat_str(&pf->hw, ret),
14180                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14181                 goto out;
14182         }
14183
14184         ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
14185                                                    &ets_data, NULL);
14186         if (ret) {
14187                 dev_info(&pf->pdev->dev,
14188                          "query veb bw ets config failed, err %s aq_err %s\n",
14189                          i40e_stat_str(&pf->hw, ret),
14190                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
14191                 goto out;
14192         }
14193
14194         veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
14195         veb->bw_max_quanta = ets_data.tc_bw_max;
14196         veb->is_abs_credits = bw_data.absolute_credits_enable;
14197         veb->enabled_tc = ets_data.tc_valid_bits;
14198         tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
14199                     (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
14200         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
14201                 veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
14202                 veb->bw_tc_limit_credits[i] =
14203                                         le16_to_cpu(bw_data.tc_bw_limits[i]);
14204                 veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
14205         }
14206
14207 out:
14208         return ret;
14209 }
14210
14211 /**
14212  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
14213  * @pf: board private structure
14214  *
14215  * On error: returns error code (negative)
14216  * On success: returns vsi index in PF (positive)
14217  **/
14218 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
14219 {
14220         int ret = -ENOENT;
14221         struct i40e_veb *veb;
14222         int i;
14223
14224         /* Need to protect the allocation of switch elements at the PF level */
14225         mutex_lock(&pf->switch_mutex);
14226
14227         /* VEB list may be fragmented if VEB creation/destruction has
14228          * been happening.  We can afford to do a quick scan to look
14229          * for any free slots in the list.
14230          *
14231          * find next empty veb slot, looping back around if necessary
14232          */
14233         i = 0;
14234         while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
14235                 i++;
14236         if (i >= I40E_MAX_VEB) {
14237                 ret = -ENOMEM;
14238                 goto err_alloc_veb;  /* out of VEB slots! */
14239         }
14240
14241         veb = kzalloc(sizeof(*veb), GFP_KERNEL);
14242         if (!veb) {
14243                 ret = -ENOMEM;
14244                 goto err_alloc_veb;
14245         }
14246         veb->pf = pf;
14247         veb->idx = i;
14248         veb->enabled_tc = 1;
14249
14250         pf->veb[i] = veb;
14251         ret = i;
14252 err_alloc_veb:
14253         mutex_unlock(&pf->switch_mutex);
14254         return ret;
14255 }
14256
14257 /**
14258  * i40e_switch_branch_release - Delete a branch of the switch tree
14259  * @branch: where to start deleting
14260  *
14261  * This uses recursion to find the tips of the branch to be
14262  * removed, deleting until we get back to and can delete this VEB.
14263  **/
14264 static void i40e_switch_branch_release(struct i40e_veb *branch)
14265 {
14266         struct i40e_pf *pf = branch->pf;
14267         u16 branch_seid = branch->seid;
14268         u16 veb_idx = branch->idx;
14269         int i;
14270
14271         /* release any VEBs on this VEB - RECURSION */
14272         for (i = 0; i < I40E_MAX_VEB; i++) {
14273                 if (!pf->veb[i])
14274                         continue;
14275                 if (pf->veb[i]->uplink_seid == branch->seid)
14276                         i40e_switch_branch_release(pf->veb[i]);
14277         }
14278
14279         /* Release the VSIs on this VEB, but not the owner VSI.
14280          *
14281          * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
14282          *       the VEB itself, so don't use (*branch) after this loop.
14283          */
14284         for (i = 0; i < pf->num_alloc_vsi; i++) {
14285                 if (!pf->vsi[i])
14286                         continue;
14287                 if (pf->vsi[i]->uplink_seid == branch_seid &&
14288                    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
14289                         i40e_vsi_release(pf->vsi[i]);
14290                 }
14291         }
14292
14293         /* There's one corner case where the VEB might not have been
14294          * removed, so double check it here and remove it if needed.
14295          * This case happens if the veb was created from the debugfs
14296          * commands and no VSIs were added to it.
14297          */
14298         if (pf->veb[veb_idx])
14299                 i40e_veb_release(pf->veb[veb_idx]);
14300 }
14301
14302 /**
14303  * i40e_veb_clear - remove veb struct
14304  * @veb: the veb to remove
14305  **/
14306 static void i40e_veb_clear(struct i40e_veb *veb)
14307 {
14308         if (!veb)
14309                 return;
14310
14311         if (veb->pf) {
14312                 struct i40e_pf *pf = veb->pf;
14313
14314                 mutex_lock(&pf->switch_mutex);
14315                 if (pf->veb[veb->idx] == veb)
14316                         pf->veb[veb->idx] = NULL;
14317                 mutex_unlock(&pf->switch_mutex);
14318         }
14319
14320         kfree(veb);
14321 }
14322
14323 /**
14324  * i40e_veb_release - Delete a VEB and free its resources
14325  * @veb: the VEB being removed
14326  **/
14327 void i40e_veb_release(struct i40e_veb *veb)
14328 {
14329         struct i40e_vsi *vsi = NULL;
14330         struct i40e_pf *pf;
14331         int i, n = 0;
14332
14333         pf = veb->pf;
14334
14335         /* find the remaining VSI and check for extras */
14336         for (i = 0; i < pf->num_alloc_vsi; i++) {
14337                 if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
14338                         n++;
14339                         vsi = pf->vsi[i];
14340                 }
14341         }
14342         if (n != 1) {
14343                 dev_info(&pf->pdev->dev,
14344                          "can't remove VEB %d with %d VSIs left\n",
14345                          veb->seid, n);
14346                 return;
14347         }
14348
14349         /* move the remaining VSI to uplink veb */
14350         vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
14351         if (veb->uplink_seid) {
14352                 vsi->uplink_seid = veb->uplink_seid;
14353                 if (veb->uplink_seid == pf->mac_seid)
14354                         vsi->veb_idx = I40E_NO_VEB;
14355                 else
14356                         vsi->veb_idx = veb->veb_idx;
14357         } else {
14358                 /* floating VEB */
14359                 vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
14360                 vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
14361         }
14362
14363         i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14364         i40e_veb_clear(veb);
14365 }
14366
14367 /**
14368  * i40e_add_veb - create the VEB in the switch
14369  * @veb: the VEB to be instantiated
14370  * @vsi: the controlling VSI
14371  **/
14372 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
14373 {
14374         struct i40e_pf *pf = veb->pf;
14375         bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
14376         int ret;
14377
14378         ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
14379                               veb->enabled_tc, false,
14380                               &veb->seid, enable_stats, NULL);
14381
14382         /* get a VEB from the hardware */
14383         if (ret) {
14384                 dev_info(&pf->pdev->dev,
14385                          "couldn't add VEB, err %s aq_err %s\n",
14386                          i40e_stat_str(&pf->hw, ret),
14387                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14388                 return -EPERM;
14389         }
14390
14391         /* get statistics counter */
14392         ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
14393                                          &veb->stats_idx, NULL, NULL, NULL);
14394         if (ret) {
14395                 dev_info(&pf->pdev->dev,
14396                          "couldn't get VEB statistics idx, err %s aq_err %s\n",
14397                          i40e_stat_str(&pf->hw, ret),
14398                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14399                 return -EPERM;
14400         }
14401         ret = i40e_veb_get_bw_info(veb);
14402         if (ret) {
14403                 dev_info(&pf->pdev->dev,
14404                          "couldn't get VEB bw info, err %s aq_err %s\n",
14405                          i40e_stat_str(&pf->hw, ret),
14406                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14407                 i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
14408                 return -ENOENT;
14409         }
14410
14411         vsi->uplink_seid = veb->seid;
14412         vsi->veb_idx = veb->idx;
14413         vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
14414
14415         return 0;
14416 }
14417
14418 /**
14419  * i40e_veb_setup - Set up a VEB
14420  * @pf: board private structure
14421  * @flags: VEB setup flags
14422  * @uplink_seid: the switch element to link to
14423  * @vsi_seid: the initial VSI seid
14424  * @enabled_tc: Enabled TC bit-map
14425  *
14426  * This allocates the sw VEB structure and links it into the switch
14427  * It is possible and legal for this to be a duplicate of an already
14428  * existing VEB.  It is also possible for both uplink and vsi seids
14429  * to be zero, in order to create a floating VEB.
14430  *
14431  * Returns pointer to the successfully allocated VEB sw struct on
14432  * success, otherwise returns NULL on failure.
14433  **/
14434 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
14435                                 u16 uplink_seid, u16 vsi_seid,
14436                                 u8 enabled_tc)
14437 {
14438         struct i40e_veb *veb, *uplink_veb = NULL;
14439         int vsi_idx, veb_idx;
14440         int ret;
14441
14442         /* if one seid is 0, the other must be 0 to create a floating relay */
14443         if ((uplink_seid == 0 || vsi_seid == 0) &&
14444             (uplink_seid + vsi_seid != 0)) {
14445                 dev_info(&pf->pdev->dev,
14446                          "one, not both seid's are 0: uplink=%d vsi=%d\n",
14447                          uplink_seid, vsi_seid);
14448                 return NULL;
14449         }
14450
14451         /* make sure there is such a vsi and uplink */
14452         for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14453                 if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14454                         break;
14455         if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14456                 dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14457                          vsi_seid);
14458                 return NULL;
14459         }
14460
14461         if (uplink_seid && uplink_seid != pf->mac_seid) {
14462                 for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14463                         if (pf->veb[veb_idx] &&
14464                             pf->veb[veb_idx]->seid == uplink_seid) {
14465                                 uplink_veb = pf->veb[veb_idx];
14466                                 break;
14467                         }
14468                 }
14469                 if (!uplink_veb) {
14470                         dev_info(&pf->pdev->dev,
14471                                  "uplink seid %d not found\n", uplink_seid);
14472                         return NULL;
14473                 }
14474         }
14475
14476         /* get veb sw struct */
14477         veb_idx = i40e_veb_mem_alloc(pf);
14478         if (veb_idx < 0)
14479                 goto err_alloc;
14480         veb = pf->veb[veb_idx];
14481         veb->flags = flags;
14482         veb->uplink_seid = uplink_seid;
14483         veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14484         veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14485
14486         /* create the VEB in the switch */
14487         ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14488         if (ret)
14489                 goto err_veb;
14490         if (vsi_idx == pf->lan_vsi)
14491                 pf->lan_veb = veb->idx;
14492
14493         return veb;
14494
14495 err_veb:
14496         i40e_veb_clear(veb);
14497 err_alloc:
14498         return NULL;
14499 }
14500
14501 /**
14502  * i40e_setup_pf_switch_element - set PF vars based on switch type
14503  * @pf: board private structure
14504  * @ele: element we are building info from
14505  * @num_reported: total number of elements
14506  * @printconfig: should we print the contents
14507  *
14508  * helper function to assist in extracting a few useful SEID values.
14509  **/
14510 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14511                                 struct i40e_aqc_switch_config_element_resp *ele,
14512                                 u16 num_reported, bool printconfig)
14513 {
14514         u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14515         u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14516         u8 element_type = ele->element_type;
14517         u16 seid = le16_to_cpu(ele->seid);
14518
14519         if (printconfig)
14520                 dev_info(&pf->pdev->dev,
14521                          "type=%d seid=%d uplink=%d downlink=%d\n",
14522                          element_type, seid, uplink_seid, downlink_seid);
14523
14524         switch (element_type) {
14525         case I40E_SWITCH_ELEMENT_TYPE_MAC:
14526                 pf->mac_seid = seid;
14527                 break;
14528         case I40E_SWITCH_ELEMENT_TYPE_VEB:
14529                 /* Main VEB? */
14530                 if (uplink_seid != pf->mac_seid)
14531                         break;
14532                 if (pf->lan_veb >= I40E_MAX_VEB) {
14533                         int v;
14534
14535                         /* find existing or else empty VEB */
14536                         for (v = 0; v < I40E_MAX_VEB; v++) {
14537                                 if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14538                                         pf->lan_veb = v;
14539                                         break;
14540                                 }
14541                         }
14542                         if (pf->lan_veb >= I40E_MAX_VEB) {
14543                                 v = i40e_veb_mem_alloc(pf);
14544                                 if (v < 0)
14545                                         break;
14546                                 pf->lan_veb = v;
14547                         }
14548                 }
14549                 if (pf->lan_veb >= I40E_MAX_VEB)
14550                         break;
14551
14552                 pf->veb[pf->lan_veb]->seid = seid;
14553                 pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14554                 pf->veb[pf->lan_veb]->pf = pf;
14555                 pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14556                 break;
14557         case I40E_SWITCH_ELEMENT_TYPE_VSI:
14558                 if (num_reported != 1)
14559                         break;
14560                 /* This is immediately after a reset so we can assume this is
14561                  * the PF's VSI
14562                  */
14563                 pf->mac_seid = uplink_seid;
14564                 pf->pf_seid = downlink_seid;
14565                 pf->main_vsi_seid = seid;
14566                 if (printconfig)
14567                         dev_info(&pf->pdev->dev,
14568                                  "pf_seid=%d main_vsi_seid=%d\n",
14569                                  pf->pf_seid, pf->main_vsi_seid);
14570                 break;
14571         case I40E_SWITCH_ELEMENT_TYPE_PF:
14572         case I40E_SWITCH_ELEMENT_TYPE_VF:
14573         case I40E_SWITCH_ELEMENT_TYPE_EMP:
14574         case I40E_SWITCH_ELEMENT_TYPE_BMC:
14575         case I40E_SWITCH_ELEMENT_TYPE_PE:
14576         case I40E_SWITCH_ELEMENT_TYPE_PA:
14577                 /* ignore these for now */
14578                 break;
14579         default:
14580                 dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14581                          element_type, seid);
14582                 break;
14583         }
14584 }
14585
14586 /**
14587  * i40e_fetch_switch_configuration - Get switch config from firmware
14588  * @pf: board private structure
14589  * @printconfig: should we print the contents
14590  *
14591  * Get the current switch configuration from the device and
14592  * extract a few useful SEID values.
14593  **/
14594 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14595 {
14596         struct i40e_aqc_get_switch_config_resp *sw_config;
14597         u16 next_seid = 0;
14598         int ret = 0;
14599         u8 *aq_buf;
14600         int i;
14601
14602         aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14603         if (!aq_buf)
14604                 return -ENOMEM;
14605
14606         sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14607         do {
14608                 u16 num_reported, num_total;
14609
14610                 ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14611                                                 I40E_AQ_LARGE_BUF,
14612                                                 &next_seid, NULL);
14613                 if (ret) {
14614                         dev_info(&pf->pdev->dev,
14615                                  "get switch config failed err %s aq_err %s\n",
14616                                  i40e_stat_str(&pf->hw, ret),
14617                                  i40e_aq_str(&pf->hw,
14618                                              pf->hw.aq.asq_last_status));
14619                         kfree(aq_buf);
14620                         return -ENOENT;
14621                 }
14622
14623                 num_reported = le16_to_cpu(sw_config->header.num_reported);
14624                 num_total = le16_to_cpu(sw_config->header.num_total);
14625
14626                 if (printconfig)
14627                         dev_info(&pf->pdev->dev,
14628                                  "header: %d reported %d total\n",
14629                                  num_reported, num_total);
14630
14631                 for (i = 0; i < num_reported; i++) {
14632                         struct i40e_aqc_switch_config_element_resp *ele =
14633                                 &sw_config->element[i];
14634
14635                         i40e_setup_pf_switch_element(pf, ele, num_reported,
14636                                                      printconfig);
14637                 }
14638         } while (next_seid != 0);
14639
14640         kfree(aq_buf);
14641         return ret;
14642 }
14643
14644 /**
14645  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14646  * @pf: board private structure
14647  * @reinit: if the Main VSI needs to re-initialized.
14648  * @lock_acquired: indicates whether or not the lock has been acquired
14649  *
14650  * Returns 0 on success, negative value on failure
14651  **/
14652 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit, bool lock_acquired)
14653 {
14654         u16 flags = 0;
14655         int ret;
14656
14657         /* find out what's out there already */
14658         ret = i40e_fetch_switch_configuration(pf, false);
14659         if (ret) {
14660                 dev_info(&pf->pdev->dev,
14661                          "couldn't fetch switch config, err %s aq_err %s\n",
14662                          i40e_stat_str(&pf->hw, ret),
14663                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14664                 return ret;
14665         }
14666         i40e_pf_reset_stats(pf);
14667
14668         /* set the switch config bit for the whole device to
14669          * support limited promisc or true promisc
14670          * when user requests promisc. The default is limited
14671          * promisc.
14672         */
14673
14674         if ((pf->hw.pf_id == 0) &&
14675             !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
14676                 flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14677                 pf->last_sw_conf_flags = flags;
14678         }
14679
14680         if (pf->hw.pf_id == 0) {
14681                 u16 valid_flags;
14682
14683                 valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14684                 ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
14685                                                 NULL);
14686                 if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
14687                         dev_info(&pf->pdev->dev,
14688                                  "couldn't set switch config bits, err %s aq_err %s\n",
14689                                  i40e_stat_str(&pf->hw, ret),
14690                                  i40e_aq_str(&pf->hw,
14691                                              pf->hw.aq.asq_last_status));
14692                         /* not a fatal problem, just keep going */
14693                 }
14694                 pf->last_sw_conf_valid_flags = valid_flags;
14695         }
14696
14697         /* first time setup */
14698         if (pf->lan_vsi == I40E_NO_VSI || reinit) {
14699                 struct i40e_vsi *vsi = NULL;
14700                 u16 uplink_seid;
14701
14702                 /* Set up the PF VSI associated with the PF's main VSI
14703                  * that is already in the HW switch
14704                  */
14705                 if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
14706                         uplink_seid = pf->veb[pf->lan_veb]->seid;
14707                 else
14708                         uplink_seid = pf->mac_seid;
14709                 if (pf->lan_vsi == I40E_NO_VSI)
14710                         vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
14711                 else if (reinit)
14712                         vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
14713                 if (!vsi) {
14714                         dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
14715                         i40e_cloud_filter_exit(pf);
14716                         i40e_fdir_teardown(pf);
14717                         return -EAGAIN;
14718                 }
14719         } else {
14720                 /* force a reset of TC and queue layout configurations */
14721                 u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14722
14723                 pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14724                 pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14725                 i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14726         }
14727         i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
14728
14729         i40e_fdir_sb_setup(pf);
14730
14731         /* Setup static PF queue filter control settings */
14732         ret = i40e_setup_pf_filter_control(pf);
14733         if (ret) {
14734                 dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
14735                          ret);
14736                 /* Failure here should not stop continuing other steps */
14737         }
14738
14739         /* enable RSS in the HW, even for only one queue, as the stack can use
14740          * the hash
14741          */
14742         if ((pf->flags & I40E_FLAG_RSS_ENABLED))
14743                 i40e_pf_config_rss(pf);
14744
14745         /* fill in link information and enable LSE reporting */
14746         i40e_link_event(pf);
14747
14748         /* Initialize user-specific link properties */
14749         pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
14750                                   I40E_AQ_AN_COMPLETED) ? true : false);
14751
14752         i40e_ptp_init(pf);
14753
14754         if (!lock_acquired)
14755                 rtnl_lock();
14756
14757         /* repopulate tunnel port filters */
14758         udp_tunnel_nic_reset_ntf(pf->vsi[pf->lan_vsi]->netdev);
14759
14760         if (!lock_acquired)
14761                 rtnl_unlock();
14762
14763         return ret;
14764 }
14765
14766 /**
14767  * i40e_determine_queue_usage - Work out queue distribution
14768  * @pf: board private structure
14769  **/
14770 static void i40e_determine_queue_usage(struct i40e_pf *pf)
14771 {
14772         int queues_left;
14773         int q_max;
14774
14775         pf->num_lan_qps = 0;
14776
14777         /* Find the max queues to be put into basic use.  We'll always be
14778          * using TC0, whether or not DCB is running, and TC0 will get the
14779          * big RSS set.
14780          */
14781         queues_left = pf->hw.func_caps.num_tx_qp;
14782
14783         if ((queues_left == 1) ||
14784             !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
14785                 /* one qp for PF, no queues for anything else */
14786                 queues_left = 0;
14787                 pf->alloc_rss_size = pf->num_lan_qps = 1;
14788
14789                 /* make sure all the fancies are disabled */
14790                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
14791                                I40E_FLAG_IWARP_ENABLED  |
14792                                I40E_FLAG_FD_SB_ENABLED  |
14793                                I40E_FLAG_FD_ATR_ENABLED |
14794                                I40E_FLAG_DCB_CAPABLE    |
14795                                I40E_FLAG_DCB_ENABLED    |
14796                                I40E_FLAG_SRIOV_ENABLED  |
14797                                I40E_FLAG_VMDQ_ENABLED);
14798                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
14799         } else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
14800                                   I40E_FLAG_FD_SB_ENABLED |
14801                                   I40E_FLAG_FD_ATR_ENABLED |
14802                                   I40E_FLAG_DCB_CAPABLE))) {
14803                 /* one qp for PF */
14804                 pf->alloc_rss_size = pf->num_lan_qps = 1;
14805                 queues_left -= pf->num_lan_qps;
14806
14807                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
14808                                I40E_FLAG_IWARP_ENABLED  |
14809                                I40E_FLAG_FD_SB_ENABLED  |
14810                                I40E_FLAG_FD_ATR_ENABLED |
14811                                I40E_FLAG_DCB_ENABLED    |
14812                                I40E_FLAG_VMDQ_ENABLED);
14813                 pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
14814         } else {
14815                 /* Not enough queues for all TCs */
14816                 if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
14817                     (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
14818                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
14819                                         I40E_FLAG_DCB_ENABLED);
14820                         dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
14821                 }
14822
14823                 /* limit lan qps to the smaller of qps, cpus or msix */
14824                 q_max = max_t(int, pf->rss_size_max, num_online_cpus());
14825                 q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
14826                 q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
14827                 pf->num_lan_qps = q_max;
14828
14829                 queues_left -= pf->num_lan_qps;
14830         }
14831
14832         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
14833                 if (queues_left > 1) {
14834                         queues_left -= 1; /* save 1 queue for FD */
14835                 } else {
14836                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
14837                         pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
14838                         dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
14839                 }
14840         }
14841
14842         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
14843             pf->num_vf_qps && pf->num_req_vfs && queues_left) {
14844                 pf->num_req_vfs = min_t(int, pf->num_req_vfs,
14845                                         (queues_left / pf->num_vf_qps));
14846                 queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
14847         }
14848
14849         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
14850             pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
14851                 pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
14852                                           (queues_left / pf->num_vmdq_qps));
14853                 queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
14854         }
14855
14856         pf->queues_left = queues_left;
14857         dev_dbg(&pf->pdev->dev,
14858                 "qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
14859                 pf->hw.func_caps.num_tx_qp,
14860                 !!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
14861                 pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
14862                 pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
14863                 queues_left);
14864 }
14865
14866 /**
14867  * i40e_setup_pf_filter_control - Setup PF static filter control
14868  * @pf: PF to be setup
14869  *
14870  * i40e_setup_pf_filter_control sets up a PF's initial filter control
14871  * settings. If PE/FCoE are enabled then it will also set the per PF
14872  * based filter sizes required for them. It also enables Flow director,
14873  * ethertype and macvlan type filter settings for the pf.
14874  *
14875  * Returns 0 on success, negative on failure
14876  **/
14877 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
14878 {
14879         struct i40e_filter_control_settings *settings = &pf->filter_settings;
14880
14881         settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
14882
14883         /* Flow Director is enabled */
14884         if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
14885                 settings->enable_fdir = true;
14886
14887         /* Ethtype and MACVLAN filters enabled for PF */
14888         settings->enable_ethtype = true;
14889         settings->enable_macvlan = true;
14890
14891         if (i40e_set_filter_control(&pf->hw, settings))
14892                 return -ENOENT;
14893
14894         return 0;
14895 }
14896
14897 #define INFO_STRING_LEN 255
14898 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
14899 static void i40e_print_features(struct i40e_pf *pf)
14900 {
14901         struct i40e_hw *hw = &pf->hw;
14902         char *buf;
14903         int i;
14904
14905         buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
14906         if (!buf)
14907                 return;
14908
14909         i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
14910 #ifdef CONFIG_PCI_IOV
14911         i += scnprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
14912 #endif
14913         i += scnprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
14914                       pf->hw.func_caps.num_vsis,
14915                       pf->vsi[pf->lan_vsi]->num_queue_pairs);
14916         if (pf->flags & I40E_FLAG_RSS_ENABLED)
14917                 i += scnprintf(&buf[i], REMAIN(i), " RSS");
14918         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
14919                 i += scnprintf(&buf[i], REMAIN(i), " FD_ATR");
14920         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
14921                 i += scnprintf(&buf[i], REMAIN(i), " FD_SB");
14922                 i += scnprintf(&buf[i], REMAIN(i), " NTUPLE");
14923         }
14924         if (pf->flags & I40E_FLAG_DCB_CAPABLE)
14925                 i += scnprintf(&buf[i], REMAIN(i), " DCB");
14926         i += scnprintf(&buf[i], REMAIN(i), " VxLAN");
14927         i += scnprintf(&buf[i], REMAIN(i), " Geneve");
14928         if (pf->flags & I40E_FLAG_PTP)
14929                 i += scnprintf(&buf[i], REMAIN(i), " PTP");
14930         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
14931                 i += scnprintf(&buf[i], REMAIN(i), " VEB");
14932         else
14933                 i += scnprintf(&buf[i], REMAIN(i), " VEPA");
14934
14935         dev_info(&pf->pdev->dev, "%s\n", buf);
14936         kfree(buf);
14937         WARN_ON(i > INFO_STRING_LEN);
14938 }
14939
14940 /**
14941  * i40e_get_platform_mac_addr - get platform-specific MAC address
14942  * @pdev: PCI device information struct
14943  * @pf: board private structure
14944  *
14945  * Look up the MAC address for the device. First we'll try
14946  * eth_platform_get_mac_address, which will check Open Firmware, or arch
14947  * specific fallback. Otherwise, we'll default to the stored value in
14948  * firmware.
14949  **/
14950 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
14951 {
14952         if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
14953                 i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
14954 }
14955
14956 /**
14957  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
14958  * @fec_cfg: FEC option to set in flags
14959  * @flags: ptr to flags in which we set FEC option
14960  **/
14961 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
14962 {
14963         if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
14964                 *flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
14965         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
14966             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
14967                 *flags |= I40E_FLAG_RS_FEC;
14968                 *flags &= ~I40E_FLAG_BASE_R_FEC;
14969         }
14970         if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
14971             (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
14972                 *flags |= I40E_FLAG_BASE_R_FEC;
14973                 *flags &= ~I40E_FLAG_RS_FEC;
14974         }
14975         if (fec_cfg == 0)
14976                 *flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
14977 }
14978
14979 /**
14980  * i40e_check_recovery_mode - check if we are running transition firmware
14981  * @pf: board private structure
14982  *
14983  * Check registers indicating the firmware runs in recovery mode. Sets the
14984  * appropriate driver state.
14985  *
14986  * Returns true if the recovery mode was detected, false otherwise
14987  **/
14988 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
14989 {
14990         u32 val = rd32(&pf->hw, I40E_GL_FWSTS);
14991
14992         if (val & I40E_GL_FWSTS_FWS1B_MASK) {
14993                 dev_crit(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
14994                 dev_crit(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
14995                 set_bit(__I40E_RECOVERY_MODE, pf->state);
14996
14997                 return true;
14998         }
14999         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15000                 dev_info(&pf->pdev->dev, "Please do Power-On Reset to initialize adapter in normal mode with full functionality.\n");
15001
15002         return false;
15003 }
15004
15005 /**
15006  * i40e_pf_loop_reset - perform reset in a loop.
15007  * @pf: board private structure
15008  *
15009  * This function is useful when a NIC is about to enter recovery mode.
15010  * When a NIC's internal data structures are corrupted the NIC's
15011  * firmware is going to enter recovery mode.
15012  * Right after a POR it takes about 7 minutes for firmware to enter
15013  * recovery mode. Until that time a NIC is in some kind of intermediate
15014  * state. After that time period the NIC almost surely enters
15015  * recovery mode. The only way for a driver to detect intermediate
15016  * state is to issue a series of pf-resets and check a return value.
15017  * If a PF reset returns success then the firmware could be in recovery
15018  * mode so the caller of this code needs to check for recovery mode
15019  * if this function returns success. There is a little chance that
15020  * firmware will hang in intermediate state forever.
15021  * Since waiting 7 minutes is quite a lot of time this function waits
15022  * 10 seconds and then gives up by returning an error.
15023  *
15024  * Return 0 on success, negative on failure.
15025  **/
15026 static i40e_status i40e_pf_loop_reset(struct i40e_pf *pf)
15027 {
15028         /* wait max 10 seconds for PF reset to succeed */
15029         const unsigned long time_end = jiffies + 10 * HZ;
15030
15031         struct i40e_hw *hw = &pf->hw;
15032         i40e_status ret;
15033
15034         ret = i40e_pf_reset(hw);
15035         while (ret != I40E_SUCCESS && time_before(jiffies, time_end)) {
15036                 usleep_range(10000, 20000);
15037                 ret = i40e_pf_reset(hw);
15038         }
15039
15040         if (ret == I40E_SUCCESS)
15041                 pf->pfr_count++;
15042         else
15043                 dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
15044
15045         return ret;
15046 }
15047
15048 /**
15049  * i40e_check_fw_empr - check if FW issued unexpected EMP Reset
15050  * @pf: board private structure
15051  *
15052  * Check FW registers to determine if FW issued unexpected EMP Reset.
15053  * Every time when unexpected EMP Reset occurs the FW increments
15054  * a counter of unexpected EMP Resets. When the counter reaches 10
15055  * the FW should enter the Recovery mode
15056  *
15057  * Returns true if FW issued unexpected EMP Reset
15058  **/
15059 static bool i40e_check_fw_empr(struct i40e_pf *pf)
15060 {
15061         const u32 fw_sts = rd32(&pf->hw, I40E_GL_FWSTS) &
15062                            I40E_GL_FWSTS_FWS1B_MASK;
15063         return (fw_sts > I40E_GL_FWSTS_FWS1B_EMPR_0) &&
15064                (fw_sts <= I40E_GL_FWSTS_FWS1B_EMPR_10);
15065 }
15066
15067 /**
15068  * i40e_handle_resets - handle EMP resets and PF resets
15069  * @pf: board private structure
15070  *
15071  * Handle both EMP resets and PF resets and conclude whether there are
15072  * any issues regarding these resets. If there are any issues then
15073  * generate log entry.
15074  *
15075  * Return 0 if NIC is healthy or negative value when there are issues
15076  * with resets
15077  **/
15078 static i40e_status i40e_handle_resets(struct i40e_pf *pf)
15079 {
15080         const i40e_status pfr = i40e_pf_loop_reset(pf);
15081         const bool is_empr = i40e_check_fw_empr(pf);
15082
15083         if (is_empr || pfr != I40E_SUCCESS)
15084                 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");
15085
15086         return is_empr ? I40E_ERR_RESET_FAILED : pfr;
15087 }
15088
15089 /**
15090  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
15091  * @pf: board private structure
15092  * @hw: ptr to the hardware info
15093  *
15094  * This function does a minimal setup of all subsystems needed for running
15095  * recovery mode.
15096  *
15097  * Returns 0 on success, negative on failure
15098  **/
15099 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
15100 {
15101         struct i40e_vsi *vsi;
15102         int err;
15103         int v_idx;
15104
15105         pci_save_state(pf->pdev);
15106
15107         /* set up periodic task facility */
15108         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15109         pf->service_timer_period = HZ;
15110
15111         INIT_WORK(&pf->service_task, i40e_service_task);
15112         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15113
15114         err = i40e_init_interrupt_scheme(pf);
15115         if (err)
15116                 goto err_switch_setup;
15117
15118         /* The number of VSIs reported by the FW is the minimum guaranteed
15119          * to us; HW supports far more and we share the remaining pool with
15120          * the other PFs. We allocate space for more than the guarantee with
15121          * the understanding that we might not get them all later.
15122          */
15123         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15124                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15125         else
15126                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15127
15128         /* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
15129         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15130                           GFP_KERNEL);
15131         if (!pf->vsi) {
15132                 err = -ENOMEM;
15133                 goto err_switch_setup;
15134         }
15135
15136         /* We allocate one VSI which is needed as absolute minimum
15137          * in order to register the netdev
15138          */
15139         v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
15140         if (v_idx < 0) {
15141                 err = v_idx;
15142                 goto err_switch_setup;
15143         }
15144         pf->lan_vsi = v_idx;
15145         vsi = pf->vsi[v_idx];
15146         if (!vsi) {
15147                 err = -EFAULT;
15148                 goto err_switch_setup;
15149         }
15150         vsi->alloc_queue_pairs = 1;
15151         err = i40e_config_netdev(vsi);
15152         if (err)
15153                 goto err_switch_setup;
15154         err = register_netdev(vsi->netdev);
15155         if (err)
15156                 goto err_switch_setup;
15157         vsi->netdev_registered = true;
15158         i40e_dbg_pf_init(pf);
15159
15160         err = i40e_setup_misc_vector_for_recovery_mode(pf);
15161         if (err)
15162                 goto err_switch_setup;
15163
15164         /* tell the firmware that we're starting */
15165         i40e_send_version(pf);
15166
15167         /* since everything's happy, start the service_task timer */
15168         mod_timer(&pf->service_timer,
15169                   round_jiffies(jiffies + pf->service_timer_period));
15170
15171         return 0;
15172
15173 err_switch_setup:
15174         i40e_reset_interrupt_capability(pf);
15175         del_timer_sync(&pf->service_timer);
15176         i40e_shutdown_adminq(hw);
15177         iounmap(hw->hw_addr);
15178         pci_disable_pcie_error_reporting(pf->pdev);
15179         pci_release_mem_regions(pf->pdev);
15180         pci_disable_device(pf->pdev);
15181         kfree(pf);
15182
15183         return err;
15184 }
15185
15186 /**
15187  * i40e_set_subsystem_device_id - set subsystem device id
15188  * @hw: pointer to the hardware info
15189  *
15190  * Set PCI subsystem device id either from a pci_dev structure or
15191  * a specific FW register.
15192  **/
15193 static inline void i40e_set_subsystem_device_id(struct i40e_hw *hw)
15194 {
15195         struct pci_dev *pdev = ((struct i40e_pf *)hw->back)->pdev;
15196
15197         hw->subsystem_device_id = pdev->subsystem_device ?
15198                 pdev->subsystem_device :
15199                 (ushort)(rd32(hw, I40E_PFPCI_SUBSYSID) & USHRT_MAX);
15200 }
15201
15202 /**
15203  * i40e_probe - Device initialization routine
15204  * @pdev: PCI device information struct
15205  * @ent: entry in i40e_pci_tbl
15206  *
15207  * i40e_probe initializes a PF identified by a pci_dev structure.
15208  * The OS initialization, configuring of the PF private structure,
15209  * and a hardware reset occur.
15210  *
15211  * Returns 0 on success, negative on failure
15212  **/
15213 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
15214 {
15215         struct i40e_aq_get_phy_abilities_resp abilities;
15216 #ifdef CONFIG_I40E_DCB
15217         enum i40e_get_fw_lldp_status_resp lldp_status;
15218         i40e_status status;
15219 #endif /* CONFIG_I40E_DCB */
15220         struct i40e_pf *pf;
15221         struct i40e_hw *hw;
15222         static u16 pfs_found;
15223         u16 wol_nvm_bits;
15224         u16 link_status;
15225         int err;
15226         u32 val;
15227         u32 i;
15228
15229         err = pci_enable_device_mem(pdev);
15230         if (err)
15231                 return err;
15232
15233         /* set up for high or low dma */
15234         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
15235         if (err) {
15236                 err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
15237                 if (err) {
15238                         dev_err(&pdev->dev,
15239                                 "DMA configuration failed: 0x%x\n", err);
15240                         goto err_dma;
15241                 }
15242         }
15243
15244         /* set up pci connections */
15245         err = pci_request_mem_regions(pdev, i40e_driver_name);
15246         if (err) {
15247                 dev_info(&pdev->dev,
15248                          "pci_request_selected_regions failed %d\n", err);
15249                 goto err_pci_reg;
15250         }
15251
15252         pci_enable_pcie_error_reporting(pdev);
15253         pci_set_master(pdev);
15254
15255         /* Now that we have a PCI connection, we need to do the
15256          * low level device setup.  This is primarily setting up
15257          * the Admin Queue structures and then querying for the
15258          * device's current profile information.
15259          */
15260         pf = kzalloc(sizeof(*pf), GFP_KERNEL);
15261         if (!pf) {
15262                 err = -ENOMEM;
15263                 goto err_pf_alloc;
15264         }
15265         pf->next_vsi = 0;
15266         pf->pdev = pdev;
15267         set_bit(__I40E_DOWN, pf->state);
15268
15269         hw = &pf->hw;
15270         hw->back = pf;
15271
15272         pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
15273                                 I40E_MAX_CSR_SPACE);
15274         /* We believe that the highest register to read is
15275          * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
15276          * is not less than that before mapping to prevent a
15277          * kernel panic.
15278          */
15279         if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
15280                 dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
15281                         pf->ioremap_len);
15282                 err = -ENOMEM;
15283                 goto err_ioremap;
15284         }
15285         hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
15286         if (!hw->hw_addr) {
15287                 err = -EIO;
15288                 dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
15289                          (unsigned int)pci_resource_start(pdev, 0),
15290                          pf->ioremap_len, err);
15291                 goto err_ioremap;
15292         }
15293         hw->vendor_id = pdev->vendor;
15294         hw->device_id = pdev->device;
15295         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
15296         hw->subsystem_vendor_id = pdev->subsystem_vendor;
15297         i40e_set_subsystem_device_id(hw);
15298         hw->bus.device = PCI_SLOT(pdev->devfn);
15299         hw->bus.func = PCI_FUNC(pdev->devfn);
15300         hw->bus.bus_id = pdev->bus->number;
15301         pf->instance = pfs_found;
15302
15303         /* Select something other than the 802.1ad ethertype for the
15304          * switch to use internally and drop on ingress.
15305          */
15306         hw->switch_tag = 0xffff;
15307         hw->first_tag = ETH_P_8021AD;
15308         hw->second_tag = ETH_P_8021Q;
15309
15310         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
15311         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
15312         INIT_LIST_HEAD(&pf->ddp_old_prof);
15313
15314         /* set up the locks for the AQ, do this only once in probe
15315          * and destroy them only once in remove
15316          */
15317         mutex_init(&hw->aq.asq_mutex);
15318         mutex_init(&hw->aq.arq_mutex);
15319
15320         pf->msg_enable = netif_msg_init(debug,
15321                                         NETIF_MSG_DRV |
15322                                         NETIF_MSG_PROBE |
15323                                         NETIF_MSG_LINK);
15324         if (debug < -1)
15325                 pf->hw.debug_mask = debug;
15326
15327         /* do a special CORER for clearing PXE mode once at init */
15328         if (hw->revision_id == 0 &&
15329             (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
15330                 wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
15331                 i40e_flush(hw);
15332                 msleep(200);
15333                 pf->corer_count++;
15334
15335                 i40e_clear_pxe_mode(hw);
15336         }
15337
15338         /* Reset here to make sure all is clean and to define PF 'n' */
15339         i40e_clear_hw(hw);
15340
15341         err = i40e_set_mac_type(hw);
15342         if (err) {
15343                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15344                          err);
15345                 goto err_pf_reset;
15346         }
15347
15348         err = i40e_handle_resets(pf);
15349         if (err)
15350                 goto err_pf_reset;
15351
15352         i40e_check_recovery_mode(pf);
15353
15354         if (is_kdump_kernel()) {
15355                 hw->aq.num_arq_entries = I40E_MIN_ARQ_LEN;
15356                 hw->aq.num_asq_entries = I40E_MIN_ASQ_LEN;
15357         } else {
15358                 hw->aq.num_arq_entries = I40E_AQ_LEN;
15359                 hw->aq.num_asq_entries = I40E_AQ_LEN;
15360         }
15361         hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15362         hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
15363         pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
15364
15365         snprintf(pf->int_name, sizeof(pf->int_name) - 1,
15366                  "%s-%s:misc",
15367                  dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
15368
15369         err = i40e_init_shared_code(hw);
15370         if (err) {
15371                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
15372                          err);
15373                 goto err_pf_reset;
15374         }
15375
15376         /* set up a default setting for link flow control */
15377         pf->hw.fc.requested_mode = I40E_FC_NONE;
15378
15379         err = i40e_init_adminq(hw);
15380         if (err) {
15381                 if (err == I40E_ERR_FIRMWARE_API_VERSION)
15382                         dev_info(&pdev->dev,
15383                                  "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",
15384                                  hw->aq.api_maj_ver,
15385                                  hw->aq.api_min_ver,
15386                                  I40E_FW_API_VERSION_MAJOR,
15387                                  I40E_FW_MINOR_VERSION(hw));
15388                 else
15389                         dev_info(&pdev->dev,
15390                                  "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
15391
15392                 goto err_pf_reset;
15393         }
15394         i40e_get_oem_version(hw);
15395
15396         /* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
15397         dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
15398                  hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
15399                  hw->aq.api_maj_ver, hw->aq.api_min_ver,
15400                  i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
15401                  hw->subsystem_vendor_id, hw->subsystem_device_id);
15402
15403         if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
15404             hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
15405                 dev_info(&pdev->dev,
15406                          "The driver for the device detected a newer version of the NVM image v%u.%u than expected v%u.%u. Please install the most recent version of the network driver.\n",
15407                          hw->aq.api_maj_ver,
15408                          hw->aq.api_min_ver,
15409                          I40E_FW_API_VERSION_MAJOR,
15410                          I40E_FW_MINOR_VERSION(hw));
15411         else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
15412                 dev_info(&pdev->dev,
15413                          "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",
15414                          hw->aq.api_maj_ver,
15415                          hw->aq.api_min_ver,
15416                          I40E_FW_API_VERSION_MAJOR,
15417                          I40E_FW_MINOR_VERSION(hw));
15418
15419         i40e_verify_eeprom(pf);
15420
15421         /* Rev 0 hardware was never productized */
15422         if (hw->revision_id < 1)
15423                 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");
15424
15425         i40e_clear_pxe_mode(hw);
15426
15427         err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
15428         if (err)
15429                 goto err_adminq_setup;
15430
15431         err = i40e_sw_init(pf);
15432         if (err) {
15433                 dev_info(&pdev->dev, "sw_init failed: %d\n", err);
15434                 goto err_sw_init;
15435         }
15436
15437         if (test_bit(__I40E_RECOVERY_MODE, pf->state))
15438                 return i40e_init_recovery_mode(pf, hw);
15439
15440         err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
15441                                 hw->func_caps.num_rx_qp, 0, 0);
15442         if (err) {
15443                 dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
15444                 goto err_init_lan_hmc;
15445         }
15446
15447         err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
15448         if (err) {
15449                 dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
15450                 err = -ENOENT;
15451                 goto err_configure_lan_hmc;
15452         }
15453
15454         /* Disable LLDP for NICs that have firmware versions lower than v4.3.
15455          * Ignore error return codes because if it was already disabled via
15456          * hardware settings this will fail
15457          */
15458         if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
15459                 dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
15460                 i40e_aq_stop_lldp(hw, true, false, NULL);
15461         }
15462
15463         /* allow a platform config to override the HW addr */
15464         i40e_get_platform_mac_addr(pdev, pf);
15465
15466         if (!is_valid_ether_addr(hw->mac.addr)) {
15467                 dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
15468                 err = -EIO;
15469                 goto err_mac_addr;
15470         }
15471         dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
15472         ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
15473         i40e_get_port_mac_addr(hw, hw->mac.port_addr);
15474         if (is_valid_ether_addr(hw->mac.port_addr))
15475                 pf->hw_features |= I40E_HW_PORT_ID_VALID;
15476
15477         i40e_ptp_alloc_pins(pf);
15478         pci_set_drvdata(pdev, pf);
15479         pci_save_state(pdev);
15480
15481 #ifdef CONFIG_I40E_DCB
15482         status = i40e_get_fw_lldp_status(&pf->hw, &lldp_status);
15483         (!status &&
15484          lldp_status == I40E_GET_FW_LLDP_STATUS_ENABLED) ?
15485                 (pf->flags &= ~I40E_FLAG_DISABLE_FW_LLDP) :
15486                 (pf->flags |= I40E_FLAG_DISABLE_FW_LLDP);
15487         dev_info(&pdev->dev,
15488                  (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
15489                         "FW LLDP is disabled\n" :
15490                         "FW LLDP is enabled\n");
15491
15492         /* Enable FW to write default DCB config on link-up */
15493         i40e_aq_set_dcb_parameters(hw, true, NULL);
15494
15495         err = i40e_init_pf_dcb(pf);
15496         if (err) {
15497                 dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
15498                 pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
15499                 /* Continue without DCB enabled */
15500         }
15501 #endif /* CONFIG_I40E_DCB */
15502
15503         /* set up periodic task facility */
15504         timer_setup(&pf->service_timer, i40e_service_timer, 0);
15505         pf->service_timer_period = HZ;
15506
15507         INIT_WORK(&pf->service_task, i40e_service_task);
15508         clear_bit(__I40E_SERVICE_SCHED, pf->state);
15509
15510         /* NVM bit on means WoL disabled for the port */
15511         i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15512         if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15513                 pf->wol_en = false;
15514         else
15515                 pf->wol_en = true;
15516         device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15517
15518         /* set up the main switch operations */
15519         i40e_determine_queue_usage(pf);
15520         err = i40e_init_interrupt_scheme(pf);
15521         if (err)
15522                 goto err_switch_setup;
15523
15524         /* Reduce Tx and Rx pairs for kdump
15525          * When MSI-X is enabled, it's not allowed to use more TC queue
15526          * pairs than MSI-X vectors (pf->num_lan_msix) exist. Thus
15527          * vsi->num_queue_pairs will be equal to pf->num_lan_msix, i.e., 1.
15528          */
15529         if (is_kdump_kernel())
15530                 pf->num_lan_msix = 1;
15531
15532         pf->udp_tunnel_nic.set_port = i40e_udp_tunnel_set_port;
15533         pf->udp_tunnel_nic.unset_port = i40e_udp_tunnel_unset_port;
15534         pf->udp_tunnel_nic.flags = UDP_TUNNEL_NIC_INFO_MAY_SLEEP;
15535         pf->udp_tunnel_nic.shared = &pf->udp_tunnel_shared;
15536         pf->udp_tunnel_nic.tables[0].n_entries = I40E_MAX_PF_UDP_OFFLOAD_PORTS;
15537         pf->udp_tunnel_nic.tables[0].tunnel_types = UDP_TUNNEL_TYPE_VXLAN |
15538                                                     UDP_TUNNEL_TYPE_GENEVE;
15539
15540         /* The number of VSIs reported by the FW is the minimum guaranteed
15541          * to us; HW supports far more and we share the remaining pool with
15542          * the other PFs. We allocate space for more than the guarantee with
15543          * the understanding that we might not get them all later.
15544          */
15545         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15546                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15547         else
15548                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15549         if (pf->num_alloc_vsi > UDP_TUNNEL_NIC_MAX_SHARING_DEVICES) {
15550                 dev_warn(&pf->pdev->dev,
15551                          "limiting the VSI count due to UDP tunnel limitation %d > %d\n",
15552                          pf->num_alloc_vsi, UDP_TUNNEL_NIC_MAX_SHARING_DEVICES);
15553                 pf->num_alloc_vsi = UDP_TUNNEL_NIC_MAX_SHARING_DEVICES;
15554         }
15555
15556         /* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15557         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15558                           GFP_KERNEL);
15559         if (!pf->vsi) {
15560                 err = -ENOMEM;
15561                 goto err_switch_setup;
15562         }
15563
15564 #ifdef CONFIG_PCI_IOV
15565         /* prep for VF support */
15566         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15567             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15568             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15569                 if (pci_num_vf(pdev))
15570                         pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
15571         }
15572 #endif
15573         err = i40e_setup_pf_switch(pf, false, false);
15574         if (err) {
15575                 dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15576                 goto err_vsis;
15577         }
15578         INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
15579
15580         /* if FDIR VSI was set up, start it now */
15581         for (i = 0; i < pf->num_alloc_vsi; i++) {
15582                 if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
15583                         i40e_vsi_open(pf->vsi[i]);
15584                         break;
15585                 }
15586         }
15587
15588         /* The driver only wants link up/down and module qualification
15589          * reports from firmware.  Note the negative logic.
15590          */
15591         err = i40e_aq_set_phy_int_mask(&pf->hw,
15592                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
15593                                          I40E_AQ_EVENT_MEDIA_NA |
15594                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15595         if (err)
15596                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
15597                          i40e_stat_str(&pf->hw, err),
15598                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15599
15600         /* Reconfigure hardware for allowing smaller MSS in the case
15601          * of TSO, so that we avoid the MDD being fired and causing
15602          * a reset in the case of small MSS+TSO.
15603          */
15604         val = rd32(hw, I40E_REG_MSS);
15605         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15606                 val &= ~I40E_REG_MSS_MIN_MASK;
15607                 val |= I40E_64BYTE_MSS;
15608                 wr32(hw, I40E_REG_MSS, val);
15609         }
15610
15611         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
15612                 msleep(75);
15613                 err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15614                 if (err)
15615                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
15616                                  i40e_stat_str(&pf->hw, err),
15617                                  i40e_aq_str(&pf->hw,
15618                                              pf->hw.aq.asq_last_status));
15619         }
15620         /* The main driver is (mostly) up and happy. We need to set this state
15621          * before setting up the misc vector or we get a race and the vector
15622          * ends up disabled forever.
15623          */
15624         clear_bit(__I40E_DOWN, pf->state);
15625
15626         /* In case of MSIX we are going to setup the misc vector right here
15627          * to handle admin queue events etc. In case of legacy and MSI
15628          * the misc functionality and queue processing is combined in
15629          * the same vector and that gets setup at open.
15630          */
15631         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
15632                 err = i40e_setup_misc_vector(pf);
15633                 if (err) {
15634                         dev_info(&pdev->dev,
15635                                  "setup of misc vector failed: %d\n", err);
15636                         i40e_cloud_filter_exit(pf);
15637                         i40e_fdir_teardown(pf);
15638                         goto err_vsis;
15639                 }
15640         }
15641
15642 #ifdef CONFIG_PCI_IOV
15643         /* prep for VF support */
15644         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15645             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15646             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15647                 /* disable link interrupts for VFs */
15648                 val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15649                 val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15650                 wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15651                 i40e_flush(hw);
15652
15653                 if (pci_num_vf(pdev)) {
15654                         dev_info(&pdev->dev,
15655                                  "Active VFs found, allocating resources.\n");
15656                         err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15657                         if (err)
15658                                 dev_info(&pdev->dev,
15659                                          "Error %d allocating resources for existing VFs\n",
15660                                          err);
15661                 }
15662         }
15663 #endif /* CONFIG_PCI_IOV */
15664
15665         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15666                 pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
15667                                                       pf->num_iwarp_msix,
15668                                                       I40E_IWARP_IRQ_PILE_ID);
15669                 if (pf->iwarp_base_vector < 0) {
15670                         dev_info(&pdev->dev,
15671                                  "failed to get tracking for %d vectors for IWARP err=%d\n",
15672                                  pf->num_iwarp_msix, pf->iwarp_base_vector);
15673                         pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
15674                 }
15675         }
15676
15677         i40e_dbg_pf_init(pf);
15678
15679         /* tell the firmware that we're starting */
15680         i40e_send_version(pf);
15681
15682         /* since everything's happy, start the service_task timer */
15683         mod_timer(&pf->service_timer,
15684                   round_jiffies(jiffies + pf->service_timer_period));
15685
15686         /* add this PF to client device list and launch a client service task */
15687         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15688                 err = i40e_lan_add_device(pf);
15689                 if (err)
15690                         dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
15691                                  err);
15692         }
15693
15694 #define PCI_SPEED_SIZE 8
15695 #define PCI_WIDTH_SIZE 8
15696         /* Devices on the IOSF bus do not have this information
15697          * and will report PCI Gen 1 x 1 by default so don't bother
15698          * checking them.
15699          */
15700         if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
15701                 char speed[PCI_SPEED_SIZE] = "Unknown";
15702                 char width[PCI_WIDTH_SIZE] = "Unknown";
15703
15704                 /* Get the negotiated link width and speed from PCI config
15705                  * space
15706                  */
15707                 pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
15708                                           &link_status);
15709
15710                 i40e_set_pci_config_data(hw, link_status);
15711
15712                 switch (hw->bus.speed) {
15713                 case i40e_bus_speed_8000:
15714                         strlcpy(speed, "8.0", PCI_SPEED_SIZE); break;
15715                 case i40e_bus_speed_5000:
15716                         strlcpy(speed, "5.0", PCI_SPEED_SIZE); break;
15717                 case i40e_bus_speed_2500:
15718                         strlcpy(speed, "2.5", PCI_SPEED_SIZE); break;
15719                 default:
15720                         break;
15721                 }
15722                 switch (hw->bus.width) {
15723                 case i40e_bus_width_pcie_x8:
15724                         strlcpy(width, "8", PCI_WIDTH_SIZE); break;
15725                 case i40e_bus_width_pcie_x4:
15726                         strlcpy(width, "4", PCI_WIDTH_SIZE); break;
15727                 case i40e_bus_width_pcie_x2:
15728                         strlcpy(width, "2", PCI_WIDTH_SIZE); break;
15729                 case i40e_bus_width_pcie_x1:
15730                         strlcpy(width, "1", PCI_WIDTH_SIZE); break;
15731                 default:
15732                         break;
15733                 }
15734
15735                 dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
15736                          speed, width);
15737
15738                 if (hw->bus.width < i40e_bus_width_pcie_x8 ||
15739                     hw->bus.speed < i40e_bus_speed_8000) {
15740                         dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
15741                         dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
15742                 }
15743         }
15744
15745         /* get the requested speeds from the fw */
15746         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
15747         if (err)
15748                 dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
15749                         i40e_stat_str(&pf->hw, err),
15750                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15751         pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
15752
15753         /* set the FEC config due to the board capabilities */
15754         i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
15755
15756         /* get the supported phy types from the fw */
15757         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
15758         if (err)
15759                 dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
15760                         i40e_stat_str(&pf->hw, err),
15761                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15762
15763         /* make sure the MFS hasn't been set lower than the default */
15764 #define MAX_FRAME_SIZE_DEFAULT 0x2600
15765         val = (rd32(&pf->hw, I40E_PRTGL_SAH) &
15766                I40E_PRTGL_SAH_MFS_MASK) >> I40E_PRTGL_SAH_MFS_SHIFT;
15767         if (val < MAX_FRAME_SIZE_DEFAULT)
15768                 dev_warn(&pdev->dev, "MFS for port %x has been set below the default: %x\n",
15769                          i, val);
15770
15771         /* Add a filter to drop all Flow control frames from any VSI from being
15772          * transmitted. By doing so we stop a malicious VF from sending out
15773          * PAUSE or PFC frames and potentially controlling traffic for other
15774          * PF/VF VSIs.
15775          * The FW can still send Flow control frames if enabled.
15776          */
15777         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
15778                                                        pf->main_vsi_seid);
15779
15780         if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
15781                 (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
15782                 pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
15783         if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
15784                 pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
15785         /* print a string summarizing features */
15786         i40e_print_features(pf);
15787
15788         return 0;
15789
15790         /* Unwind what we've done if something failed in the setup */
15791 err_vsis:
15792         set_bit(__I40E_DOWN, pf->state);
15793         i40e_clear_interrupt_scheme(pf);
15794         kfree(pf->vsi);
15795 err_switch_setup:
15796         i40e_reset_interrupt_capability(pf);
15797         del_timer_sync(&pf->service_timer);
15798 err_mac_addr:
15799 err_configure_lan_hmc:
15800         (void)i40e_shutdown_lan_hmc(hw);
15801 err_init_lan_hmc:
15802         kfree(pf->qp_pile);
15803 err_sw_init:
15804 err_adminq_setup:
15805 err_pf_reset:
15806         iounmap(hw->hw_addr);
15807 err_ioremap:
15808         kfree(pf);
15809 err_pf_alloc:
15810         pci_disable_pcie_error_reporting(pdev);
15811         pci_release_mem_regions(pdev);
15812 err_pci_reg:
15813 err_dma:
15814         pci_disable_device(pdev);
15815         return err;
15816 }
15817
15818 /**
15819  * i40e_remove - Device removal routine
15820  * @pdev: PCI device information struct
15821  *
15822  * i40e_remove is called by the PCI subsystem to alert the driver
15823  * that is should release a PCI device.  This could be caused by a
15824  * Hot-Plug event, or because the driver is going to be removed from
15825  * memory.
15826  **/
15827 static void i40e_remove(struct pci_dev *pdev)
15828 {
15829         struct i40e_pf *pf = pci_get_drvdata(pdev);
15830         struct i40e_hw *hw = &pf->hw;
15831         i40e_status ret_code;
15832         int i;
15833
15834         i40e_dbg_pf_exit(pf);
15835
15836         i40e_ptp_stop(pf);
15837
15838         /* Disable RSS in hw */
15839         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
15840         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
15841
15842         while (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
15843                 usleep_range(1000, 2000);
15844
15845         if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
15846                 set_bit(__I40E_VF_RESETS_DISABLED, pf->state);
15847                 i40e_free_vfs(pf);
15848                 pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
15849         }
15850         /* no more scheduling of any task */
15851         set_bit(__I40E_SUSPENDED, pf->state);
15852         set_bit(__I40E_DOWN, pf->state);
15853         if (pf->service_timer.function)
15854                 del_timer_sync(&pf->service_timer);
15855         if (pf->service_task.func)
15856                 cancel_work_sync(&pf->service_task);
15857
15858         if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
15859                 struct i40e_vsi *vsi = pf->vsi[0];
15860
15861                 /* We know that we have allocated only one vsi for this PF,
15862                  * it was just for registering netdevice, so the interface
15863                  * could be visible in the 'ifconfig' output
15864                  */
15865                 unregister_netdev(vsi->netdev);
15866                 free_netdev(vsi->netdev);
15867
15868                 goto unmap;
15869         }
15870
15871         /* Client close must be called explicitly here because the timer
15872          * has been stopped.
15873          */
15874         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
15875
15876         i40e_fdir_teardown(pf);
15877
15878         /* If there is a switch structure or any orphans, remove them.
15879          * This will leave only the PF's VSI remaining.
15880          */
15881         for (i = 0; i < I40E_MAX_VEB; i++) {
15882                 if (!pf->veb[i])
15883                         continue;
15884
15885                 if (pf->veb[i]->uplink_seid == pf->mac_seid ||
15886                     pf->veb[i]->uplink_seid == 0)
15887                         i40e_switch_branch_release(pf->veb[i]);
15888         }
15889
15890         /* Now we can shutdown the PF's VSI, just before we kill
15891          * adminq and hmc.
15892          */
15893         if (pf->vsi[pf->lan_vsi])
15894                 i40e_vsi_release(pf->vsi[pf->lan_vsi]);
15895
15896         i40e_cloud_filter_exit(pf);
15897
15898         /* remove attached clients */
15899         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15900                 ret_code = i40e_lan_del_device(pf);
15901                 if (ret_code)
15902                         dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
15903                                  ret_code);
15904         }
15905
15906         /* shutdown and destroy the HMC */
15907         if (hw->hmc.hmc_obj) {
15908                 ret_code = i40e_shutdown_lan_hmc(hw);
15909                 if (ret_code)
15910                         dev_warn(&pdev->dev,
15911                                  "Failed to destroy the HMC resources: %d\n",
15912                                  ret_code);
15913         }
15914
15915 unmap:
15916         /* Free MSI/legacy interrupt 0 when in recovery mode. */
15917         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
15918             !(pf->flags & I40E_FLAG_MSIX_ENABLED))
15919                 free_irq(pf->pdev->irq, pf);
15920
15921         /* shutdown the adminq */
15922         i40e_shutdown_adminq(hw);
15923
15924         /* destroy the locks only once, here */
15925         mutex_destroy(&hw->aq.arq_mutex);
15926         mutex_destroy(&hw->aq.asq_mutex);
15927
15928         /* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
15929         rtnl_lock();
15930         i40e_clear_interrupt_scheme(pf);
15931         for (i = 0; i < pf->num_alloc_vsi; i++) {
15932                 if (pf->vsi[i]) {
15933                         if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
15934                                 i40e_vsi_clear_rings(pf->vsi[i]);
15935                         i40e_vsi_clear(pf->vsi[i]);
15936                         pf->vsi[i] = NULL;
15937                 }
15938         }
15939         rtnl_unlock();
15940
15941         for (i = 0; i < I40E_MAX_VEB; i++) {
15942                 kfree(pf->veb[i]);
15943                 pf->veb[i] = NULL;
15944         }
15945
15946         kfree(pf->qp_pile);
15947         kfree(pf->vsi);
15948
15949         iounmap(hw->hw_addr);
15950         kfree(pf);
15951         pci_release_mem_regions(pdev);
15952
15953         pci_disable_pcie_error_reporting(pdev);
15954         pci_disable_device(pdev);
15955 }
15956
15957 /**
15958  * i40e_pci_error_detected - warning that something funky happened in PCI land
15959  * @pdev: PCI device information struct
15960  * @error: the type of PCI error
15961  *
15962  * Called to warn that something happened and the error handling steps
15963  * are in progress.  Allows the driver to quiesce things, be ready for
15964  * remediation.
15965  **/
15966 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
15967                                                 pci_channel_state_t error)
15968 {
15969         struct i40e_pf *pf = pci_get_drvdata(pdev);
15970
15971         dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
15972
15973         if (!pf) {
15974                 dev_info(&pdev->dev,
15975                          "Cannot recover - error happened during device probe\n");
15976                 return PCI_ERS_RESULT_DISCONNECT;
15977         }
15978
15979         /* shutdown all operations */
15980         if (!test_bit(__I40E_SUSPENDED, pf->state))
15981                 i40e_prep_for_reset(pf);
15982
15983         /* Request a slot reset */
15984         return PCI_ERS_RESULT_NEED_RESET;
15985 }
15986
15987 /**
15988  * i40e_pci_error_slot_reset - a PCI slot reset just happened
15989  * @pdev: PCI device information struct
15990  *
15991  * Called to find if the driver can work with the device now that
15992  * the pci slot has been reset.  If a basic connection seems good
15993  * (registers are readable and have sane content) then return a
15994  * happy little PCI_ERS_RESULT_xxx.
15995  **/
15996 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
15997 {
15998         struct i40e_pf *pf = pci_get_drvdata(pdev);
15999         pci_ers_result_t result;
16000         u32 reg;
16001
16002         dev_dbg(&pdev->dev, "%s\n", __func__);
16003         if (pci_enable_device_mem(pdev)) {
16004                 dev_info(&pdev->dev,
16005                          "Cannot re-enable PCI device after reset.\n");
16006                 result = PCI_ERS_RESULT_DISCONNECT;
16007         } else {
16008                 pci_set_master(pdev);
16009                 pci_restore_state(pdev);
16010                 pci_save_state(pdev);
16011                 pci_wake_from_d3(pdev, false);
16012
16013                 reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
16014                 if (reg == 0)
16015                         result = PCI_ERS_RESULT_RECOVERED;
16016                 else
16017                         result = PCI_ERS_RESULT_DISCONNECT;
16018         }
16019
16020         return result;
16021 }
16022
16023 /**
16024  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
16025  * @pdev: PCI device information struct
16026  */
16027 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
16028 {
16029         struct i40e_pf *pf = pci_get_drvdata(pdev);
16030
16031         i40e_prep_for_reset(pf);
16032 }
16033
16034 /**
16035  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
16036  * @pdev: PCI device information struct
16037  */
16038 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
16039 {
16040         struct i40e_pf *pf = pci_get_drvdata(pdev);
16041
16042         i40e_reset_and_rebuild(pf, false, false);
16043 }
16044
16045 /**
16046  * i40e_pci_error_resume - restart operations after PCI error recovery
16047  * @pdev: PCI device information struct
16048  *
16049  * Called to allow the driver to bring things back up after PCI error
16050  * and/or reset recovery has finished.
16051  **/
16052 static void i40e_pci_error_resume(struct pci_dev *pdev)
16053 {
16054         struct i40e_pf *pf = pci_get_drvdata(pdev);
16055
16056         dev_dbg(&pdev->dev, "%s\n", __func__);
16057         if (test_bit(__I40E_SUSPENDED, pf->state))
16058                 return;
16059
16060         i40e_handle_reset_warning(pf, false);
16061 }
16062
16063 /**
16064  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
16065  * using the mac_address_write admin q function
16066  * @pf: pointer to i40e_pf struct
16067  **/
16068 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
16069 {
16070         struct i40e_hw *hw = &pf->hw;
16071         i40e_status ret;
16072         u8 mac_addr[6];
16073         u16 flags = 0;
16074
16075         /* Get current MAC address in case it's an LAA */
16076         if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
16077                 ether_addr_copy(mac_addr,
16078                                 pf->vsi[pf->lan_vsi]->netdev->dev_addr);
16079         } else {
16080                 dev_err(&pf->pdev->dev,
16081                         "Failed to retrieve MAC address; using default\n");
16082                 ether_addr_copy(mac_addr, hw->mac.addr);
16083         }
16084
16085         /* The FW expects the mac address write cmd to first be called with
16086          * one of these flags before calling it again with the multicast
16087          * enable flags.
16088          */
16089         flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
16090
16091         if (hw->func_caps.flex10_enable && hw->partition_id != 1)
16092                 flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
16093
16094         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16095         if (ret) {
16096                 dev_err(&pf->pdev->dev,
16097                         "Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
16098                 return;
16099         }
16100
16101         flags = I40E_AQC_MC_MAG_EN
16102                         | I40E_AQC_WOL_PRESERVE_ON_PFR
16103                         | I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
16104         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
16105         if (ret)
16106                 dev_err(&pf->pdev->dev,
16107                         "Failed to enable Multicast Magic Packet wake up\n");
16108 }
16109
16110 /**
16111  * i40e_shutdown - PCI callback for shutting down
16112  * @pdev: PCI device information struct
16113  **/
16114 static void i40e_shutdown(struct pci_dev *pdev)
16115 {
16116         struct i40e_pf *pf = pci_get_drvdata(pdev);
16117         struct i40e_hw *hw = &pf->hw;
16118
16119         set_bit(__I40E_SUSPENDED, pf->state);
16120         set_bit(__I40E_DOWN, pf->state);
16121
16122         del_timer_sync(&pf->service_timer);
16123         cancel_work_sync(&pf->service_task);
16124         i40e_cloud_filter_exit(pf);
16125         i40e_fdir_teardown(pf);
16126
16127         /* Client close must be called explicitly here because the timer
16128          * has been stopped.
16129          */
16130         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16131
16132         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16133                 i40e_enable_mc_magic_wake(pf);
16134
16135         i40e_prep_for_reset(pf);
16136
16137         wr32(hw, I40E_PFPM_APM,
16138              (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16139         wr32(hw, I40E_PFPM_WUFC,
16140              (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16141
16142         /* Free MSI/legacy interrupt 0 when in recovery mode. */
16143         if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
16144             !(pf->flags & I40E_FLAG_MSIX_ENABLED))
16145                 free_irq(pf->pdev->irq, pf);
16146
16147         /* Since we're going to destroy queues during the
16148          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16149          * whole section
16150          */
16151         rtnl_lock();
16152         i40e_clear_interrupt_scheme(pf);
16153         rtnl_unlock();
16154
16155         if (system_state == SYSTEM_POWER_OFF) {
16156                 pci_wake_from_d3(pdev, pf->wol_en);
16157                 pci_set_power_state(pdev, PCI_D3hot);
16158         }
16159 }
16160
16161 /**
16162  * i40e_suspend - PM callback for moving to D3
16163  * @dev: generic device information structure
16164  **/
16165 static int __maybe_unused i40e_suspend(struct device *dev)
16166 {
16167         struct i40e_pf *pf = dev_get_drvdata(dev);
16168         struct i40e_hw *hw = &pf->hw;
16169
16170         /* If we're already suspended, then there is nothing to do */
16171         if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
16172                 return 0;
16173
16174         set_bit(__I40E_DOWN, pf->state);
16175
16176         /* Ensure service task will not be running */
16177         del_timer_sync(&pf->service_timer);
16178         cancel_work_sync(&pf->service_task);
16179
16180         /* Client close must be called explicitly here because the timer
16181          * has been stopped.
16182          */
16183         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
16184
16185         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
16186                 i40e_enable_mc_magic_wake(pf);
16187
16188         /* Since we're going to destroy queues during the
16189          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
16190          * whole section
16191          */
16192         rtnl_lock();
16193
16194         i40e_prep_for_reset(pf);
16195
16196         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
16197         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
16198
16199         /* Clear the interrupt scheme and release our IRQs so that the system
16200          * can safely hibernate even when there are a large number of CPUs.
16201          * Otherwise hibernation might fail when mapping all the vectors back
16202          * to CPU0.
16203          */
16204         i40e_clear_interrupt_scheme(pf);
16205
16206         rtnl_unlock();
16207
16208         return 0;
16209 }
16210
16211 /**
16212  * i40e_resume - PM callback for waking up from D3
16213  * @dev: generic device information structure
16214  **/
16215 static int __maybe_unused i40e_resume(struct device *dev)
16216 {
16217         struct i40e_pf *pf = dev_get_drvdata(dev);
16218         int err;
16219
16220         /* If we're not suspended, then there is nothing to do */
16221         if (!test_bit(__I40E_SUSPENDED, pf->state))
16222                 return 0;
16223
16224         /* We need to hold the RTNL lock prior to restoring interrupt schemes,
16225          * since we're going to be restoring queues
16226          */
16227         rtnl_lock();
16228
16229         /* We cleared the interrupt scheme when we suspended, so we need to
16230          * restore it now to resume device functionality.
16231          */
16232         err = i40e_restore_interrupt_scheme(pf);
16233         if (err) {
16234                 dev_err(dev, "Cannot restore interrupt scheme: %d\n",
16235                         err);
16236         }
16237
16238         clear_bit(__I40E_DOWN, pf->state);
16239         i40e_reset_and_rebuild(pf, false, true);
16240
16241         rtnl_unlock();
16242
16243         /* Clear suspended state last after everything is recovered */
16244         clear_bit(__I40E_SUSPENDED, pf->state);
16245
16246         /* Restart the service task */
16247         mod_timer(&pf->service_timer,
16248                   round_jiffies(jiffies + pf->service_timer_period));
16249
16250         return 0;
16251 }
16252
16253 static const struct pci_error_handlers i40e_err_handler = {
16254         .error_detected = i40e_pci_error_detected,
16255         .slot_reset = i40e_pci_error_slot_reset,
16256         .reset_prepare = i40e_pci_error_reset_prepare,
16257         .reset_done = i40e_pci_error_reset_done,
16258         .resume = i40e_pci_error_resume,
16259 };
16260
16261 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
16262
16263 static struct pci_driver i40e_driver = {
16264         .name     = i40e_driver_name,
16265         .id_table = i40e_pci_tbl,
16266         .probe    = i40e_probe,
16267         .remove   = i40e_remove,
16268         .driver   = {
16269                 .pm = &i40e_pm_ops,
16270         },
16271         .shutdown = i40e_shutdown,
16272         .err_handler = &i40e_err_handler,
16273         .sriov_configure = i40e_pci_sriov_configure,
16274 };
16275
16276 /**
16277  * i40e_init_module - Driver registration routine
16278  *
16279  * i40e_init_module is the first routine called when the driver is
16280  * loaded. All it does is register with the PCI subsystem.
16281  **/
16282 static int __init i40e_init_module(void)
16283 {
16284         pr_info("%s: %s\n", i40e_driver_name, i40e_driver_string);
16285         pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
16286
16287         /* There is no need to throttle the number of active tasks because
16288          * each device limits its own task using a state bit for scheduling
16289          * the service task, and the device tasks do not interfere with each
16290          * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
16291          * since we need to be able to guarantee forward progress even under
16292          * memory pressure.
16293          */
16294         i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
16295         if (!i40e_wq) {
16296                 pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
16297                 return -ENOMEM;
16298         }
16299
16300         i40e_dbg_init();
16301         return pci_register_driver(&i40e_driver);
16302 }
16303 module_init(i40e_init_module);
16304
16305 /**
16306  * i40e_exit_module - Driver exit cleanup routine
16307  *
16308  * i40e_exit_module is called just before the driver is removed
16309  * from memory.
16310  **/
16311 static void __exit i40e_exit_module(void)
16312 {
16313         pci_unregister_driver(&i40e_driver);
16314         destroy_workqueue(i40e_wq);
16315         ida_destroy(&i40e_client_ida);
16316         i40e_dbg_exit();
16317 }
16318 module_exit(i40e_exit_module);