Linux-libre 4.14.145-gnu
[librecmc/linux-libre.git] / drivers / net / ethernet / intel / i40e / i40e_main.c
1 /*******************************************************************************
2  *
3  * Intel Ethernet Controller XL710 Family Linux Driver
4  * Copyright(c) 2013 - 2017 Intel Corporation.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  * The full GNU General Public License is included in this distribution in
19  * the file called "COPYING".
20  *
21  * Contact Information:
22  * e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
23  * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
24  *
25  ******************************************************************************/
26
27 #include <linux/etherdevice.h>
28 #include <linux/of_net.h>
29 #include <linux/pci.h>
30 #include <linux/bpf.h>
31
32 /* Local includes */
33 #include "i40e.h"
34 #include "i40e_diag.h"
35 #include <net/udp_tunnel.h>
36 /* All i40e tracepoints are defined by the include below, which
37  * must be included exactly once across the whole kernel with
38  * CREATE_TRACE_POINTS defined
39  */
40 #define CREATE_TRACE_POINTS
41 #include "i40e_trace.h"
42
43 const char i40e_driver_name[] = "i40e";
44 static const char i40e_driver_string[] =
45                         "Intel(R) Ethernet Connection XL710 Network Driver";
46
47 #define DRV_KERN "-k"
48
49 #define DRV_VERSION_MAJOR 2
50 #define DRV_VERSION_MINOR 1
51 #define DRV_VERSION_BUILD 14
52 #define DRV_VERSION __stringify(DRV_VERSION_MAJOR) "." \
53              __stringify(DRV_VERSION_MINOR) "." \
54              __stringify(DRV_VERSION_BUILD)    DRV_KERN
55 const char i40e_driver_version_str[] = DRV_VERSION;
56 static const char i40e_copyright[] = "Copyright (c) 2013 - 2014 Intel Corporation.";
57
58 /* a bit of forward declarations */
59 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
60 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
61 static int i40e_add_vsi(struct i40e_vsi *vsi);
62 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
63 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit);
64 static int i40e_setup_misc_vector(struct i40e_pf *pf);
65 static void i40e_determine_queue_usage(struct i40e_pf *pf);
66 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
67 static void i40e_prep_for_reset(struct i40e_pf *pf, bool lock_acquired);
68 static int i40e_reset(struct i40e_pf *pf);
69 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
70 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
71 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
72
73 /* i40e_pci_tbl - PCI Device ID Table
74  *
75  * Last entry must be all 0s
76  *
77  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
78  *   Class, Class Mask, private data (not used) }
79  */
80 static const struct pci_device_id i40e_pci_tbl[] = {
81         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
82         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
83         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
84         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
85         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
86         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
87         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
88         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
89         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
90         {PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
91         {PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
92         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
93         {PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
94         {PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
95         {PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
96         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
97         {PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
98         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
99         {PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
100         /* required last entry */
101         {0, }
102 };
103 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
104
105 #define I40E_MAX_VF_COUNT 128
106 static int debug = -1;
107 module_param(debug, uint, 0);
108 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
109
110 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
111 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
112 MODULE_LICENSE("GPL");
113 MODULE_VERSION(DRV_VERSION);
114
115 static struct workqueue_struct *i40e_wq;
116
117 /**
118  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
119  * @hw:   pointer to the HW structure
120  * @mem:  ptr to mem struct to fill out
121  * @size: size of memory requested
122  * @alignment: what to align the allocation to
123  **/
124 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
125                             u64 size, u32 alignment)
126 {
127         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
128
129         mem->size = ALIGN(size, alignment);
130         mem->va = dma_zalloc_coherent(&pf->pdev->dev, mem->size,
131                                       &mem->pa, GFP_KERNEL);
132         if (!mem->va)
133                 return -ENOMEM;
134
135         return 0;
136 }
137
138 /**
139  * i40e_free_dma_mem_d - OS specific memory free for shared code
140  * @hw:   pointer to the HW structure
141  * @mem:  ptr to mem struct to free
142  **/
143 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
144 {
145         struct i40e_pf *pf = (struct i40e_pf *)hw->back;
146
147         dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
148         mem->va = NULL;
149         mem->pa = 0;
150         mem->size = 0;
151
152         return 0;
153 }
154
155 /**
156  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
157  * @hw:   pointer to the HW structure
158  * @mem:  ptr to mem struct to fill out
159  * @size: size of memory requested
160  **/
161 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
162                              u32 size)
163 {
164         mem->size = size;
165         mem->va = kzalloc(size, GFP_KERNEL);
166
167         if (!mem->va)
168                 return -ENOMEM;
169
170         return 0;
171 }
172
173 /**
174  * i40e_free_virt_mem_d - OS specific memory free for shared code
175  * @hw:   pointer to the HW structure
176  * @mem:  ptr to mem struct to free
177  **/
178 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
179 {
180         /* it's ok to kfree a NULL pointer */
181         kfree(mem->va);
182         mem->va = NULL;
183         mem->size = 0;
184
185         return 0;
186 }
187
188 /**
189  * i40e_get_lump - find a lump of free generic resource
190  * @pf: board private structure
191  * @pile: the pile of resource to search
192  * @needed: the number of items needed
193  * @id: an owner id to stick on the items assigned
194  *
195  * Returns the base item index of the lump, or negative for error
196  *
197  * The search_hint trick and lack of advanced fit-finding only work
198  * because we're highly likely to have all the same size lump requests.
199  * Linear search time and any fragmentation should be minimal.
200  **/
201 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
202                          u16 needed, u16 id)
203 {
204         int ret = -ENOMEM;
205         int i, j;
206
207         if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
208                 dev_info(&pf->pdev->dev,
209                          "param err: pile=%p needed=%d id=0x%04x\n",
210                          pile, needed, id);
211                 return -EINVAL;
212         }
213
214         /* start the linear search with an imperfect hint */
215         i = pile->search_hint;
216         while (i < pile->num_entries) {
217                 /* skip already allocated entries */
218                 if (pile->list[i] & I40E_PILE_VALID_BIT) {
219                         i++;
220                         continue;
221                 }
222
223                 /* do we have enough in this lump? */
224                 for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
225                         if (pile->list[i+j] & I40E_PILE_VALID_BIT)
226                                 break;
227                 }
228
229                 if (j == needed) {
230                         /* there was enough, so assign it to the requestor */
231                         for (j = 0; j < needed; j++)
232                                 pile->list[i+j] = id | I40E_PILE_VALID_BIT;
233                         ret = i;
234                         pile->search_hint = i + j;
235                         break;
236                 }
237
238                 /* not enough, so skip over it and continue looking */
239                 i += j;
240         }
241
242         return ret;
243 }
244
245 /**
246  * i40e_put_lump - return a lump of generic resource
247  * @pile: the pile of resource to search
248  * @index: the base item index
249  * @id: the owner id of the items assigned
250  *
251  * Returns the count of items in the lump
252  **/
253 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
254 {
255         int valid_id = (id | I40E_PILE_VALID_BIT);
256         int count = 0;
257         int i;
258
259         if (!pile || index >= pile->num_entries)
260                 return -EINVAL;
261
262         for (i = index;
263              i < pile->num_entries && pile->list[i] == valid_id;
264              i++) {
265                 pile->list[i] = 0;
266                 count++;
267         }
268
269         if (count && index < pile->search_hint)
270                 pile->search_hint = index;
271
272         return count;
273 }
274
275 /**
276  * i40e_find_vsi_from_id - searches for the vsi with the given id
277  * @pf - the pf structure to search for the vsi
278  * @id - id of the vsi it is searching for
279  **/
280 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
281 {
282         int i;
283
284         for (i = 0; i < pf->num_alloc_vsi; i++)
285                 if (pf->vsi[i] && (pf->vsi[i]->id == id))
286                         return pf->vsi[i];
287
288         return NULL;
289 }
290
291 /**
292  * i40e_service_event_schedule - Schedule the service task to wake up
293  * @pf: board private structure
294  *
295  * If not already scheduled, this puts the task into the work queue
296  **/
297 void i40e_service_event_schedule(struct i40e_pf *pf)
298 {
299         if (!test_bit(__I40E_DOWN, pf->state) &&
300             !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
301                 queue_work(i40e_wq, &pf->service_task);
302 }
303
304 /**
305  * i40e_tx_timeout - Respond to a Tx Hang
306  * @netdev: network interface device structure
307  *
308  * If any port has noticed a Tx timeout, it is likely that the whole
309  * device is munged, not just the one netdev port, so go for the full
310  * reset.
311  **/
312 static void i40e_tx_timeout(struct net_device *netdev)
313 {
314         struct i40e_netdev_priv *np = netdev_priv(netdev);
315         struct i40e_vsi *vsi = np->vsi;
316         struct i40e_pf *pf = vsi->back;
317         struct i40e_ring *tx_ring = NULL;
318         unsigned int i, hung_queue = 0;
319         u32 head, val;
320
321         pf->tx_timeout_count++;
322
323         /* find the stopped queue the same way the stack does */
324         for (i = 0; i < netdev->num_tx_queues; i++) {
325                 struct netdev_queue *q;
326                 unsigned long trans_start;
327
328                 q = netdev_get_tx_queue(netdev, i);
329                 trans_start = q->trans_start;
330                 if (netif_xmit_stopped(q) &&
331                     time_after(jiffies,
332                                (trans_start + netdev->watchdog_timeo))) {
333                         hung_queue = i;
334                         break;
335                 }
336         }
337
338         if (i == netdev->num_tx_queues) {
339                 netdev_info(netdev, "tx_timeout: no netdev hung queue found\n");
340         } else {
341                 /* now that we have an index, find the tx_ring struct */
342                 for (i = 0; i < vsi->num_queue_pairs; i++) {
343                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
344                                 if (hung_queue ==
345                                     vsi->tx_rings[i]->queue_index) {
346                                         tx_ring = vsi->tx_rings[i];
347                                         break;
348                                 }
349                         }
350                 }
351         }
352
353         if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
354                 pf->tx_timeout_recovery_level = 1;  /* reset after some time */
355         else if (time_before(jiffies,
356                       (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
357                 return;   /* don't do any new action before the next timeout */
358
359         if (tx_ring) {
360                 head = i40e_get_head(tx_ring);
361                 /* Read interrupt register */
362                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
363                         val = rd32(&pf->hw,
364                              I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
365                                                 tx_ring->vsi->base_vector - 1));
366                 else
367                         val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
368
369                 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",
370                             vsi->seid, hung_queue, tx_ring->next_to_clean,
371                             head, tx_ring->next_to_use,
372                             readl(tx_ring->tail), val);
373         }
374
375         pf->tx_timeout_last_recovery = jiffies;
376         netdev_info(netdev, "tx_timeout recovery level %d, hung_queue %d\n",
377                     pf->tx_timeout_recovery_level, hung_queue);
378
379         switch (pf->tx_timeout_recovery_level) {
380         case 1:
381                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
382                 break;
383         case 2:
384                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
385                 break;
386         case 3:
387                 set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
388                 break;
389         default:
390                 netdev_err(netdev, "tx_timeout recovery unsuccessful\n");
391                 break;
392         }
393
394         i40e_service_event_schedule(pf);
395         pf->tx_timeout_recovery_level++;
396 }
397
398 /**
399  * i40e_get_vsi_stats_struct - Get System Network Statistics
400  * @vsi: the VSI we care about
401  *
402  * Returns the address of the device statistics structure.
403  * The statistics are actually updated from the service task.
404  **/
405 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
406 {
407         return &vsi->net_stats;
408 }
409
410 /**
411  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
412  * @ring: Tx ring to get statistics from
413  * @stats: statistics entry to be updated
414  **/
415 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
416                                             struct rtnl_link_stats64 *stats)
417 {
418         u64 bytes, packets;
419         unsigned int start;
420
421         do {
422                 start = u64_stats_fetch_begin_irq(&ring->syncp);
423                 packets = ring->stats.packets;
424                 bytes   = ring->stats.bytes;
425         } while (u64_stats_fetch_retry_irq(&ring->syncp, start));
426
427         stats->tx_packets += packets;
428         stats->tx_bytes   += bytes;
429 }
430
431 /**
432  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
433  * @netdev: network interface device structure
434  *
435  * Returns the address of the device statistics structure.
436  * The statistics are actually updated from the service task.
437  **/
438 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
439                                   struct rtnl_link_stats64 *stats)
440 {
441         struct i40e_netdev_priv *np = netdev_priv(netdev);
442         struct i40e_ring *tx_ring, *rx_ring;
443         struct i40e_vsi *vsi = np->vsi;
444         struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
445         int i;
446
447         if (test_bit(__I40E_VSI_DOWN, vsi->state))
448                 return;
449
450         if (!vsi->tx_rings)
451                 return;
452
453         rcu_read_lock();
454         for (i = 0; i < vsi->num_queue_pairs; i++) {
455                 u64 bytes, packets;
456                 unsigned int start;
457
458                 tx_ring = ACCESS_ONCE(vsi->tx_rings[i]);
459                 if (!tx_ring)
460                         continue;
461                 i40e_get_netdev_stats_struct_tx(tx_ring, stats);
462
463                 rx_ring = &tx_ring[1];
464
465                 do {
466                         start = u64_stats_fetch_begin_irq(&rx_ring->syncp);
467                         packets = rx_ring->stats.packets;
468                         bytes   = rx_ring->stats.bytes;
469                 } while (u64_stats_fetch_retry_irq(&rx_ring->syncp, start));
470
471                 stats->rx_packets += packets;
472                 stats->rx_bytes   += bytes;
473
474                 if (i40e_enabled_xdp_vsi(vsi))
475                         i40e_get_netdev_stats_struct_tx(&rx_ring[1], stats);
476         }
477         rcu_read_unlock();
478
479         /* following stats updated by i40e_watchdog_subtask() */
480         stats->multicast        = vsi_stats->multicast;
481         stats->tx_errors        = vsi_stats->tx_errors;
482         stats->tx_dropped       = vsi_stats->tx_dropped;
483         stats->rx_errors        = vsi_stats->rx_errors;
484         stats->rx_dropped       = vsi_stats->rx_dropped;
485         stats->rx_crc_errors    = vsi_stats->rx_crc_errors;
486         stats->rx_length_errors = vsi_stats->rx_length_errors;
487 }
488
489 /**
490  * i40e_vsi_reset_stats - Resets all stats of the given vsi
491  * @vsi: the VSI to have its stats reset
492  **/
493 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
494 {
495         struct rtnl_link_stats64 *ns;
496         int i;
497
498         if (!vsi)
499                 return;
500
501         ns = i40e_get_vsi_stats_struct(vsi);
502         memset(ns, 0, sizeof(*ns));
503         memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
504         memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
505         memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
506         if (vsi->rx_rings && vsi->rx_rings[0]) {
507                 for (i = 0; i < vsi->num_queue_pairs; i++) {
508                         memset(&vsi->rx_rings[i]->stats, 0,
509                                sizeof(vsi->rx_rings[i]->stats));
510                         memset(&vsi->rx_rings[i]->rx_stats, 0,
511                                sizeof(vsi->rx_rings[i]->rx_stats));
512                         memset(&vsi->tx_rings[i]->stats, 0,
513                                sizeof(vsi->tx_rings[i]->stats));
514                         memset(&vsi->tx_rings[i]->tx_stats, 0,
515                                sizeof(vsi->tx_rings[i]->tx_stats));
516                 }
517         }
518         vsi->stat_offsets_loaded = false;
519 }
520
521 /**
522  * i40e_pf_reset_stats - Reset all of the stats for the given PF
523  * @pf: the PF to be reset
524  **/
525 void i40e_pf_reset_stats(struct i40e_pf *pf)
526 {
527         int i;
528
529         memset(&pf->stats, 0, sizeof(pf->stats));
530         memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
531         pf->stat_offsets_loaded = false;
532
533         for (i = 0; i < I40E_MAX_VEB; i++) {
534                 if (pf->veb[i]) {
535                         memset(&pf->veb[i]->stats, 0,
536                                sizeof(pf->veb[i]->stats));
537                         memset(&pf->veb[i]->stats_offsets, 0,
538                                sizeof(pf->veb[i]->stats_offsets));
539                         pf->veb[i]->stat_offsets_loaded = false;
540                 }
541         }
542         pf->hw_csum_rx_error = 0;
543 }
544
545 /**
546  * i40e_stat_update48 - read and update a 48 bit stat from the chip
547  * @hw: ptr to the hardware info
548  * @hireg: the high 32 bit reg to read
549  * @loreg: the low 32 bit reg to read
550  * @offset_loaded: has the initial offset been loaded yet
551  * @offset: ptr to current offset value
552  * @stat: ptr to the stat
553  *
554  * Since the device stats are not reset at PFReset, they likely will not
555  * be zeroed when the driver starts.  We'll save the first values read
556  * and use them as offsets to be subtracted from the raw values in order
557  * to report stats that count from zero.  In the process, we also manage
558  * the potential roll-over.
559  **/
560 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
561                                bool offset_loaded, u64 *offset, u64 *stat)
562 {
563         u64 new_data;
564
565         if (hw->device_id == I40E_DEV_ID_QEMU) {
566                 new_data = rd32(hw, loreg);
567                 new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
568         } else {
569                 new_data = rd64(hw, loreg);
570         }
571         if (!offset_loaded)
572                 *offset = new_data;
573         if (likely(new_data >= *offset))
574                 *stat = new_data - *offset;
575         else
576                 *stat = (new_data + BIT_ULL(48)) - *offset;
577         *stat &= 0xFFFFFFFFFFFFULL;
578 }
579
580 /**
581  * i40e_stat_update32 - read and update a 32 bit stat from the chip
582  * @hw: ptr to the hardware info
583  * @reg: the hw reg to read
584  * @offset_loaded: has the initial offset been loaded yet
585  * @offset: ptr to current offset value
586  * @stat: ptr to the stat
587  **/
588 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
589                                bool offset_loaded, u64 *offset, u64 *stat)
590 {
591         u32 new_data;
592
593         new_data = rd32(hw, reg);
594         if (!offset_loaded)
595                 *offset = new_data;
596         if (likely(new_data >= *offset))
597                 *stat = (u32)(new_data - *offset);
598         else
599                 *stat = (u32)((new_data + BIT_ULL(32)) - *offset);
600 }
601
602 /**
603  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
604  * @vsi: the VSI to be updated
605  **/
606 void i40e_update_eth_stats(struct i40e_vsi *vsi)
607 {
608         int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
609         struct i40e_pf *pf = vsi->back;
610         struct i40e_hw *hw = &pf->hw;
611         struct i40e_eth_stats *oes;
612         struct i40e_eth_stats *es;     /* device's eth stats */
613
614         es = &vsi->eth_stats;
615         oes = &vsi->eth_stats_offsets;
616
617         /* Gather up the stats that the hw collects */
618         i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
619                            vsi->stat_offsets_loaded,
620                            &oes->tx_errors, &es->tx_errors);
621         i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
622                            vsi->stat_offsets_loaded,
623                            &oes->rx_discards, &es->rx_discards);
624         i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
625                            vsi->stat_offsets_loaded,
626                            &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
627         i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
628                            vsi->stat_offsets_loaded,
629                            &oes->tx_errors, &es->tx_errors);
630
631         i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
632                            I40E_GLV_GORCL(stat_idx),
633                            vsi->stat_offsets_loaded,
634                            &oes->rx_bytes, &es->rx_bytes);
635         i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
636                            I40E_GLV_UPRCL(stat_idx),
637                            vsi->stat_offsets_loaded,
638                            &oes->rx_unicast, &es->rx_unicast);
639         i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
640                            I40E_GLV_MPRCL(stat_idx),
641                            vsi->stat_offsets_loaded,
642                            &oes->rx_multicast, &es->rx_multicast);
643         i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
644                            I40E_GLV_BPRCL(stat_idx),
645                            vsi->stat_offsets_loaded,
646                            &oes->rx_broadcast, &es->rx_broadcast);
647
648         i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
649                            I40E_GLV_GOTCL(stat_idx),
650                            vsi->stat_offsets_loaded,
651                            &oes->tx_bytes, &es->tx_bytes);
652         i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
653                            I40E_GLV_UPTCL(stat_idx),
654                            vsi->stat_offsets_loaded,
655                            &oes->tx_unicast, &es->tx_unicast);
656         i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
657                            I40E_GLV_MPTCL(stat_idx),
658                            vsi->stat_offsets_loaded,
659                            &oes->tx_multicast, &es->tx_multicast);
660         i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
661                            I40E_GLV_BPTCL(stat_idx),
662                            vsi->stat_offsets_loaded,
663                            &oes->tx_broadcast, &es->tx_broadcast);
664         vsi->stat_offsets_loaded = true;
665 }
666
667 /**
668  * i40e_update_veb_stats - Update Switch component statistics
669  * @veb: the VEB being updated
670  **/
671 static void i40e_update_veb_stats(struct i40e_veb *veb)
672 {
673         struct i40e_pf *pf = veb->pf;
674         struct i40e_hw *hw = &pf->hw;
675         struct i40e_eth_stats *oes;
676         struct i40e_eth_stats *es;     /* device's eth stats */
677         struct i40e_veb_tc_stats *veb_oes;
678         struct i40e_veb_tc_stats *veb_es;
679         int i, idx = 0;
680
681         idx = veb->stats_idx;
682         es = &veb->stats;
683         oes = &veb->stats_offsets;
684         veb_es = &veb->tc_stats;
685         veb_oes = &veb->tc_stats_offsets;
686
687         /* Gather up the stats that the hw collects */
688         i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
689                            veb->stat_offsets_loaded,
690                            &oes->tx_discards, &es->tx_discards);
691         if (hw->revision_id > 0)
692                 i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
693                                    veb->stat_offsets_loaded,
694                                    &oes->rx_unknown_protocol,
695                                    &es->rx_unknown_protocol);
696         i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
697                            veb->stat_offsets_loaded,
698                            &oes->rx_bytes, &es->rx_bytes);
699         i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
700                            veb->stat_offsets_loaded,
701                            &oes->rx_unicast, &es->rx_unicast);
702         i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
703                            veb->stat_offsets_loaded,
704                            &oes->rx_multicast, &es->rx_multicast);
705         i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
706                            veb->stat_offsets_loaded,
707                            &oes->rx_broadcast, &es->rx_broadcast);
708
709         i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
710                            veb->stat_offsets_loaded,
711                            &oes->tx_bytes, &es->tx_bytes);
712         i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
713                            veb->stat_offsets_loaded,
714                            &oes->tx_unicast, &es->tx_unicast);
715         i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
716                            veb->stat_offsets_loaded,
717                            &oes->tx_multicast, &es->tx_multicast);
718         i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
719                            veb->stat_offsets_loaded,
720                            &oes->tx_broadcast, &es->tx_broadcast);
721         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
722                 i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
723                                    I40E_GLVEBTC_RPCL(i, idx),
724                                    veb->stat_offsets_loaded,
725                                    &veb_oes->tc_rx_packets[i],
726                                    &veb_es->tc_rx_packets[i]);
727                 i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
728                                    I40E_GLVEBTC_RBCL(i, idx),
729                                    veb->stat_offsets_loaded,
730                                    &veb_oes->tc_rx_bytes[i],
731                                    &veb_es->tc_rx_bytes[i]);
732                 i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
733                                    I40E_GLVEBTC_TPCL(i, idx),
734                                    veb->stat_offsets_loaded,
735                                    &veb_oes->tc_tx_packets[i],
736                                    &veb_es->tc_tx_packets[i]);
737                 i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
738                                    I40E_GLVEBTC_TBCL(i, idx),
739                                    veb->stat_offsets_loaded,
740                                    &veb_oes->tc_tx_bytes[i],
741                                    &veb_es->tc_tx_bytes[i]);
742         }
743         veb->stat_offsets_loaded = true;
744 }
745
746 /**
747  * i40e_update_vsi_stats - Update the vsi statistics counters.
748  * @vsi: the VSI to be updated
749  *
750  * There are a few instances where we store the same stat in a
751  * couple of different structs.  This is partly because we have
752  * the netdev stats that need to be filled out, which is slightly
753  * different from the "eth_stats" defined by the chip and used in
754  * VF communications.  We sort it out here.
755  **/
756 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
757 {
758         struct i40e_pf *pf = vsi->back;
759         struct rtnl_link_stats64 *ons;
760         struct rtnl_link_stats64 *ns;   /* netdev stats */
761         struct i40e_eth_stats *oes;
762         struct i40e_eth_stats *es;     /* device's eth stats */
763         u32 tx_restart, tx_busy;
764         struct i40e_ring *p;
765         u32 rx_page, rx_buf;
766         u64 bytes, packets;
767         unsigned int start;
768         u64 tx_linearize;
769         u64 tx_force_wb;
770         u64 rx_p, rx_b;
771         u64 tx_p, tx_b;
772         u16 q;
773
774         if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
775             test_bit(__I40E_CONFIG_BUSY, pf->state))
776                 return;
777
778         ns = i40e_get_vsi_stats_struct(vsi);
779         ons = &vsi->net_stats_offsets;
780         es = &vsi->eth_stats;
781         oes = &vsi->eth_stats_offsets;
782
783         /* Gather up the netdev and vsi stats that the driver collects
784          * on the fly during packet processing
785          */
786         rx_b = rx_p = 0;
787         tx_b = tx_p = 0;
788         tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
789         rx_page = 0;
790         rx_buf = 0;
791         rcu_read_lock();
792         for (q = 0; q < vsi->num_queue_pairs; q++) {
793                 /* locate Tx ring */
794                 p = ACCESS_ONCE(vsi->tx_rings[q]);
795
796                 do {
797                         start = u64_stats_fetch_begin_irq(&p->syncp);
798                         packets = p->stats.packets;
799                         bytes = p->stats.bytes;
800                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
801                 tx_b += bytes;
802                 tx_p += packets;
803                 tx_restart += p->tx_stats.restart_queue;
804                 tx_busy += p->tx_stats.tx_busy;
805                 tx_linearize += p->tx_stats.tx_linearize;
806                 tx_force_wb += p->tx_stats.tx_force_wb;
807
808                 /* Rx queue is part of the same block as Tx queue */
809                 p = &p[1];
810                 do {
811                         start = u64_stats_fetch_begin_irq(&p->syncp);
812                         packets = p->stats.packets;
813                         bytes = p->stats.bytes;
814                 } while (u64_stats_fetch_retry_irq(&p->syncp, start));
815                 rx_b += bytes;
816                 rx_p += packets;
817                 rx_buf += p->rx_stats.alloc_buff_failed;
818                 rx_page += p->rx_stats.alloc_page_failed;
819         }
820         rcu_read_unlock();
821         vsi->tx_restart = tx_restart;
822         vsi->tx_busy = tx_busy;
823         vsi->tx_linearize = tx_linearize;
824         vsi->tx_force_wb = tx_force_wb;
825         vsi->rx_page_failed = rx_page;
826         vsi->rx_buf_failed = rx_buf;
827
828         ns->rx_packets = rx_p;
829         ns->rx_bytes = rx_b;
830         ns->tx_packets = tx_p;
831         ns->tx_bytes = tx_b;
832
833         /* update netdev stats from eth stats */
834         i40e_update_eth_stats(vsi);
835         ons->tx_errors = oes->tx_errors;
836         ns->tx_errors = es->tx_errors;
837         ons->multicast = oes->rx_multicast;
838         ns->multicast = es->rx_multicast;
839         ons->rx_dropped = oes->rx_discards;
840         ns->rx_dropped = es->rx_discards;
841         ons->tx_dropped = oes->tx_discards;
842         ns->tx_dropped = es->tx_discards;
843
844         /* pull in a couple PF stats if this is the main vsi */
845         if (vsi == pf->vsi[pf->lan_vsi]) {
846                 ns->rx_crc_errors = pf->stats.crc_errors;
847                 ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
848                 ns->rx_length_errors = pf->stats.rx_length_errors;
849         }
850 }
851
852 /**
853  * i40e_update_pf_stats - Update the PF statistics counters.
854  * @pf: the PF to be updated
855  **/
856 static void i40e_update_pf_stats(struct i40e_pf *pf)
857 {
858         struct i40e_hw_port_stats *osd = &pf->stats_offsets;
859         struct i40e_hw_port_stats *nsd = &pf->stats;
860         struct i40e_hw *hw = &pf->hw;
861         u32 val;
862         int i;
863
864         i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
865                            I40E_GLPRT_GORCL(hw->port),
866                            pf->stat_offsets_loaded,
867                            &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
868         i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
869                            I40E_GLPRT_GOTCL(hw->port),
870                            pf->stat_offsets_loaded,
871                            &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
872         i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
873                            pf->stat_offsets_loaded,
874                            &osd->eth.rx_discards,
875                            &nsd->eth.rx_discards);
876         i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
877                            I40E_GLPRT_UPRCL(hw->port),
878                            pf->stat_offsets_loaded,
879                            &osd->eth.rx_unicast,
880                            &nsd->eth.rx_unicast);
881         i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
882                            I40E_GLPRT_MPRCL(hw->port),
883                            pf->stat_offsets_loaded,
884                            &osd->eth.rx_multicast,
885                            &nsd->eth.rx_multicast);
886         i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
887                            I40E_GLPRT_BPRCL(hw->port),
888                            pf->stat_offsets_loaded,
889                            &osd->eth.rx_broadcast,
890                            &nsd->eth.rx_broadcast);
891         i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
892                            I40E_GLPRT_UPTCL(hw->port),
893                            pf->stat_offsets_loaded,
894                            &osd->eth.tx_unicast,
895                            &nsd->eth.tx_unicast);
896         i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
897                            I40E_GLPRT_MPTCL(hw->port),
898                            pf->stat_offsets_loaded,
899                            &osd->eth.tx_multicast,
900                            &nsd->eth.tx_multicast);
901         i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
902                            I40E_GLPRT_BPTCL(hw->port),
903                            pf->stat_offsets_loaded,
904                            &osd->eth.tx_broadcast,
905                            &nsd->eth.tx_broadcast);
906
907         i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
908                            pf->stat_offsets_loaded,
909                            &osd->tx_dropped_link_down,
910                            &nsd->tx_dropped_link_down);
911
912         i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
913                            pf->stat_offsets_loaded,
914                            &osd->crc_errors, &nsd->crc_errors);
915
916         i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
917                            pf->stat_offsets_loaded,
918                            &osd->illegal_bytes, &nsd->illegal_bytes);
919
920         i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
921                            pf->stat_offsets_loaded,
922                            &osd->mac_local_faults,
923                            &nsd->mac_local_faults);
924         i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
925                            pf->stat_offsets_loaded,
926                            &osd->mac_remote_faults,
927                            &nsd->mac_remote_faults);
928
929         i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
930                            pf->stat_offsets_loaded,
931                            &osd->rx_length_errors,
932                            &nsd->rx_length_errors);
933
934         i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
935                            pf->stat_offsets_loaded,
936                            &osd->link_xon_rx, &nsd->link_xon_rx);
937         i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
938                            pf->stat_offsets_loaded,
939                            &osd->link_xon_tx, &nsd->link_xon_tx);
940         i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
941                            pf->stat_offsets_loaded,
942                            &osd->link_xoff_rx, &nsd->link_xoff_rx);
943         i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
944                            pf->stat_offsets_loaded,
945                            &osd->link_xoff_tx, &nsd->link_xoff_tx);
946
947         for (i = 0; i < 8; i++) {
948                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
949                                    pf->stat_offsets_loaded,
950                                    &osd->priority_xoff_rx[i],
951                                    &nsd->priority_xoff_rx[i]);
952                 i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
953                                    pf->stat_offsets_loaded,
954                                    &osd->priority_xon_rx[i],
955                                    &nsd->priority_xon_rx[i]);
956                 i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
957                                    pf->stat_offsets_loaded,
958                                    &osd->priority_xon_tx[i],
959                                    &nsd->priority_xon_tx[i]);
960                 i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
961                                    pf->stat_offsets_loaded,
962                                    &osd->priority_xoff_tx[i],
963                                    &nsd->priority_xoff_tx[i]);
964                 i40e_stat_update32(hw,
965                                    I40E_GLPRT_RXON2OFFCNT(hw->port, i),
966                                    pf->stat_offsets_loaded,
967                                    &osd->priority_xon_2_xoff[i],
968                                    &nsd->priority_xon_2_xoff[i]);
969         }
970
971         i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
972                            I40E_GLPRT_PRC64L(hw->port),
973                            pf->stat_offsets_loaded,
974                            &osd->rx_size_64, &nsd->rx_size_64);
975         i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
976                            I40E_GLPRT_PRC127L(hw->port),
977                            pf->stat_offsets_loaded,
978                            &osd->rx_size_127, &nsd->rx_size_127);
979         i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
980                            I40E_GLPRT_PRC255L(hw->port),
981                            pf->stat_offsets_loaded,
982                            &osd->rx_size_255, &nsd->rx_size_255);
983         i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
984                            I40E_GLPRT_PRC511L(hw->port),
985                            pf->stat_offsets_loaded,
986                            &osd->rx_size_511, &nsd->rx_size_511);
987         i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
988                            I40E_GLPRT_PRC1023L(hw->port),
989                            pf->stat_offsets_loaded,
990                            &osd->rx_size_1023, &nsd->rx_size_1023);
991         i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
992                            I40E_GLPRT_PRC1522L(hw->port),
993                            pf->stat_offsets_loaded,
994                            &osd->rx_size_1522, &nsd->rx_size_1522);
995         i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
996                            I40E_GLPRT_PRC9522L(hw->port),
997                            pf->stat_offsets_loaded,
998                            &osd->rx_size_big, &nsd->rx_size_big);
999
1000         i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1001                            I40E_GLPRT_PTC64L(hw->port),
1002                            pf->stat_offsets_loaded,
1003                            &osd->tx_size_64, &nsd->tx_size_64);
1004         i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1005                            I40E_GLPRT_PTC127L(hw->port),
1006                            pf->stat_offsets_loaded,
1007                            &osd->tx_size_127, &nsd->tx_size_127);
1008         i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1009                            I40E_GLPRT_PTC255L(hw->port),
1010                            pf->stat_offsets_loaded,
1011                            &osd->tx_size_255, &nsd->tx_size_255);
1012         i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1013                            I40E_GLPRT_PTC511L(hw->port),
1014                            pf->stat_offsets_loaded,
1015                            &osd->tx_size_511, &nsd->tx_size_511);
1016         i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1017                            I40E_GLPRT_PTC1023L(hw->port),
1018                            pf->stat_offsets_loaded,
1019                            &osd->tx_size_1023, &nsd->tx_size_1023);
1020         i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1021                            I40E_GLPRT_PTC1522L(hw->port),
1022                            pf->stat_offsets_loaded,
1023                            &osd->tx_size_1522, &nsd->tx_size_1522);
1024         i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1025                            I40E_GLPRT_PTC9522L(hw->port),
1026                            pf->stat_offsets_loaded,
1027                            &osd->tx_size_big, &nsd->tx_size_big);
1028
1029         i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1030                            pf->stat_offsets_loaded,
1031                            &osd->rx_undersize, &nsd->rx_undersize);
1032         i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1033                            pf->stat_offsets_loaded,
1034                            &osd->rx_fragments, &nsd->rx_fragments);
1035         i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1036                            pf->stat_offsets_loaded,
1037                            &osd->rx_oversize, &nsd->rx_oversize);
1038         i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1039                            pf->stat_offsets_loaded,
1040                            &osd->rx_jabber, &nsd->rx_jabber);
1041
1042         /* FDIR stats */
1043         i40e_stat_update32(hw,
1044                            I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(pf->hw.pf_id)),
1045                            pf->stat_offsets_loaded,
1046                            &osd->fd_atr_match, &nsd->fd_atr_match);
1047         i40e_stat_update32(hw,
1048                            I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(pf->hw.pf_id)),
1049                            pf->stat_offsets_loaded,
1050                            &osd->fd_sb_match, &nsd->fd_sb_match);
1051         i40e_stat_update32(hw,
1052                       I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(pf->hw.pf_id)),
1053                       pf->stat_offsets_loaded,
1054                       &osd->fd_atr_tunnel_match, &nsd->fd_atr_tunnel_match);
1055
1056         val = rd32(hw, I40E_PRTPM_EEE_STAT);
1057         nsd->tx_lpi_status =
1058                        (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1059                         I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1060         nsd->rx_lpi_status =
1061                        (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1062                         I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1063         i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1064                            pf->stat_offsets_loaded,
1065                            &osd->tx_lpi_count, &nsd->tx_lpi_count);
1066         i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1067                            pf->stat_offsets_loaded,
1068                            &osd->rx_lpi_count, &nsd->rx_lpi_count);
1069
1070         if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1071             !(pf->flags & I40E_FLAG_FD_SB_AUTO_DISABLED))
1072                 nsd->fd_sb_status = true;
1073         else
1074                 nsd->fd_sb_status = false;
1075
1076         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1077             !(pf->flags & I40E_FLAG_FD_ATR_AUTO_DISABLED))
1078                 nsd->fd_atr_status = true;
1079         else
1080                 nsd->fd_atr_status = false;
1081
1082         pf->stat_offsets_loaded = true;
1083 }
1084
1085 /**
1086  * i40e_update_stats - Update the various statistics counters.
1087  * @vsi: the VSI to be updated
1088  *
1089  * Update the various stats for this VSI and its related entities.
1090  **/
1091 void i40e_update_stats(struct i40e_vsi *vsi)
1092 {
1093         struct i40e_pf *pf = vsi->back;
1094
1095         if (vsi == pf->vsi[pf->lan_vsi])
1096                 i40e_update_pf_stats(pf);
1097
1098         i40e_update_vsi_stats(vsi);
1099 }
1100
1101 /**
1102  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1103  * @vsi: the VSI to be searched
1104  * @macaddr: the MAC address
1105  * @vlan: the vlan
1106  *
1107  * Returns ptr to the filter object or NULL
1108  **/
1109 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1110                                                 const u8 *macaddr, s16 vlan)
1111 {
1112         struct i40e_mac_filter *f;
1113         u64 key;
1114
1115         if (!vsi || !macaddr)
1116                 return NULL;
1117
1118         key = i40e_addr_to_hkey(macaddr);
1119         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1120                 if ((ether_addr_equal(macaddr, f->macaddr)) &&
1121                     (vlan == f->vlan))
1122                         return f;
1123         }
1124         return NULL;
1125 }
1126
1127 /**
1128  * i40e_find_mac - Find a mac addr in the macvlan filters list
1129  * @vsi: the VSI to be searched
1130  * @macaddr: the MAC address we are searching for
1131  *
1132  * Returns the first filter with the provided MAC address or NULL if
1133  * MAC address was not found
1134  **/
1135 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1136 {
1137         struct i40e_mac_filter *f;
1138         u64 key;
1139
1140         if (!vsi || !macaddr)
1141                 return NULL;
1142
1143         key = i40e_addr_to_hkey(macaddr);
1144         hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1145                 if ((ether_addr_equal(macaddr, f->macaddr)))
1146                         return f;
1147         }
1148         return NULL;
1149 }
1150
1151 /**
1152  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1153  * @vsi: the VSI to be searched
1154  *
1155  * Returns true if VSI is in vlan mode or false otherwise
1156  **/
1157 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1158 {
1159         /* If we have a PVID, always operate in VLAN mode */
1160         if (vsi->info.pvid)
1161                 return true;
1162
1163         /* We need to operate in VLAN mode whenever we have any filters with
1164          * a VLAN other than I40E_VLAN_ALL. We could check the table each
1165          * time, incurring search cost repeatedly. However, we can notice two
1166          * things:
1167          *
1168          * 1) the only place where we can gain a VLAN filter is in
1169          *    i40e_add_filter.
1170          *
1171          * 2) the only place where filters are actually removed is in
1172          *    i40e_sync_filters_subtask.
1173          *
1174          * Thus, we can simply use a boolean value, has_vlan_filters which we
1175          * will set to true when we add a VLAN filter in i40e_add_filter. Then
1176          * we have to perform the full search after deleting filters in
1177          * i40e_sync_filters_subtask, but we already have to search
1178          * filters here and can perform the check at the same time. This
1179          * results in avoiding embedding a loop for VLAN mode inside another
1180          * loop over all the filters, and should maintain correctness as noted
1181          * above.
1182          */
1183         return vsi->has_vlan_filter;
1184 }
1185
1186 /**
1187  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1188  * @vsi: the VSI to configure
1189  * @tmp_add_list: list of filters ready to be added
1190  * @tmp_del_list: list of filters ready to be deleted
1191  * @vlan_filters: the number of active VLAN filters
1192  *
1193  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1194  * behave as expected. If we have any active VLAN filters remaining or about
1195  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1196  * so that they only match against untagged traffic. If we no longer have any
1197  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1198  * so that they match against both tagged and untagged traffic. In this way,
1199  * we ensure that we correctly receive the desired traffic. This ensures that
1200  * when we have an active VLAN we will receive only untagged traffic and
1201  * traffic matching active VLANs. If we have no active VLANs then we will
1202  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1203  *
1204  * Finally, in a similar fashion, this function also corrects filters when
1205  * there is an active PVID assigned to this VSI.
1206  *
1207  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1208  *
1209  * This function is only expected to be called from within
1210  * i40e_sync_vsi_filters.
1211  *
1212  * NOTE: This function expects to be called while under the
1213  * mac_filter_hash_lock
1214  */
1215 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1216                                          struct hlist_head *tmp_add_list,
1217                                          struct hlist_head *tmp_del_list,
1218                                          int vlan_filters)
1219 {
1220         s16 pvid = le16_to_cpu(vsi->info.pvid);
1221         struct i40e_mac_filter *f, *add_head;
1222         struct i40e_new_mac_filter *new;
1223         struct hlist_node *h;
1224         int bkt, new_vlan;
1225
1226         /* To determine if a particular filter needs to be replaced we
1227          * have the three following conditions:
1228          *
1229          * a) if we have a PVID assigned, then all filters which are
1230          *    not marked as VLAN=PVID must be replaced with filters that
1231          *    are.
1232          * b) otherwise, if we have any active VLANS, all filters
1233          *    which are marked as VLAN=-1 must be replaced with
1234          *    filters marked as VLAN=0
1235          * c) finally, if we do not have any active VLANS, all filters
1236          *    which are marked as VLAN=0 must be replaced with filters
1237          *    marked as VLAN=-1
1238          */
1239
1240         /* Update the filters about to be added in place */
1241         hlist_for_each_entry(new, tmp_add_list, hlist) {
1242                 if (pvid && new->f->vlan != pvid)
1243                         new->f->vlan = pvid;
1244                 else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1245                         new->f->vlan = 0;
1246                 else if (!vlan_filters && new->f->vlan == 0)
1247                         new->f->vlan = I40E_VLAN_ANY;
1248         }
1249
1250         /* Update the remaining active filters */
1251         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1252                 /* Combine the checks for whether a filter needs to be changed
1253                  * and then determine the new VLAN inside the if block, in
1254                  * order to avoid duplicating code for adding the new filter
1255                  * then deleting the old filter.
1256                  */
1257                 if ((pvid && f->vlan != pvid) ||
1258                     (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1259                     (!vlan_filters && f->vlan == 0)) {
1260                         /* Determine the new vlan we will be adding */
1261                         if (pvid)
1262                                 new_vlan = pvid;
1263                         else if (vlan_filters)
1264                                 new_vlan = 0;
1265                         else
1266                                 new_vlan = I40E_VLAN_ANY;
1267
1268                         /* Create the new filter */
1269                         add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1270                         if (!add_head)
1271                                 return -ENOMEM;
1272
1273                         /* Create a temporary i40e_new_mac_filter */
1274                         new = kzalloc(sizeof(*new), GFP_ATOMIC);
1275                         if (!new)
1276                                 return -ENOMEM;
1277
1278                         new->f = add_head;
1279                         new->state = add_head->state;
1280
1281                         /* Add the new filter to the tmp list */
1282                         hlist_add_head(&new->hlist, tmp_add_list);
1283
1284                         /* Put the original filter into the delete list */
1285                         f->state = I40E_FILTER_REMOVE;
1286                         hash_del(&f->hlist);
1287                         hlist_add_head(&f->hlist, tmp_del_list);
1288                 }
1289         }
1290
1291         vsi->has_vlan_filter = !!vlan_filters;
1292
1293         return 0;
1294 }
1295
1296 /**
1297  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1298  * @vsi: the PF Main VSI - inappropriate for any other VSI
1299  * @macaddr: the MAC address
1300  *
1301  * Remove whatever filter the firmware set up so the driver can manage
1302  * its own filtering intelligently.
1303  **/
1304 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1305 {
1306         struct i40e_aqc_remove_macvlan_element_data element;
1307         struct i40e_pf *pf = vsi->back;
1308
1309         /* Only appropriate for the PF main VSI */
1310         if (vsi->type != I40E_VSI_MAIN)
1311                 return;
1312
1313         memset(&element, 0, sizeof(element));
1314         ether_addr_copy(element.mac_addr, macaddr);
1315         element.vlan_tag = 0;
1316         /* Ignore error returns, some firmware does it this way... */
1317         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1318         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1319
1320         memset(&element, 0, sizeof(element));
1321         ether_addr_copy(element.mac_addr, macaddr);
1322         element.vlan_tag = 0;
1323         /* ...and some firmware does it this way. */
1324         element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1325                         I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1326         i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1327 }
1328
1329 /**
1330  * i40e_add_filter - Add a mac/vlan filter to the VSI
1331  * @vsi: the VSI to be searched
1332  * @macaddr: the MAC address
1333  * @vlan: the vlan
1334  *
1335  * Returns ptr to the filter object or NULL when no memory available.
1336  *
1337  * NOTE: This function is expected to be called with mac_filter_hash_lock
1338  * being held.
1339  **/
1340 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1341                                         const u8 *macaddr, s16 vlan)
1342 {
1343         struct i40e_mac_filter *f;
1344         u64 key;
1345
1346         if (!vsi || !macaddr)
1347                 return NULL;
1348
1349         f = i40e_find_filter(vsi, macaddr, vlan);
1350         if (!f) {
1351                 f = kzalloc(sizeof(*f), GFP_ATOMIC);
1352                 if (!f)
1353                         return NULL;
1354
1355                 /* Update the boolean indicating if we need to function in
1356                  * VLAN mode.
1357                  */
1358                 if (vlan >= 0)
1359                         vsi->has_vlan_filter = true;
1360
1361                 ether_addr_copy(f->macaddr, macaddr);
1362                 f->vlan = vlan;
1363                 /* If we're in overflow promisc mode, set the state directly
1364                  * to failed, so we don't bother to try sending the filter
1365                  * to the hardware.
1366                  */
1367                 if (test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state))
1368                         f->state = I40E_FILTER_FAILED;
1369                 else
1370                         f->state = I40E_FILTER_NEW;
1371                 INIT_HLIST_NODE(&f->hlist);
1372
1373                 key = i40e_addr_to_hkey(macaddr);
1374                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
1375
1376                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1377                 vsi->back->flags |= I40E_FLAG_FILTER_SYNC;
1378         }
1379
1380         /* If we're asked to add a filter that has been marked for removal, it
1381          * is safe to simply restore it to active state. __i40e_del_filter
1382          * will have simply deleted any filters which were previously marked
1383          * NEW or FAILED, so if it is currently marked REMOVE it must have
1384          * previously been ACTIVE. Since we haven't yet run the sync filters
1385          * task, just restore this filter to the ACTIVE state so that the
1386          * sync task leaves it in place
1387          */
1388         if (f->state == I40E_FILTER_REMOVE)
1389                 f->state = I40E_FILTER_ACTIVE;
1390
1391         return f;
1392 }
1393
1394 /**
1395  * __i40e_del_filter - Remove a specific filter from the VSI
1396  * @vsi: VSI to remove from
1397  * @f: the filter to remove from the list
1398  *
1399  * This function should be called instead of i40e_del_filter only if you know
1400  * the exact filter you will remove already, such as via i40e_find_filter or
1401  * i40e_find_mac.
1402  *
1403  * NOTE: This function is expected to be called with mac_filter_hash_lock
1404  * being held.
1405  * ANOTHER NOTE: This function MUST be called from within the context of
1406  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1407  * instead of list_for_each_entry().
1408  **/
1409 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1410 {
1411         if (!f)
1412                 return;
1413
1414         /* If the filter was never added to firmware then we can just delete it
1415          * directly and we don't want to set the status to remove or else an
1416          * admin queue command will unnecessarily fire.
1417          */
1418         if ((f->state == I40E_FILTER_FAILED) ||
1419             (f->state == I40E_FILTER_NEW)) {
1420                 hash_del(&f->hlist);
1421                 kfree(f);
1422         } else {
1423                 f->state = I40E_FILTER_REMOVE;
1424         }
1425
1426         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1427         vsi->back->flags |= I40E_FLAG_FILTER_SYNC;
1428 }
1429
1430 /**
1431  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1432  * @vsi: the VSI to be searched
1433  * @macaddr: the MAC address
1434  * @vlan: the VLAN
1435  *
1436  * NOTE: This function is expected to be called with mac_filter_hash_lock
1437  * being held.
1438  * ANOTHER NOTE: This function MUST be called from within the context of
1439  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1440  * instead of list_for_each_entry().
1441  **/
1442 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1443 {
1444         struct i40e_mac_filter *f;
1445
1446         if (!vsi || !macaddr)
1447                 return;
1448
1449         f = i40e_find_filter(vsi, macaddr, vlan);
1450         __i40e_del_filter(vsi, f);
1451 }
1452
1453 /**
1454  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1455  * @vsi: the VSI to be searched
1456  * @macaddr: the mac address to be filtered
1457  *
1458  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1459  * go through all the macvlan filters and add a macvlan filter for each
1460  * unique vlan that already exists. If a PVID has been assigned, instead only
1461  * add the macaddr to that VLAN.
1462  *
1463  * Returns last filter added on success, else NULL
1464  **/
1465 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1466                                             const u8 *macaddr)
1467 {
1468         struct i40e_mac_filter *f, *add = NULL;
1469         struct hlist_node *h;
1470         int bkt;
1471
1472         if (vsi->info.pvid)
1473                 return i40e_add_filter(vsi, macaddr,
1474                                        le16_to_cpu(vsi->info.pvid));
1475
1476         if (!i40e_is_vsi_in_vlan(vsi))
1477                 return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1478
1479         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1480                 if (f->state == I40E_FILTER_REMOVE)
1481                         continue;
1482                 add = i40e_add_filter(vsi, macaddr, f->vlan);
1483                 if (!add)
1484                         return NULL;
1485         }
1486
1487         return add;
1488 }
1489
1490 /**
1491  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1492  * @vsi: the VSI to be searched
1493  * @macaddr: the mac address to be removed
1494  *
1495  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1496  * associated with.
1497  *
1498  * Returns 0 for success, or error
1499  **/
1500 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1501 {
1502         struct i40e_mac_filter *f;
1503         struct hlist_node *h;
1504         bool found = false;
1505         int bkt;
1506
1507         WARN(!spin_is_locked(&vsi->mac_filter_hash_lock),
1508              "Missing mac_filter_hash_lock\n");
1509         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1510                 if (ether_addr_equal(macaddr, f->macaddr)) {
1511                         __i40e_del_filter(vsi, f);
1512                         found = true;
1513                 }
1514         }
1515
1516         if (found)
1517                 return 0;
1518         else
1519                 return -ENOENT;
1520 }
1521
1522 /**
1523  * i40e_set_mac - NDO callback to set mac address
1524  * @netdev: network interface device structure
1525  * @p: pointer to an address structure
1526  *
1527  * Returns 0 on success, negative on failure
1528  **/
1529 static int i40e_set_mac(struct net_device *netdev, void *p)
1530 {
1531         struct i40e_netdev_priv *np = netdev_priv(netdev);
1532         struct i40e_vsi *vsi = np->vsi;
1533         struct i40e_pf *pf = vsi->back;
1534         struct i40e_hw *hw = &pf->hw;
1535         struct sockaddr *addr = p;
1536
1537         if (!is_valid_ether_addr(addr->sa_data))
1538                 return -EADDRNOTAVAIL;
1539
1540         if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1541                 netdev_info(netdev, "already using mac address %pM\n",
1542                             addr->sa_data);
1543                 return 0;
1544         }
1545
1546         if (test_bit(__I40E_VSI_DOWN, vsi->back->state) ||
1547             test_bit(__I40E_RESET_RECOVERY_PENDING, vsi->back->state))
1548                 return -EADDRNOTAVAIL;
1549
1550         if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1551                 netdev_info(netdev, "returning to hw mac address %pM\n",
1552                             hw->mac.addr);
1553         else
1554                 netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1555
1556         /* Copy the address first, so that we avoid a possible race with
1557          * .set_rx_mode().
1558          * - Remove old address from MAC filter
1559          * - Copy new address
1560          * - Add new address to MAC filter
1561          */
1562         spin_lock_bh(&vsi->mac_filter_hash_lock);
1563         i40e_del_mac_filter(vsi, netdev->dev_addr);
1564         ether_addr_copy(netdev->dev_addr, addr->sa_data);
1565         i40e_add_mac_filter(vsi, netdev->dev_addr);
1566         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1567
1568         if (vsi->type == I40E_VSI_MAIN) {
1569                 i40e_status ret;
1570
1571                 ret = i40e_aq_mac_address_write(&vsi->back->hw,
1572                                                 I40E_AQC_WRITE_TYPE_LAA_WOL,
1573                                                 addr->sa_data, NULL);
1574                 if (ret)
1575                         netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1576                                     i40e_stat_str(hw, ret),
1577                                     i40e_aq_str(hw, hw->aq.asq_last_status));
1578         }
1579
1580         /* schedule our worker thread which will take care of
1581          * applying the new filter changes
1582          */
1583         i40e_service_event_schedule(vsi->back);
1584         return 0;
1585 }
1586
1587 /**
1588  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1589  * @vsi: the VSI being setup
1590  * @ctxt: VSI context structure
1591  * @enabled_tc: Enabled TCs bitmap
1592  * @is_add: True if called before Add VSI
1593  *
1594  * Setup VSI queue mapping for enabled traffic classes.
1595  **/
1596 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
1597                                      struct i40e_vsi_context *ctxt,
1598                                      u8 enabled_tc,
1599                                      bool is_add)
1600 {
1601         struct i40e_pf *pf = vsi->back;
1602         u16 sections = 0;
1603         u8 netdev_tc = 0;
1604         u16 numtc = 0;
1605         u16 qcount;
1606         u8 offset;
1607         u16 qmap;
1608         int i;
1609         u16 num_tc_qps = 0;
1610
1611         sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1612         offset = 0;
1613
1614         if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
1615                 /* Find numtc from enabled TC bitmap */
1616                 for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1617                         if (enabled_tc & BIT(i)) /* TC is enabled */
1618                                 numtc++;
1619                 }
1620                 if (!numtc) {
1621                         dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
1622                         numtc = 1;
1623                 }
1624         } else {
1625                 /* At least TC0 is enabled in case of non-DCB case */
1626                 numtc = 1;
1627         }
1628
1629         vsi->tc_config.numtc = numtc;
1630         vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1631         /* Number of queues per enabled TC */
1632         qcount = vsi->alloc_queue_pairs;
1633
1634         num_tc_qps = qcount / numtc;
1635         num_tc_qps = min_t(int, num_tc_qps, i40e_pf_get_max_q_per_tc(pf));
1636
1637         /* Setup queue offset/count for all TCs for given VSI */
1638         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1639                 /* See if the given TC is enabled for the given VSI */
1640                 if (vsi->tc_config.enabled_tc & BIT(i)) {
1641                         /* TC is enabled */
1642                         int pow, num_qps;
1643
1644                         switch (vsi->type) {
1645                         case I40E_VSI_MAIN:
1646                                 qcount = min_t(int, pf->alloc_rss_size,
1647                                                num_tc_qps);
1648                                 break;
1649                         case I40E_VSI_FDIR:
1650                         case I40E_VSI_SRIOV:
1651                         case I40E_VSI_VMDQ2:
1652                         default:
1653                                 qcount = num_tc_qps;
1654                                 WARN_ON(i != 0);
1655                                 break;
1656                         }
1657                         vsi->tc_config.tc_info[i].qoffset = offset;
1658                         vsi->tc_config.tc_info[i].qcount = qcount;
1659
1660                         /* find the next higher power-of-2 of num queue pairs */
1661                         num_qps = qcount;
1662                         pow = 0;
1663                         while (num_qps && (BIT_ULL(pow) < qcount)) {
1664                                 pow++;
1665                                 num_qps >>= 1;
1666                         }
1667
1668                         vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1669                         qmap =
1670                             (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1671                             (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1672
1673                         offset += qcount;
1674                 } else {
1675                         /* TC is not enabled so set the offset to
1676                          * default queue and allocate one queue
1677                          * for the given TC.
1678                          */
1679                         vsi->tc_config.tc_info[i].qoffset = 0;
1680                         vsi->tc_config.tc_info[i].qcount = 1;
1681                         vsi->tc_config.tc_info[i].netdev_tc = 0;
1682
1683                         qmap = 0;
1684                 }
1685                 ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
1686         }
1687
1688         /* Set actual Tx/Rx queue pairs */
1689         vsi->num_queue_pairs = offset;
1690         if ((vsi->type == I40E_VSI_MAIN) && (numtc == 1)) {
1691                 if (vsi->req_queue_pairs > 0)
1692                         vsi->num_queue_pairs = vsi->req_queue_pairs;
1693                 else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1694                         vsi->num_queue_pairs = pf->num_lan_msix;
1695         }
1696
1697         /* Scheduler section valid can only be set for ADD VSI */
1698         if (is_add) {
1699                 sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1700
1701                 ctxt->info.up_enable_bits = enabled_tc;
1702         }
1703         if (vsi->type == I40E_VSI_SRIOV) {
1704                 ctxt->info.mapping_flags |=
1705                                      cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
1706                 for (i = 0; i < vsi->num_queue_pairs; i++)
1707                         ctxt->info.queue_mapping[i] =
1708                                                cpu_to_le16(vsi->base_queue + i);
1709         } else {
1710                 ctxt->info.mapping_flags |=
1711                                         cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1712                 ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1713         }
1714         ctxt->info.valid_sections |= cpu_to_le16(sections);
1715 }
1716
1717 /**
1718  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
1719  * @netdev: the netdevice
1720  * @addr: address to add
1721  *
1722  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
1723  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
1724  */
1725 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
1726 {
1727         struct i40e_netdev_priv *np = netdev_priv(netdev);
1728         struct i40e_vsi *vsi = np->vsi;
1729
1730         if (i40e_add_mac_filter(vsi, addr))
1731                 return 0;
1732         else
1733                 return -ENOMEM;
1734 }
1735
1736 /**
1737  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
1738  * @netdev: the netdevice
1739  * @addr: address to add
1740  *
1741  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
1742  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
1743  */
1744 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
1745 {
1746         struct i40e_netdev_priv *np = netdev_priv(netdev);
1747         struct i40e_vsi *vsi = np->vsi;
1748
1749         /* Under some circumstances, we might receive a request to delete
1750          * our own device address from our uc list. Because we store the
1751          * device address in the VSI's MAC/VLAN filter list, we need to ignore
1752          * such requests and not delete our device address from this list.
1753          */
1754         if (ether_addr_equal(addr, netdev->dev_addr))
1755                 return 0;
1756
1757         i40e_del_mac_filter(vsi, addr);
1758
1759         return 0;
1760 }
1761
1762 /**
1763  * i40e_set_rx_mode - NDO callback to set the netdev filters
1764  * @netdev: network interface device structure
1765  **/
1766 static void i40e_set_rx_mode(struct net_device *netdev)
1767 {
1768         struct i40e_netdev_priv *np = netdev_priv(netdev);
1769         struct i40e_vsi *vsi = np->vsi;
1770
1771         spin_lock_bh(&vsi->mac_filter_hash_lock);
1772
1773         __dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
1774         __dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
1775
1776         spin_unlock_bh(&vsi->mac_filter_hash_lock);
1777
1778         /* check for other flag changes */
1779         if (vsi->current_netdev_flags != vsi->netdev->flags) {
1780                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1781                 vsi->back->flags |= I40E_FLAG_FILTER_SYNC;
1782         }
1783
1784         /* schedule our worker thread which will take care of
1785          * applying the new filter changes
1786          */
1787         i40e_service_event_schedule(vsi->back);
1788 }
1789
1790 /**
1791  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
1792  * @vsi: Pointer to VSI struct
1793  * @from: Pointer to list which contains MAC filter entries - changes to
1794  *        those entries needs to be undone.
1795  *
1796  * MAC filter entries from this list were slated for deletion.
1797  **/
1798 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
1799                                          struct hlist_head *from)
1800 {
1801         struct i40e_mac_filter *f;
1802         struct hlist_node *h;
1803
1804         hlist_for_each_entry_safe(f, h, from, hlist) {
1805                 u64 key = i40e_addr_to_hkey(f->macaddr);
1806
1807                 /* Move the element back into MAC filter list*/
1808                 hlist_del(&f->hlist);
1809                 hash_add(vsi->mac_filter_hash, &f->hlist, key);
1810         }
1811 }
1812
1813 /**
1814  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
1815  * @vsi: Pointer to vsi struct
1816  * @from: Pointer to list which contains MAC filter entries - changes to
1817  *        those entries needs to be undone.
1818  *
1819  * MAC filter entries from this list were slated for addition.
1820  **/
1821 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
1822                                          struct hlist_head *from)
1823 {
1824         struct i40e_new_mac_filter *new;
1825         struct hlist_node *h;
1826
1827         hlist_for_each_entry_safe(new, h, from, hlist) {
1828                 /* We can simply free the wrapper structure */
1829                 hlist_del(&new->hlist);
1830                 kfree(new);
1831         }
1832 }
1833
1834 /**
1835  * i40e_next_entry - Get the next non-broadcast filter from a list
1836  * @next: pointer to filter in list
1837  *
1838  * Returns the next non-broadcast filter in the list. Required so that we
1839  * ignore broadcast filters within the list, since these are not handled via
1840  * the normal firmware update path.
1841  */
1842 static
1843 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
1844 {
1845         hlist_for_each_entry_continue(next, hlist) {
1846                 if (!is_broadcast_ether_addr(next->f->macaddr))
1847                         return next;
1848         }
1849
1850         return NULL;
1851 }
1852
1853 /**
1854  * i40e_update_filter_state - Update filter state based on return data
1855  * from firmware
1856  * @count: Number of filters added
1857  * @add_list: return data from fw
1858  * @head: pointer to first filter in current batch
1859  *
1860  * MAC filter entries from list were slated to be added to device. Returns
1861  * number of successful filters. Note that 0 does NOT mean success!
1862  **/
1863 static int
1864 i40e_update_filter_state(int count,
1865                          struct i40e_aqc_add_macvlan_element_data *add_list,
1866                          struct i40e_new_mac_filter *add_head)
1867 {
1868         int retval = 0;
1869         int i;
1870
1871         for (i = 0; i < count; i++) {
1872                 /* Always check status of each filter. We don't need to check
1873                  * the firmware return status because we pre-set the filter
1874                  * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
1875                  * request to the adminq. Thus, if it no longer matches then
1876                  * we know the filter is active.
1877                  */
1878                 if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
1879                         add_head->state = I40E_FILTER_FAILED;
1880                 } else {
1881                         add_head->state = I40E_FILTER_ACTIVE;
1882                         retval++;
1883                 }
1884
1885                 add_head = i40e_next_filter(add_head);
1886                 if (!add_head)
1887                         break;
1888         }
1889
1890         return retval;
1891 }
1892
1893 /**
1894  * i40e_aqc_del_filters - Request firmware to delete a set of filters
1895  * @vsi: ptr to the VSI
1896  * @vsi_name: name to display in messages
1897  * @list: the list of filters to send to firmware
1898  * @num_del: the number of filters to delete
1899  * @retval: Set to -EIO on failure to delete
1900  *
1901  * Send a request to firmware via AdminQ to delete a set of filters. Uses
1902  * *retval instead of a return value so that success does not force ret_val to
1903  * be set to 0. This ensures that a sequence of calls to this function
1904  * preserve the previous value of *retval on successful delete.
1905  */
1906 static
1907 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
1908                           struct i40e_aqc_remove_macvlan_element_data *list,
1909                           int num_del, int *retval)
1910 {
1911         struct i40e_hw *hw = &vsi->back->hw;
1912         i40e_status aq_ret;
1913         int aq_err;
1914
1915         aq_ret = i40e_aq_remove_macvlan(hw, vsi->seid, list, num_del, NULL);
1916         aq_err = hw->aq.asq_last_status;
1917
1918         /* Explicitly ignore and do not report when firmware returns ENOENT */
1919         if (aq_ret && !(aq_err == I40E_AQ_RC_ENOENT)) {
1920                 *retval = -EIO;
1921                 dev_info(&vsi->back->pdev->dev,
1922                          "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
1923                          vsi_name, i40e_stat_str(hw, aq_ret),
1924                          i40e_aq_str(hw, aq_err));
1925         }
1926 }
1927
1928 /**
1929  * i40e_aqc_add_filters - Request firmware to add a set of filters
1930  * @vsi: ptr to the VSI
1931  * @vsi_name: name to display in messages
1932  * @list: the list of filters to send to firmware
1933  * @add_head: Position in the add hlist
1934  * @num_add: the number of filters to add
1935  * @promisc_change: set to true on exit if promiscuous mode was forced on
1936  *
1937  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
1938  * promisc_changed to true if the firmware has run out of space for more
1939  * filters.
1940  */
1941 static
1942 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
1943                           struct i40e_aqc_add_macvlan_element_data *list,
1944                           struct i40e_new_mac_filter *add_head,
1945                           int num_add, bool *promisc_changed)
1946 {
1947         struct i40e_hw *hw = &vsi->back->hw;
1948         int aq_err, fcnt;
1949
1950         i40e_aq_add_macvlan(hw, vsi->seid, list, num_add, NULL);
1951         aq_err = hw->aq.asq_last_status;
1952         fcnt = i40e_update_filter_state(num_add, list, add_head);
1953
1954         if (fcnt != num_add) {
1955                 *promisc_changed = true;
1956                 set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
1957                 dev_warn(&vsi->back->pdev->dev,
1958                          "Error %s adding RX filters on %s, promiscuous mode forced on\n",
1959                          i40e_aq_str(hw, aq_err),
1960                          vsi_name);
1961         }
1962 }
1963
1964 /**
1965  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
1966  * @vsi: pointer to the VSI
1967  * @f: filter data
1968  *
1969  * This function sets or clears the promiscuous broadcast flags for VLAN
1970  * filters in order to properly receive broadcast frames. Assumes that only
1971  * broadcast filters are passed.
1972  *
1973  * Returns status indicating success or failure;
1974  **/
1975 static i40e_status
1976 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
1977                           struct i40e_mac_filter *f)
1978 {
1979         bool enable = f->state == I40E_FILTER_NEW;
1980         struct i40e_hw *hw = &vsi->back->hw;
1981         i40e_status aq_ret;
1982
1983         if (f->vlan == I40E_VLAN_ANY) {
1984                 aq_ret = i40e_aq_set_vsi_broadcast(hw,
1985                                                    vsi->seid,
1986                                                    enable,
1987                                                    NULL);
1988         } else {
1989                 aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
1990                                                             vsi->seid,
1991                                                             enable,
1992                                                             f->vlan,
1993                                                             NULL);
1994         }
1995
1996         if (aq_ret)
1997                 dev_warn(&vsi->back->pdev->dev,
1998                          "Error %s setting broadcast promiscuous mode on %s\n",
1999                          i40e_aq_str(hw, hw->aq.asq_last_status),
2000                          vsi_name);
2001
2002         return aq_ret;
2003 }
2004
2005 /**
2006  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2007  * @vsi: ptr to the VSI
2008  *
2009  * Push any outstanding VSI filter changes through the AdminQ.
2010  *
2011  * Returns 0 or error value
2012  **/
2013 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2014 {
2015         struct hlist_head tmp_add_list, tmp_del_list;
2016         struct i40e_mac_filter *f;
2017         struct i40e_new_mac_filter *new, *add_head = NULL;
2018         struct i40e_hw *hw = &vsi->back->hw;
2019         unsigned int failed_filters = 0;
2020         unsigned int vlan_filters = 0;
2021         bool promisc_changed = false;
2022         char vsi_name[16] = "PF";
2023         int filter_list_len = 0;
2024         i40e_status aq_ret = 0;
2025         u32 changed_flags = 0;
2026         struct hlist_node *h;
2027         struct i40e_pf *pf;
2028         int num_add = 0;
2029         int num_del = 0;
2030         int retval = 0;
2031         u16 cmd_flags;
2032         int list_size;
2033         int bkt;
2034
2035         /* empty array typed pointers, kcalloc later */
2036         struct i40e_aqc_add_macvlan_element_data *add_list;
2037         struct i40e_aqc_remove_macvlan_element_data *del_list;
2038
2039         while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2040                 usleep_range(1000, 2000);
2041         pf = vsi->back;
2042
2043         if (vsi->netdev) {
2044                 changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2045                 vsi->current_netdev_flags = vsi->netdev->flags;
2046         }
2047
2048         INIT_HLIST_HEAD(&tmp_add_list);
2049         INIT_HLIST_HEAD(&tmp_del_list);
2050
2051         if (vsi->type == I40E_VSI_SRIOV)
2052                 snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2053         else if (vsi->type != I40E_VSI_MAIN)
2054                 snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2055
2056         if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2057                 vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2058
2059                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2060                 /* Create a list of filters to delete. */
2061                 hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2062                         if (f->state == I40E_FILTER_REMOVE) {
2063                                 /* Move the element into temporary del_list */
2064                                 hash_del(&f->hlist);
2065                                 hlist_add_head(&f->hlist, &tmp_del_list);
2066
2067                                 /* Avoid counting removed filters */
2068                                 continue;
2069                         }
2070                         if (f->state == I40E_FILTER_NEW) {
2071                                 /* Create a temporary i40e_new_mac_filter */
2072                                 new = kzalloc(sizeof(*new), GFP_ATOMIC);
2073                                 if (!new)
2074                                         goto err_no_memory_locked;
2075
2076                                 /* Store pointer to the real filter */
2077                                 new->f = f;
2078                                 new->state = f->state;
2079
2080                                 /* Add it to the hash list */
2081                                 hlist_add_head(&new->hlist, &tmp_add_list);
2082                         }
2083
2084                         /* Count the number of active (current and new) VLAN
2085                          * filters we have now. Does not count filters which
2086                          * are marked for deletion.
2087                          */
2088                         if (f->vlan > 0)
2089                                 vlan_filters++;
2090                 }
2091
2092                 retval = i40e_correct_mac_vlan_filters(vsi,
2093                                                        &tmp_add_list,
2094                                                        &tmp_del_list,
2095                                                        vlan_filters);
2096                 if (retval)
2097                         goto err_no_memory_locked;
2098
2099                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2100         }
2101
2102         /* Now process 'del_list' outside the lock */
2103         if (!hlist_empty(&tmp_del_list)) {
2104                 filter_list_len = hw->aq.asq_buf_size /
2105                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2106                 list_size = filter_list_len *
2107                             sizeof(struct i40e_aqc_remove_macvlan_element_data);
2108                 del_list = kzalloc(list_size, GFP_ATOMIC);
2109                 if (!del_list)
2110                         goto err_no_memory;
2111
2112                 hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2113                         cmd_flags = 0;
2114
2115                         /* handle broadcast filters by updating the broadcast
2116                          * promiscuous flag and release filter list.
2117                          */
2118                         if (is_broadcast_ether_addr(f->macaddr)) {
2119                                 i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2120
2121                                 hlist_del(&f->hlist);
2122                                 kfree(f);
2123                                 continue;
2124                         }
2125
2126                         /* add to delete list */
2127                         ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2128                         if (f->vlan == I40E_VLAN_ANY) {
2129                                 del_list[num_del].vlan_tag = 0;
2130                                 cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2131                         } else {
2132                                 del_list[num_del].vlan_tag =
2133                                         cpu_to_le16((u16)(f->vlan));
2134                         }
2135
2136                         cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2137                         del_list[num_del].flags = cmd_flags;
2138                         num_del++;
2139
2140                         /* flush a full buffer */
2141                         if (num_del == filter_list_len) {
2142                                 i40e_aqc_del_filters(vsi, vsi_name, del_list,
2143                                                      num_del, &retval);
2144                                 memset(del_list, 0, list_size);
2145                                 num_del = 0;
2146                         }
2147                         /* Release memory for MAC filter entries which were
2148                          * synced up with HW.
2149                          */
2150                         hlist_del(&f->hlist);
2151                         kfree(f);
2152                 }
2153
2154                 if (num_del) {
2155                         i40e_aqc_del_filters(vsi, vsi_name, del_list,
2156                                              num_del, &retval);
2157                 }
2158
2159                 kfree(del_list);
2160                 del_list = NULL;
2161         }
2162
2163         if (!hlist_empty(&tmp_add_list)) {
2164                 /* Do all the adds now. */
2165                 filter_list_len = hw->aq.asq_buf_size /
2166                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2167                 list_size = filter_list_len *
2168                                sizeof(struct i40e_aqc_add_macvlan_element_data);
2169                 add_list = kzalloc(list_size, GFP_ATOMIC);
2170                 if (!add_list)
2171                         goto err_no_memory;
2172
2173                 num_add = 0;
2174                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2175                         if (test_bit(__I40E_VSI_OVERFLOW_PROMISC,
2176                                      vsi->state)) {
2177                                 new->state = I40E_FILTER_FAILED;
2178                                 continue;
2179                         }
2180
2181                         /* handle broadcast filters by updating the broadcast
2182                          * promiscuous flag instead of adding a MAC filter.
2183                          */
2184                         if (is_broadcast_ether_addr(new->f->macaddr)) {
2185                                 if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2186                                                               new->f))
2187                                         new->state = I40E_FILTER_FAILED;
2188                                 else
2189                                         new->state = I40E_FILTER_ACTIVE;
2190                                 continue;
2191                         }
2192
2193                         /* add to add array */
2194                         if (num_add == 0)
2195                                 add_head = new;
2196                         cmd_flags = 0;
2197                         ether_addr_copy(add_list[num_add].mac_addr,
2198                                         new->f->macaddr);
2199                         if (new->f->vlan == I40E_VLAN_ANY) {
2200                                 add_list[num_add].vlan_tag = 0;
2201                                 cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2202                         } else {
2203                                 add_list[num_add].vlan_tag =
2204                                         cpu_to_le16((u16)(new->f->vlan));
2205                         }
2206                         add_list[num_add].queue_number = 0;
2207                         /* set invalid match method for later detection */
2208                         add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2209                         cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2210                         add_list[num_add].flags = cpu_to_le16(cmd_flags);
2211                         num_add++;
2212
2213                         /* flush a full buffer */
2214                         if (num_add == filter_list_len) {
2215                                 i40e_aqc_add_filters(vsi, vsi_name, add_list,
2216                                                      add_head, num_add,
2217                                                      &promisc_changed);
2218                                 memset(add_list, 0, list_size);
2219                                 num_add = 0;
2220                         }
2221                 }
2222                 if (num_add) {
2223                         i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2224                                              num_add, &promisc_changed);
2225                 }
2226                 /* Now move all of the filters from the temp add list back to
2227                  * the VSI's list.
2228                  */
2229                 spin_lock_bh(&vsi->mac_filter_hash_lock);
2230                 hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2231                         /* Only update the state if we're still NEW */
2232                         if (new->f->state == I40E_FILTER_NEW)
2233                                 new->f->state = new->state;
2234                         hlist_del(&new->hlist);
2235                         kfree(new);
2236                 }
2237                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
2238                 kfree(add_list);
2239                 add_list = NULL;
2240         }
2241
2242         /* Determine the number of active and failed filters. */
2243         spin_lock_bh(&vsi->mac_filter_hash_lock);
2244         vsi->active_filters = 0;
2245         hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2246                 if (f->state == I40E_FILTER_ACTIVE)
2247                         vsi->active_filters++;
2248                 else if (f->state == I40E_FILTER_FAILED)
2249                         failed_filters++;
2250         }
2251         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2252
2253         /* If promiscuous mode has changed, we need to calculate a new
2254          * threshold for when we are safe to exit
2255          */
2256         if (promisc_changed)
2257                 vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2258
2259         /* Check if we are able to exit overflow promiscuous mode. We can
2260          * safely exit if we didn't just enter, we no longer have any failed
2261          * filters, and we have reduced filters below the threshold value.
2262          */
2263         if (test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state) &&
2264             !promisc_changed && !failed_filters &&
2265             (vsi->active_filters < vsi->promisc_threshold)) {
2266                 dev_info(&pf->pdev->dev,
2267                          "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2268                          vsi_name);
2269                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2270                 promisc_changed = true;
2271                 vsi->promisc_threshold = 0;
2272         }
2273
2274         /* if the VF is not trusted do not do promisc */
2275         if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2276                 clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2277                 goto out;
2278         }
2279
2280         /* check for changes in promiscuous modes */
2281         if (changed_flags & IFF_ALLMULTI) {
2282                 bool cur_multipromisc;
2283
2284                 cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2285                 aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2286                                                                vsi->seid,
2287                                                                cur_multipromisc,
2288                                                                NULL);
2289                 if (aq_ret) {
2290                         retval = i40e_aq_rc_to_posix(aq_ret,
2291                                                      hw->aq.asq_last_status);
2292                         dev_info(&pf->pdev->dev,
2293                                  "set multi promisc failed on %s, err %s aq_err %s\n",
2294                                  vsi_name,
2295                                  i40e_stat_str(hw, aq_ret),
2296                                  i40e_aq_str(hw, hw->aq.asq_last_status));
2297                 }
2298         }
2299
2300         if ((changed_flags & IFF_PROMISC) || promisc_changed) {
2301                 bool cur_promisc;
2302
2303                 cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2304                                test_bit(__I40E_VSI_OVERFLOW_PROMISC,
2305                                         vsi->state));
2306                 if ((vsi->type == I40E_VSI_MAIN) &&
2307                     (pf->lan_veb != I40E_NO_VEB) &&
2308                     !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2309                         /* set defport ON for Main VSI instead of true promisc
2310                          * this way we will get all unicast/multicast and VLAN
2311                          * promisc behavior but will not get VF or VMDq traffic
2312                          * replicated on the Main VSI.
2313                          */
2314                         if (pf->cur_promisc != cur_promisc) {
2315                                 pf->cur_promisc = cur_promisc;
2316                                 if (cur_promisc)
2317                                         aq_ret =
2318                                               i40e_aq_set_default_vsi(hw,
2319                                                                       vsi->seid,
2320                                                                       NULL);
2321                                 else
2322                                         aq_ret =
2323                                             i40e_aq_clear_default_vsi(hw,
2324                                                                       vsi->seid,
2325                                                                       NULL);
2326                                 if (aq_ret) {
2327                                         retval = i40e_aq_rc_to_posix(aq_ret,
2328                                                         hw->aq.asq_last_status);
2329                                         dev_info(&pf->pdev->dev,
2330                                                  "Set default VSI failed on %s, err %s, aq_err %s\n",
2331                                                  vsi_name,
2332                                                  i40e_stat_str(hw, aq_ret),
2333                                                  i40e_aq_str(hw,
2334                                                      hw->aq.asq_last_status));
2335                                 }
2336                         }
2337                 } else {
2338                         aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2339                                                           hw,
2340                                                           vsi->seid,
2341                                                           cur_promisc, NULL,
2342                                                           true);
2343                         if (aq_ret) {
2344                                 retval =
2345                                 i40e_aq_rc_to_posix(aq_ret,
2346                                                     hw->aq.asq_last_status);
2347                                 dev_info(&pf->pdev->dev,
2348                                          "set unicast promisc failed on %s, err %s, aq_err %s\n",
2349                                          vsi_name,
2350                                          i40e_stat_str(hw, aq_ret),
2351                                          i40e_aq_str(hw,
2352                                                      hw->aq.asq_last_status));
2353                         }
2354                         aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2355                                                           hw,
2356                                                           vsi->seid,
2357                                                           cur_promisc, NULL);
2358                         if (aq_ret) {
2359                                 retval =
2360                                 i40e_aq_rc_to_posix(aq_ret,
2361                                                     hw->aq.asq_last_status);
2362                                 dev_info(&pf->pdev->dev,
2363                                          "set multicast promisc failed on %s, err %s, aq_err %s\n",
2364                                          vsi_name,
2365                                          i40e_stat_str(hw, aq_ret),
2366                                          i40e_aq_str(hw,
2367                                                      hw->aq.asq_last_status));
2368                         }
2369                 }
2370                 aq_ret = i40e_aq_set_vsi_broadcast(&vsi->back->hw,
2371                                                    vsi->seid,
2372                                                    cur_promisc, NULL);
2373                 if (aq_ret) {
2374                         retval = i40e_aq_rc_to_posix(aq_ret,
2375                                                      pf->hw.aq.asq_last_status);
2376                         dev_info(&pf->pdev->dev,
2377                                  "set brdcast promisc failed, err %s, aq_err %s\n",
2378                                          i40e_stat_str(hw, aq_ret),
2379                                          i40e_aq_str(hw,
2380                                                      hw->aq.asq_last_status));
2381                 }
2382         }
2383 out:
2384         /* if something went wrong then set the changed flag so we try again */
2385         if (retval)
2386                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2387
2388         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2389         return retval;
2390
2391 err_no_memory:
2392         /* Restore elements on the temporary add and delete lists */
2393         spin_lock_bh(&vsi->mac_filter_hash_lock);
2394 err_no_memory_locked:
2395         i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2396         i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2397         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2398
2399         vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2400         clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2401         return -ENOMEM;
2402 }
2403
2404 /**
2405  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2406  * @pf: board private structure
2407  **/
2408 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2409 {
2410         int v;
2411
2412         if (!pf || !(pf->flags & I40E_FLAG_FILTER_SYNC))
2413                 return;
2414         pf->flags &= ~I40E_FLAG_FILTER_SYNC;
2415
2416         for (v = 0; v < pf->num_alloc_vsi; v++) {
2417                 if (pf->vsi[v] &&
2418                     (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED)) {
2419                         int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2420
2421                         if (ret) {
2422                                 /* come back and try again later */
2423                                 pf->flags |= I40E_FLAG_FILTER_SYNC;
2424                                 break;
2425                         }
2426                 }
2427         }
2428 }
2429
2430 /**
2431  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2432  * @vsi: the vsi
2433  **/
2434 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2435 {
2436         if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2437                 return I40E_RXBUFFER_2048;
2438         else
2439                 return I40E_RXBUFFER_3072;
2440 }
2441
2442 /**
2443  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2444  * @netdev: network interface device structure
2445  * @new_mtu: new value for maximum frame size
2446  *
2447  * Returns 0 on success, negative on failure
2448  **/
2449 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2450 {
2451         struct i40e_netdev_priv *np = netdev_priv(netdev);
2452         struct i40e_vsi *vsi = np->vsi;
2453         struct i40e_pf *pf = vsi->back;
2454
2455         if (i40e_enabled_xdp_vsi(vsi)) {
2456                 int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2457
2458                 if (frame_size > i40e_max_xdp_frame_size(vsi))
2459                         return -EINVAL;
2460         }
2461
2462         netdev_info(netdev, "changing MTU from %d to %d\n",
2463                     netdev->mtu, new_mtu);
2464         netdev->mtu = new_mtu;
2465         if (netif_running(netdev))
2466                 i40e_vsi_reinit_locked(vsi);
2467         pf->flags |= (I40E_FLAG_SERVICE_CLIENT_REQUESTED |
2468                       I40E_FLAG_CLIENT_L2_CHANGE);
2469         return 0;
2470 }
2471
2472 /**
2473  * i40e_ioctl - Access the hwtstamp interface
2474  * @netdev: network interface device structure
2475  * @ifr: interface request data
2476  * @cmd: ioctl command
2477  **/
2478 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2479 {
2480         struct i40e_netdev_priv *np = netdev_priv(netdev);
2481         struct i40e_pf *pf = np->vsi->back;
2482
2483         switch (cmd) {
2484         case SIOCGHWTSTAMP:
2485                 return i40e_ptp_get_ts_config(pf, ifr);
2486         case SIOCSHWTSTAMP:
2487                 return i40e_ptp_set_ts_config(pf, ifr);
2488         default:
2489                 return -EOPNOTSUPP;
2490         }
2491 }
2492
2493 /**
2494  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2495  * @vsi: the vsi being adjusted
2496  **/
2497 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2498 {
2499         struct i40e_vsi_context ctxt;
2500         i40e_status ret;
2501
2502         /* Don't modify stripping options if a port VLAN is active */
2503         if (vsi->info.pvid)
2504                 return;
2505
2506         if ((vsi->info.valid_sections &
2507              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2508             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2509                 return;  /* already enabled */
2510
2511         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2512         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2513                                     I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2514
2515         ctxt.seid = vsi->seid;
2516         ctxt.info = vsi->info;
2517         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2518         if (ret) {
2519                 dev_info(&vsi->back->pdev->dev,
2520                          "update vlan stripping failed, err %s aq_err %s\n",
2521                          i40e_stat_str(&vsi->back->hw, ret),
2522                          i40e_aq_str(&vsi->back->hw,
2523                                      vsi->back->hw.aq.asq_last_status));
2524         }
2525 }
2526
2527 /**
2528  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2529  * @vsi: the vsi being adjusted
2530  **/
2531 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2532 {
2533         struct i40e_vsi_context ctxt;
2534         i40e_status ret;
2535
2536         /* Don't modify stripping options if a port VLAN is active */
2537         if (vsi->info.pvid)
2538                 return;
2539
2540         if ((vsi->info.valid_sections &
2541              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2542             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
2543              I40E_AQ_VSI_PVLAN_EMOD_MASK))
2544                 return;  /* already disabled */
2545
2546         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2547         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2548                                     I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2549
2550         ctxt.seid = vsi->seid;
2551         ctxt.info = vsi->info;
2552         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2553         if (ret) {
2554                 dev_info(&vsi->back->pdev->dev,
2555                          "update vlan stripping failed, err %s aq_err %s\n",
2556                          i40e_stat_str(&vsi->back->hw, ret),
2557                          i40e_aq_str(&vsi->back->hw,
2558                                      vsi->back->hw.aq.asq_last_status));
2559         }
2560 }
2561
2562 /**
2563  * i40e_vlan_rx_register - Setup or shutdown vlan offload
2564  * @netdev: network interface to be adjusted
2565  * @features: netdev features to test if VLAN offload is enabled or not
2566  **/
2567 static void i40e_vlan_rx_register(struct net_device *netdev, u32 features)
2568 {
2569         struct i40e_netdev_priv *np = netdev_priv(netdev);
2570         struct i40e_vsi *vsi = np->vsi;
2571
2572         if (features & NETIF_F_HW_VLAN_CTAG_RX)
2573                 i40e_vlan_stripping_enable(vsi);
2574         else
2575                 i40e_vlan_stripping_disable(vsi);
2576 }
2577
2578 /**
2579  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
2580  * @vsi: the vsi being configured
2581  * @vid: vlan id to be added (0 = untagged only , -1 = any)
2582  *
2583  * This is a helper function for adding a new MAC/VLAN filter with the
2584  * specified VLAN for each existing MAC address already in the hash table.
2585  * This function does *not* perform any accounting to update filters based on
2586  * VLAN mode.
2587  *
2588  * NOTE: this function expects to be called while under the
2589  * mac_filter_hash_lock
2590  **/
2591 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2592 {
2593         struct i40e_mac_filter *f, *add_f;
2594         struct hlist_node *h;
2595         int bkt;
2596
2597         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2598                 if (f->state == I40E_FILTER_REMOVE)
2599                         continue;
2600                 add_f = i40e_add_filter(vsi, f->macaddr, vid);
2601                 if (!add_f) {
2602                         dev_info(&vsi->back->pdev->dev,
2603                                  "Could not add vlan filter %d for %pM\n",
2604                                  vid, f->macaddr);
2605                         return -ENOMEM;
2606                 }
2607         }
2608
2609         return 0;
2610 }
2611
2612 /**
2613  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
2614  * @vsi: the VSI being configured
2615  * @vid: VLAN id to be added
2616  **/
2617 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
2618 {
2619         int err;
2620
2621         if (vsi->info.pvid)
2622                 return -EINVAL;
2623
2624         /* The network stack will attempt to add VID=0, with the intention to
2625          * receive priority tagged packets with a VLAN of 0. Our HW receives
2626          * these packets by default when configured to receive untagged
2627          * packets, so we don't need to add a filter for this case.
2628          * Additionally, HW interprets adding a VID=0 filter as meaning to
2629          * receive *only* tagged traffic and stops receiving untagged traffic.
2630          * Thus, we do not want to actually add a filter for VID=0
2631          */
2632         if (!vid)
2633                 return 0;
2634
2635         /* Locked once because all functions invoked below iterates list*/
2636         spin_lock_bh(&vsi->mac_filter_hash_lock);
2637         err = i40e_add_vlan_all_mac(vsi, vid);
2638         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2639         if (err)
2640                 return err;
2641
2642         /* schedule our worker thread which will take care of
2643          * applying the new filter changes
2644          */
2645         i40e_service_event_schedule(vsi->back);
2646         return 0;
2647 }
2648
2649 /**
2650  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
2651  * @vsi: the vsi being configured
2652  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
2653  *
2654  * This function should be used to remove all VLAN filters which match the
2655  * given VID. It does not schedule the service event and does not take the
2656  * mac_filter_hash_lock so it may be combined with other operations under
2657  * a single invocation of the mac_filter_hash_lock.
2658  *
2659  * NOTE: this function expects to be called while under the
2660  * mac_filter_hash_lock
2661  */
2662 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2663 {
2664         struct i40e_mac_filter *f;
2665         struct hlist_node *h;
2666         int bkt;
2667
2668         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2669                 if (f->vlan == vid)
2670                         __i40e_del_filter(vsi, f);
2671         }
2672 }
2673
2674 /**
2675  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
2676  * @vsi: the VSI being configured
2677  * @vid: VLAN id to be removed
2678  **/
2679 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
2680 {
2681         if (!vid || vsi->info.pvid)
2682                 return;
2683
2684         spin_lock_bh(&vsi->mac_filter_hash_lock);
2685         i40e_rm_vlan_all_mac(vsi, vid);
2686         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2687
2688         /* schedule our worker thread which will take care of
2689          * applying the new filter changes
2690          */
2691         i40e_service_event_schedule(vsi->back);
2692 }
2693
2694 /**
2695  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
2696  * @netdev: network interface to be adjusted
2697  * @vid: vlan id to be added
2698  *
2699  * net_device_ops implementation for adding vlan ids
2700  **/
2701 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
2702                                 __always_unused __be16 proto, u16 vid)
2703 {
2704         struct i40e_netdev_priv *np = netdev_priv(netdev);
2705         struct i40e_vsi *vsi = np->vsi;
2706         int ret = 0;
2707
2708         if (vid >= VLAN_N_VID)
2709                 return -EINVAL;
2710
2711         ret = i40e_vsi_add_vlan(vsi, vid);
2712         if (!ret)
2713                 set_bit(vid, vsi->active_vlans);
2714
2715         return ret;
2716 }
2717
2718 /**
2719  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
2720  * @netdev: network interface to be adjusted
2721  * @vid: vlan id to be removed
2722  *
2723  * net_device_ops implementation for removing vlan ids
2724  **/
2725 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
2726                                  __always_unused __be16 proto, u16 vid)
2727 {
2728         struct i40e_netdev_priv *np = netdev_priv(netdev);
2729         struct i40e_vsi *vsi = np->vsi;
2730
2731         /* return code is ignored as there is nothing a user
2732          * can do about failure to remove and a log message was
2733          * already printed from the other function
2734          */
2735         i40e_vsi_kill_vlan(vsi, vid);
2736
2737         clear_bit(vid, vsi->active_vlans);
2738
2739         return 0;
2740 }
2741
2742 /**
2743  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
2744  * @vsi: the vsi being brought back up
2745  **/
2746 static void i40e_restore_vlan(struct i40e_vsi *vsi)
2747 {
2748         u16 vid;
2749
2750         if (!vsi->netdev)
2751                 return;
2752
2753         i40e_vlan_rx_register(vsi->netdev, vsi->netdev->features);
2754
2755         for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
2756                 i40e_vlan_rx_add_vid(vsi->netdev, htons(ETH_P_8021Q),
2757                                      vid);
2758 }
2759
2760 /**
2761  * i40e_vsi_add_pvid - Add pvid for the VSI
2762  * @vsi: the vsi being adjusted
2763  * @vid: the vlan id to set as a PVID
2764  **/
2765 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
2766 {
2767         struct i40e_vsi_context ctxt;
2768         i40e_status ret;
2769
2770         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2771         vsi->info.pvid = cpu_to_le16(vid);
2772         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
2773                                     I40E_AQ_VSI_PVLAN_INSERT_PVID |
2774                                     I40E_AQ_VSI_PVLAN_EMOD_STR;
2775
2776         ctxt.seid = vsi->seid;
2777         ctxt.info = vsi->info;
2778         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2779         if (ret) {
2780                 dev_info(&vsi->back->pdev->dev,
2781                          "add pvid failed, err %s aq_err %s\n",
2782                          i40e_stat_str(&vsi->back->hw, ret),
2783                          i40e_aq_str(&vsi->back->hw,
2784                                      vsi->back->hw.aq.asq_last_status));
2785                 return -ENOENT;
2786         }
2787
2788         return 0;
2789 }
2790
2791 /**
2792  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
2793  * @vsi: the vsi being adjusted
2794  *
2795  * Just use the vlan_rx_register() service to put it back to normal
2796  **/
2797 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
2798 {
2799         i40e_vlan_stripping_disable(vsi);
2800
2801         vsi->info.pvid = 0;
2802 }
2803
2804 /**
2805  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
2806  * @vsi: ptr to the VSI
2807  *
2808  * If this function returns with an error, then it's possible one or
2809  * more of the rings is populated (while the rest are not).  It is the
2810  * callers duty to clean those orphaned rings.
2811  *
2812  * Return 0 on success, negative on failure
2813  **/
2814 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
2815 {
2816         int i, err = 0;
2817
2818         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
2819                 err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
2820
2821         if (!i40e_enabled_xdp_vsi(vsi))
2822                 return err;
2823
2824         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
2825                 err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
2826
2827         return err;
2828 }
2829
2830 /**
2831  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
2832  * @vsi: ptr to the VSI
2833  *
2834  * Free VSI's transmit software resources
2835  **/
2836 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
2837 {
2838         int i;
2839
2840         if (vsi->tx_rings) {
2841                 for (i = 0; i < vsi->num_queue_pairs; i++)
2842                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
2843                                 i40e_free_tx_resources(vsi->tx_rings[i]);
2844         }
2845
2846         if (vsi->xdp_rings) {
2847                 for (i = 0; i < vsi->num_queue_pairs; i++)
2848                         if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
2849                                 i40e_free_tx_resources(vsi->xdp_rings[i]);
2850         }
2851 }
2852
2853 /**
2854  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
2855  * @vsi: ptr to the VSI
2856  *
2857  * If this function returns with an error, then it's possible one or
2858  * more of the rings is populated (while the rest are not).  It is the
2859  * callers duty to clean those orphaned rings.
2860  *
2861  * Return 0 on success, negative on failure
2862  **/
2863 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
2864 {
2865         int i, err = 0;
2866
2867         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
2868                 err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
2869         return err;
2870 }
2871
2872 /**
2873  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
2874  * @vsi: ptr to the VSI
2875  *
2876  * Free all receive software resources
2877  **/
2878 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
2879 {
2880         int i;
2881
2882         if (!vsi->rx_rings)
2883                 return;
2884
2885         for (i = 0; i < vsi->num_queue_pairs; i++)
2886                 if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
2887                         i40e_free_rx_resources(vsi->rx_rings[i]);
2888 }
2889
2890 /**
2891  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
2892  * @ring: The Tx ring to configure
2893  *
2894  * This enables/disables XPS for a given Tx descriptor ring
2895  * based on the TCs enabled for the VSI that ring belongs to.
2896  **/
2897 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
2898 {
2899         struct i40e_vsi *vsi = ring->vsi;
2900         int cpu;
2901
2902         if (!ring->q_vector || !ring->netdev)
2903                 return;
2904
2905         if ((vsi->tc_config.numtc <= 1) &&
2906             !test_and_set_bit(__I40E_TX_XPS_INIT_DONE, &ring->state)) {
2907                 cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
2908                 netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
2909                                     ring->queue_index);
2910         }
2911
2912         /* schedule our worker thread which will take care of
2913          * applying the new filter changes
2914          */
2915         i40e_service_event_schedule(vsi->back);
2916 }
2917
2918 /**
2919  * i40e_configure_tx_ring - Configure a transmit ring context and rest
2920  * @ring: The Tx ring to configure
2921  *
2922  * Configure the Tx descriptor ring in the HMC context.
2923  **/
2924 static int i40e_configure_tx_ring(struct i40e_ring *ring)
2925 {
2926         struct i40e_vsi *vsi = ring->vsi;
2927         u16 pf_q = vsi->base_queue + ring->queue_index;
2928         struct i40e_hw *hw = &vsi->back->hw;
2929         struct i40e_hmc_obj_txq tx_ctx;
2930         i40e_status err = 0;
2931         u32 qtx_ctl = 0;
2932
2933         /* some ATR related tx ring init */
2934         if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
2935                 ring->atr_sample_rate = vsi->back->atr_sample_rate;
2936                 ring->atr_count = 0;
2937         } else {
2938                 ring->atr_sample_rate = 0;
2939         }
2940
2941         /* configure XPS */
2942         i40e_config_xps_tx_ring(ring);
2943
2944         /* clear the context structure first */
2945         memset(&tx_ctx, 0, sizeof(tx_ctx));
2946
2947         tx_ctx.new_context = 1;
2948         tx_ctx.base = (ring->dma / 128);
2949         tx_ctx.qlen = ring->count;
2950         tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
2951                                                I40E_FLAG_FD_ATR_ENABLED));
2952         tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
2953         /* FDIR VSI tx ring can still use RS bit and writebacks */
2954         if (vsi->type != I40E_VSI_FDIR)
2955                 tx_ctx.head_wb_ena = 1;
2956         tx_ctx.head_wb_addr = ring->dma +
2957                               (ring->count * sizeof(struct i40e_tx_desc));
2958
2959         /* As part of VSI creation/update, FW allocates certain
2960          * Tx arbitration queue sets for each TC enabled for
2961          * the VSI. The FW returns the handles to these queue
2962          * sets as part of the response buffer to Add VSI,
2963          * Update VSI, etc. AQ commands. It is expected that
2964          * these queue set handles be associated with the Tx
2965          * queues by the driver as part of the TX queue context
2966          * initialization. This has to be done regardless of
2967          * DCB as by default everything is mapped to TC0.
2968          */
2969         tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
2970         tx_ctx.rdylist_act = 0;
2971
2972         /* clear the context in the HMC */
2973         err = i40e_clear_lan_tx_queue_context(hw, pf_q);
2974         if (err) {
2975                 dev_info(&vsi->back->pdev->dev,
2976                          "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
2977                          ring->queue_index, pf_q, err);
2978                 return -ENOMEM;
2979         }
2980
2981         /* set the context in the HMC */
2982         err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
2983         if (err) {
2984                 dev_info(&vsi->back->pdev->dev,
2985                          "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
2986                          ring->queue_index, pf_q, err);
2987                 return -ENOMEM;
2988         }
2989
2990         /* Now associate this queue with this PCI function */
2991         if (vsi->type == I40E_VSI_VMDQ2) {
2992                 qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
2993                 qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
2994                            I40E_QTX_CTL_VFVM_INDX_MASK;
2995         } else {
2996                 qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
2997         }
2998
2999         qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3000                     I40E_QTX_CTL_PF_INDX_MASK);
3001         wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3002         i40e_flush(hw);
3003
3004         /* cache tail off for easier writes later */
3005         ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3006
3007         return 0;
3008 }
3009
3010 /**
3011  * i40e_configure_rx_ring - Configure a receive ring context
3012  * @ring: The Rx ring to configure
3013  *
3014  * Configure the Rx descriptor ring in the HMC context.
3015  **/
3016 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3017 {
3018         struct i40e_vsi *vsi = ring->vsi;
3019         u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3020         u16 pf_q = vsi->base_queue + ring->queue_index;
3021         struct i40e_hw *hw = &vsi->back->hw;
3022         struct i40e_hmc_obj_rxq rx_ctx;
3023         i40e_status err = 0;
3024
3025         ring->state = 0;
3026
3027         /* clear the context structure first */
3028         memset(&rx_ctx, 0, sizeof(rx_ctx));
3029
3030         ring->rx_buf_len = vsi->rx_buf_len;
3031
3032         rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3033                                     BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3034
3035         rx_ctx.base = (ring->dma / 128);
3036         rx_ctx.qlen = ring->count;
3037
3038         /* use 32 byte descriptors */
3039         rx_ctx.dsize = 1;
3040
3041         /* descriptor type is always zero
3042          * rx_ctx.dtype = 0;
3043          */
3044         rx_ctx.hsplit_0 = 0;
3045
3046         rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3047         if (hw->revision_id == 0)
3048                 rx_ctx.lrxqthresh = 0;
3049         else
3050                 rx_ctx.lrxqthresh = 2;
3051         rx_ctx.crcstrip = 1;
3052         rx_ctx.l2tsel = 1;
3053         /* this controls whether VLAN is stripped from inner headers */
3054         rx_ctx.showiv = 0;
3055         /* set the prefena field to 1 because the manual says to */
3056         rx_ctx.prefena = 1;
3057
3058         /* clear the context in the HMC */
3059         err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3060         if (err) {
3061                 dev_info(&vsi->back->pdev->dev,
3062                          "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3063                          ring->queue_index, pf_q, err);
3064                 return -ENOMEM;
3065         }
3066
3067         /* set the context in the HMC */
3068         err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3069         if (err) {
3070                 dev_info(&vsi->back->pdev->dev,
3071                          "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3072                          ring->queue_index, pf_q, err);
3073                 return -ENOMEM;
3074         }
3075
3076         /* configure Rx buffer alignment */
3077         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3078                 clear_ring_build_skb_enabled(ring);
3079         else
3080                 set_ring_build_skb_enabled(ring);
3081
3082         /* cache tail for quicker writes, and clear the reg before use */
3083         ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3084         writel(0, ring->tail);
3085
3086         i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3087
3088         return 0;
3089 }
3090
3091 /**
3092  * i40e_vsi_configure_tx - Configure the VSI for Tx
3093  * @vsi: VSI structure describing this set of rings and resources
3094  *
3095  * Configure the Tx VSI for operation.
3096  **/
3097 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3098 {
3099         int err = 0;
3100         u16 i;
3101
3102         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3103                 err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3104
3105         if (!i40e_enabled_xdp_vsi(vsi))
3106                 return err;
3107
3108         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3109                 err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3110
3111         return err;
3112 }
3113
3114 /**
3115  * i40e_vsi_configure_rx - Configure the VSI for Rx
3116  * @vsi: the VSI being configured
3117  *
3118  * Configure the Rx VSI for operation.
3119  **/
3120 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3121 {
3122         int err = 0;
3123         u16 i;
3124
3125         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3126                 vsi->max_frame = I40E_MAX_RXBUFFER;
3127                 vsi->rx_buf_len = I40E_RXBUFFER_2048;
3128 #if (PAGE_SIZE < 8192)
3129         } else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3130                    (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3131                 vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3132                 vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3133 #endif
3134         } else {
3135                 vsi->max_frame = I40E_MAX_RXBUFFER;
3136                 vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3137                                                        I40E_RXBUFFER_2048;
3138         }
3139
3140         /* set up individual rings */
3141         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3142                 err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3143
3144         return err;
3145 }
3146
3147 /**
3148  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3149  * @vsi: ptr to the VSI
3150  **/
3151 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3152 {
3153         struct i40e_ring *tx_ring, *rx_ring;
3154         u16 qoffset, qcount;
3155         int i, n;
3156
3157         if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3158                 /* Reset the TC information */
3159                 for (i = 0; i < vsi->num_queue_pairs; i++) {
3160                         rx_ring = vsi->rx_rings[i];
3161                         tx_ring = vsi->tx_rings[i];
3162                         rx_ring->dcb_tc = 0;
3163                         tx_ring->dcb_tc = 0;
3164                 }
3165         }
3166
3167         for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3168                 if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3169                         continue;
3170
3171                 qoffset = vsi->tc_config.tc_info[n].qoffset;
3172                 qcount = vsi->tc_config.tc_info[n].qcount;
3173                 for (i = qoffset; i < (qoffset + qcount); i++) {
3174                         rx_ring = vsi->rx_rings[i];
3175                         tx_ring = vsi->tx_rings[i];
3176                         rx_ring->dcb_tc = n;
3177                         tx_ring->dcb_tc = n;
3178                 }
3179         }
3180 }
3181
3182 /**
3183  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3184  * @vsi: ptr to the VSI
3185  **/
3186 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3187 {
3188         if (vsi->netdev)
3189                 i40e_set_rx_mode(vsi->netdev);
3190 }
3191
3192 /**
3193  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3194  * @vsi: Pointer to the targeted VSI
3195  *
3196  * This function replays the hlist on the hw where all the SB Flow Director
3197  * filters were saved.
3198  **/
3199 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3200 {
3201         struct i40e_fdir_filter *filter;
3202         struct i40e_pf *pf = vsi->back;
3203         struct hlist_node *node;
3204
3205         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3206                 return;
3207
3208         /* Reset FDir counters as we're replaying all existing filters */
3209         pf->fd_tcp4_filter_cnt = 0;
3210         pf->fd_udp4_filter_cnt = 0;
3211         pf->fd_sctp4_filter_cnt = 0;
3212         pf->fd_ip4_filter_cnt = 0;
3213
3214         hlist_for_each_entry_safe(filter, node,
3215                                   &pf->fdir_filter_list, fdir_node) {
3216                 i40e_add_del_fdir(vsi, filter, true);
3217         }
3218 }
3219
3220 /**
3221  * i40e_vsi_configure - Set up the VSI for action
3222  * @vsi: the VSI being configured
3223  **/
3224 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3225 {
3226         int err;
3227
3228         i40e_set_vsi_rx_mode(vsi);
3229         i40e_restore_vlan(vsi);
3230         i40e_vsi_config_dcb_rings(vsi);
3231         err = i40e_vsi_configure_tx(vsi);
3232         if (!err)
3233                 err = i40e_vsi_configure_rx(vsi);
3234
3235         return err;
3236 }
3237
3238 /**
3239  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3240  * @vsi: the VSI being configured
3241  **/
3242 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3243 {
3244         bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3245         struct i40e_pf *pf = vsi->back;
3246         struct i40e_hw *hw = &pf->hw;
3247         u16 vector;
3248         int i, q;
3249         u32 qp;
3250
3251         /* The interrupt indexing is offset by 1 in the PFINT_ITRn
3252          * and PFINT_LNKLSTn registers, e.g.:
3253          *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3254          */
3255         qp = vsi->base_queue;
3256         vector = vsi->base_vector;
3257         for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3258                 struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3259
3260                 q_vector->itr_countdown = ITR_COUNTDOWN_START;
3261                 q_vector->rx.itr = ITR_TO_REG(vsi->rx_rings[i]->rx_itr_setting);
3262                 q_vector->rx.latency_range = I40E_LOW_LATENCY;
3263                 wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3264                      q_vector->rx.itr);
3265                 q_vector->tx.itr = ITR_TO_REG(vsi->tx_rings[i]->tx_itr_setting);
3266                 q_vector->tx.latency_range = I40E_LOW_LATENCY;
3267                 wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3268                      q_vector->tx.itr);
3269                 wr32(hw, I40E_PFINT_RATEN(vector - 1),
3270                      i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3271
3272                 /* Linked list for the queuepairs assigned to this vector */
3273                 wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3274                 for (q = 0; q < q_vector->num_ringpairs; q++) {
3275                         u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3276                         u32 val;
3277
3278                         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3279                               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3280                               (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3281                               (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3282                               (I40E_QUEUE_TYPE_TX <<
3283                                I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3284
3285                         wr32(hw, I40E_QINT_RQCTL(qp), val);
3286
3287                         if (has_xdp) {
3288                                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3289                                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3290                                       (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3291                                       (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3292                                       (I40E_QUEUE_TYPE_TX <<
3293                                        I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3294
3295                                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3296                         }
3297
3298                         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3299                               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3300                               (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3301                               ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3302                               (I40E_QUEUE_TYPE_RX <<
3303                                I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3304
3305                         /* Terminate the linked list */
3306                         if (q == (q_vector->num_ringpairs - 1))
3307                                 val |= (I40E_QUEUE_END_OF_LIST <<
3308                                         I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3309
3310                         wr32(hw, I40E_QINT_TQCTL(qp), val);
3311                         qp++;
3312                 }
3313         }
3314
3315         i40e_flush(hw);
3316 }
3317
3318 /**
3319  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3320  * @hw: ptr to the hardware info
3321  **/
3322 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3323 {
3324         struct i40e_hw *hw = &pf->hw;
3325         u32 val;
3326
3327         /* clear things first */
3328         wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3329         rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3330
3331         val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3332               I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3333               I40E_PFINT_ICR0_ENA_GRST_MASK          |
3334               I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3335               I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3336               I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3337               I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3338               I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3339
3340         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3341                 val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3342
3343         if (pf->flags & I40E_FLAG_PTP)
3344                 val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3345
3346         wr32(hw, I40E_PFINT_ICR0_ENA, val);
3347
3348         /* SW_ITR_IDX = 0, but don't change INTENA */
3349         wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3350                                         I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3351
3352         /* OTHER_ITR_IDX = 0 */
3353         wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3354 }
3355
3356 /**
3357  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3358  * @vsi: the VSI being configured
3359  **/
3360 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3361 {
3362         u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3363         struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3364         struct i40e_pf *pf = vsi->back;
3365         struct i40e_hw *hw = &pf->hw;
3366         u32 val;
3367
3368         /* set the ITR configuration */
3369         q_vector->itr_countdown = ITR_COUNTDOWN_START;
3370         q_vector->rx.itr = ITR_TO_REG(vsi->rx_rings[0]->rx_itr_setting);
3371         q_vector->rx.latency_range = I40E_LOW_LATENCY;
3372         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.itr);
3373         q_vector->tx.itr = ITR_TO_REG(vsi->tx_rings[0]->tx_itr_setting);
3374         q_vector->tx.latency_range = I40E_LOW_LATENCY;
3375         wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.itr);
3376
3377         i40e_enable_misc_int_causes(pf);
3378
3379         /* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3380         wr32(hw, I40E_PFINT_LNKLST0, 0);
3381
3382         /* Associate the queue pair to the vector and enable the queue int */
3383         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK                   |
3384               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3385               (nextqp      << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3386               (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3387
3388         wr32(hw, I40E_QINT_RQCTL(0), val);
3389
3390         if (i40e_enabled_xdp_vsi(vsi)) {
3391                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                 |
3392                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
3393                       (I40E_QUEUE_TYPE_TX
3394                        << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3395
3396                wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3397         }
3398
3399         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                  |
3400               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3401               (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3402
3403         wr32(hw, I40E_QINT_TQCTL(0), val);
3404         i40e_flush(hw);
3405 }
3406
3407 /**
3408  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
3409  * @pf: board private structure
3410  **/
3411 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
3412 {
3413         struct i40e_hw *hw = &pf->hw;
3414
3415         wr32(hw, I40E_PFINT_DYN_CTL0,
3416              I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
3417         i40e_flush(hw);
3418 }
3419
3420 /**
3421  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
3422  * @pf: board private structure
3423  * @clearpba: true when all pending interrupt events should be cleared
3424  **/
3425 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf, bool clearpba)
3426 {
3427         struct i40e_hw *hw = &pf->hw;
3428         u32 val;
3429
3430         val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
3431               (clearpba ? I40E_PFINT_DYN_CTL0_CLEARPBA_MASK : 0) |
3432               (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
3433
3434         wr32(hw, I40E_PFINT_DYN_CTL0, val);
3435         i40e_flush(hw);
3436 }
3437
3438 /**
3439  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
3440  * @irq: interrupt number
3441  * @data: pointer to a q_vector
3442  **/
3443 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
3444 {
3445         struct i40e_q_vector *q_vector = data;
3446
3447         if (!q_vector->tx.ring && !q_vector->rx.ring)
3448                 return IRQ_HANDLED;
3449
3450         napi_schedule_irqoff(&q_vector->napi);
3451
3452         return IRQ_HANDLED;
3453 }
3454
3455 /**
3456  * i40e_irq_affinity_notify - Callback for affinity changes
3457  * @notify: context as to what irq was changed
3458  * @mask: the new affinity mask
3459  *
3460  * This is a callback function used by the irq_set_affinity_notifier function
3461  * so that we may register to receive changes to the irq affinity masks.
3462  **/
3463 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
3464                                      const cpumask_t *mask)
3465 {
3466         struct i40e_q_vector *q_vector =
3467                 container_of(notify, struct i40e_q_vector, affinity_notify);
3468
3469         cpumask_copy(&q_vector->affinity_mask, mask);
3470 }
3471
3472 /**
3473  * i40e_irq_affinity_release - Callback for affinity notifier release
3474  * @ref: internal core kernel usage
3475  *
3476  * This is a callback function used by the irq_set_affinity_notifier function
3477  * to inform the current notification subscriber that they will no longer
3478  * receive notifications.
3479  **/
3480 static void i40e_irq_affinity_release(struct kref *ref) {}
3481
3482 /**
3483  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
3484  * @vsi: the VSI being configured
3485  * @basename: name for the vector
3486  *
3487  * Allocates MSI-X vectors and requests interrupts from the kernel.
3488  **/
3489 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
3490 {
3491         int q_vectors = vsi->num_q_vectors;
3492         struct i40e_pf *pf = vsi->back;
3493         int base = vsi->base_vector;
3494         int rx_int_idx = 0;
3495         int tx_int_idx = 0;
3496         int vector, err;
3497         int irq_num;
3498         int cpu;
3499
3500         for (vector = 0; vector < q_vectors; vector++) {
3501                 struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
3502
3503                 irq_num = pf->msix_entries[base + vector].vector;
3504
3505                 if (q_vector->tx.ring && q_vector->rx.ring) {
3506                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3507                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
3508                         tx_int_idx++;
3509                 } else if (q_vector->rx.ring) {
3510                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3511                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
3512                 } else if (q_vector->tx.ring) {
3513                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3514                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
3515                 } else {
3516                         /* skip this unused q_vector */
3517                         continue;
3518                 }
3519                 err = request_irq(irq_num,
3520                                   vsi->irq_handler,
3521                                   0,
3522                                   q_vector->name,
3523                                   q_vector);
3524                 if (err) {
3525                         dev_info(&pf->pdev->dev,
3526                                  "MSIX request_irq failed, error: %d\n", err);
3527                         goto free_queue_irqs;
3528                 }
3529
3530                 /* register for affinity change notifications */
3531                 q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
3532                 q_vector->affinity_notify.release = i40e_irq_affinity_release;
3533                 irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
3534                 /* Spread affinity hints out across online CPUs.
3535                  *
3536                  * get_cpu_mask returns a static constant mask with
3537                  * a permanent lifetime so it's ok to pass to
3538                  * irq_set_affinity_hint without making a copy.
3539                  */
3540                 cpu = cpumask_local_spread(q_vector->v_idx, -1);
3541                 irq_set_affinity_hint(irq_num, get_cpu_mask(cpu));
3542         }
3543
3544         vsi->irqs_ready = true;
3545         return 0;
3546
3547 free_queue_irqs:
3548         while (vector) {
3549                 vector--;
3550                 irq_num = pf->msix_entries[base + vector].vector;
3551                 irq_set_affinity_notifier(irq_num, NULL);
3552                 irq_set_affinity_hint(irq_num, NULL);
3553                 free_irq(irq_num, &vsi->q_vectors[vector]);
3554         }
3555         return err;
3556 }
3557
3558 /**
3559  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
3560  * @vsi: the VSI being un-configured
3561  **/
3562 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
3563 {
3564         struct i40e_pf *pf = vsi->back;
3565         struct i40e_hw *hw = &pf->hw;
3566         int base = vsi->base_vector;
3567         int i;
3568
3569         /* disable interrupt causation from each queue */
3570         for (i = 0; i < vsi->num_queue_pairs; i++) {
3571                 u32 val;
3572
3573                 val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
3574                 val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
3575                 wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
3576
3577                 val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
3578                 val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
3579                 wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
3580
3581                 if (!i40e_enabled_xdp_vsi(vsi))
3582                         continue;
3583                 wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
3584         }
3585
3586         /* disable each interrupt */
3587         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3588                 for (i = vsi->base_vector;
3589                      i < (vsi->num_q_vectors + vsi->base_vector); i++)
3590                         wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
3591
3592                 i40e_flush(hw);
3593                 for (i = 0; i < vsi->num_q_vectors; i++)
3594                         synchronize_irq(pf->msix_entries[i + base].vector);
3595         } else {
3596                 /* Legacy and MSI mode - this stops all interrupt handling */
3597                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
3598                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
3599                 i40e_flush(hw);
3600                 synchronize_irq(pf->pdev->irq);
3601         }
3602 }
3603
3604 /**
3605  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
3606  * @vsi: the VSI being configured
3607  **/
3608 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
3609 {
3610         struct i40e_pf *pf = vsi->back;
3611         int i;
3612
3613         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3614                 for (i = 0; i < vsi->num_q_vectors; i++)
3615                         i40e_irq_dynamic_enable(vsi, i);
3616         } else {
3617                 i40e_irq_dynamic_enable_icr0(pf, true);
3618         }
3619
3620         i40e_flush(&pf->hw);
3621         return 0;
3622 }
3623
3624 /**
3625  * i40e_stop_misc_vector - Stop the vector that handles non-queue events
3626  * @pf: board private structure
3627  **/
3628 static void i40e_stop_misc_vector(struct i40e_pf *pf)
3629 {
3630         /* Disable ICR 0 */
3631         wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
3632         i40e_flush(&pf->hw);
3633 }
3634
3635 /**
3636  * i40e_intr - MSI/Legacy and non-queue interrupt handler
3637  * @irq: interrupt number
3638  * @data: pointer to a q_vector
3639  *
3640  * This is the handler used for all MSI/Legacy interrupts, and deals
3641  * with both queue and non-queue interrupts.  This is also used in
3642  * MSIX mode to handle the non-queue interrupts.
3643  **/
3644 static irqreturn_t i40e_intr(int irq, void *data)
3645 {
3646         struct i40e_pf *pf = (struct i40e_pf *)data;
3647         struct i40e_hw *hw = &pf->hw;
3648         irqreturn_t ret = IRQ_NONE;
3649         u32 icr0, icr0_remaining;
3650         u32 val, ena_mask;
3651
3652         icr0 = rd32(hw, I40E_PFINT_ICR0);
3653         ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
3654
3655         /* if sharing a legacy IRQ, we might get called w/o an intr pending */
3656         if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
3657                 goto enable_intr;
3658
3659         /* if interrupt but no bits showing, must be SWINT */
3660         if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
3661             (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
3662                 pf->sw_int_count++;
3663
3664         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
3665             (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
3666                 ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3667                 dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
3668                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
3669         }
3670
3671         /* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
3672         if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
3673                 struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
3674                 struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3675
3676                 /* We do not have a way to disarm Queue causes while leaving
3677                  * interrupt enabled for all other causes, ideally
3678                  * interrupt should be disabled while we are in NAPI but
3679                  * this is not a performance path and napi_schedule()
3680                  * can deal with rescheduling.
3681                  */
3682                 if (!test_bit(__I40E_DOWN, pf->state))
3683                         napi_schedule_irqoff(&q_vector->napi);
3684         }
3685
3686         if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
3687                 ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3688                 set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
3689                 i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
3690         }
3691
3692         if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
3693                 ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
3694                 set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
3695         }
3696
3697         if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
3698                 ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
3699                 set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
3700         }
3701
3702         if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
3703                 if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
3704                         set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
3705                 ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
3706                 val = rd32(hw, I40E_GLGEN_RSTAT);
3707                 val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
3708                        >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
3709                 if (val == I40E_RESET_CORER) {
3710                         pf->corer_count++;
3711                 } else if (val == I40E_RESET_GLOBR) {
3712                         pf->globr_count++;
3713                 } else if (val == I40E_RESET_EMPR) {
3714                         pf->empr_count++;
3715                         set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
3716                 }
3717         }
3718
3719         if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
3720                 icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
3721                 dev_info(&pf->pdev->dev, "HMC error interrupt\n");
3722                 dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
3723                          rd32(hw, I40E_PFHMC_ERRORINFO),
3724                          rd32(hw, I40E_PFHMC_ERRORDATA));
3725         }
3726
3727         if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
3728                 u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
3729
3730                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK) {
3731                         icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3732                         i40e_ptp_tx_hwtstamp(pf);
3733                 }
3734         }
3735
3736         /* If a critical error is pending we have no choice but to reset the
3737          * device.
3738          * Report and mask out any remaining unexpected interrupts.
3739          */
3740         icr0_remaining = icr0 & ena_mask;
3741         if (icr0_remaining) {
3742                 dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
3743                          icr0_remaining);
3744                 if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
3745                     (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
3746                     (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
3747                         dev_info(&pf->pdev->dev, "device will be reset\n");
3748                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
3749                         i40e_service_event_schedule(pf);
3750                 }
3751                 ena_mask &= ~icr0_remaining;
3752         }
3753         ret = IRQ_HANDLED;
3754
3755 enable_intr:
3756         /* re-enable interrupt causes */
3757         wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
3758         if (!test_bit(__I40E_DOWN, pf->state)) {
3759                 i40e_service_event_schedule(pf);
3760                 i40e_irq_dynamic_enable_icr0(pf, false);
3761         }
3762
3763         return ret;
3764 }
3765
3766 /**
3767  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
3768  * @tx_ring:  tx ring to clean
3769  * @budget:   how many cleans we're allowed
3770  *
3771  * Returns true if there's any budget left (e.g. the clean is finished)
3772  **/
3773 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
3774 {
3775         struct i40e_vsi *vsi = tx_ring->vsi;
3776         u16 i = tx_ring->next_to_clean;
3777         struct i40e_tx_buffer *tx_buf;
3778         struct i40e_tx_desc *tx_desc;
3779
3780         tx_buf = &tx_ring->tx_bi[i];
3781         tx_desc = I40E_TX_DESC(tx_ring, i);
3782         i -= tx_ring->count;
3783
3784         do {
3785                 struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
3786
3787                 /* if next_to_watch is not set then there is no work pending */
3788                 if (!eop_desc)
3789                         break;
3790
3791                 /* prevent any other reads prior to eop_desc */
3792                 smp_rmb();
3793
3794                 /* if the descriptor isn't done, no work yet to do */
3795                 if (!(eop_desc->cmd_type_offset_bsz &
3796                       cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
3797                         break;
3798
3799                 /* clear next_to_watch to prevent false hangs */
3800                 tx_buf->next_to_watch = NULL;
3801
3802                 tx_desc->buffer_addr = 0;
3803                 tx_desc->cmd_type_offset_bsz = 0;
3804                 /* move past filter desc */
3805                 tx_buf++;
3806                 tx_desc++;
3807                 i++;
3808                 if (unlikely(!i)) {
3809                         i -= tx_ring->count;
3810                         tx_buf = tx_ring->tx_bi;
3811                         tx_desc = I40E_TX_DESC(tx_ring, 0);
3812                 }
3813                 /* unmap skb header data */
3814                 dma_unmap_single(tx_ring->dev,
3815                                  dma_unmap_addr(tx_buf, dma),
3816                                  dma_unmap_len(tx_buf, len),
3817                                  DMA_TO_DEVICE);
3818                 if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
3819                         kfree(tx_buf->raw_buf);
3820
3821                 tx_buf->raw_buf = NULL;
3822                 tx_buf->tx_flags = 0;
3823                 tx_buf->next_to_watch = NULL;
3824                 dma_unmap_len_set(tx_buf, len, 0);
3825                 tx_desc->buffer_addr = 0;
3826                 tx_desc->cmd_type_offset_bsz = 0;
3827
3828                 /* move us past the eop_desc for start of next FD desc */
3829                 tx_buf++;
3830                 tx_desc++;
3831                 i++;
3832                 if (unlikely(!i)) {
3833                         i -= tx_ring->count;
3834                         tx_buf = tx_ring->tx_bi;
3835                         tx_desc = I40E_TX_DESC(tx_ring, 0);
3836                 }
3837
3838                 /* update budget accounting */
3839                 budget--;
3840         } while (likely(budget));
3841
3842         i += tx_ring->count;
3843         tx_ring->next_to_clean = i;
3844
3845         if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
3846                 i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
3847
3848         return budget > 0;
3849 }
3850
3851 /**
3852  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
3853  * @irq: interrupt number
3854  * @data: pointer to a q_vector
3855  **/
3856 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
3857 {
3858         struct i40e_q_vector *q_vector = data;
3859         struct i40e_vsi *vsi;
3860
3861         if (!q_vector->tx.ring)
3862                 return IRQ_HANDLED;
3863
3864         vsi = q_vector->tx.ring->vsi;
3865         i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
3866
3867         return IRQ_HANDLED;
3868 }
3869
3870 /**
3871  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
3872  * @vsi: the VSI being configured
3873  * @v_idx: vector index
3874  * @qp_idx: queue pair index
3875  **/
3876 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
3877 {
3878         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
3879         struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
3880         struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
3881
3882         tx_ring->q_vector = q_vector;
3883         tx_ring->next = q_vector->tx.ring;
3884         q_vector->tx.ring = tx_ring;
3885         q_vector->tx.count++;
3886
3887         /* Place XDP Tx ring in the same q_vector ring list as regular Tx */
3888         if (i40e_enabled_xdp_vsi(vsi)) {
3889                 struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
3890
3891                 xdp_ring->q_vector = q_vector;
3892                 xdp_ring->next = q_vector->tx.ring;
3893                 q_vector->tx.ring = xdp_ring;
3894                 q_vector->tx.count++;
3895         }
3896
3897         rx_ring->q_vector = q_vector;
3898         rx_ring->next = q_vector->rx.ring;
3899         q_vector->rx.ring = rx_ring;
3900         q_vector->rx.count++;
3901 }
3902
3903 /**
3904  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
3905  * @vsi: the VSI being configured
3906  *
3907  * This function maps descriptor rings to the queue-specific vectors
3908  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
3909  * one vector per queue pair, but on a constrained vector budget, we
3910  * group the queue pairs as "efficiently" as possible.
3911  **/
3912 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
3913 {
3914         int qp_remaining = vsi->num_queue_pairs;
3915         int q_vectors = vsi->num_q_vectors;
3916         int num_ringpairs;
3917         int v_start = 0;
3918         int qp_idx = 0;
3919
3920         /* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
3921          * group them so there are multiple queues per vector.
3922          * It is also important to go through all the vectors available to be
3923          * sure that if we don't use all the vectors, that the remaining vectors
3924          * are cleared. This is especially important when decreasing the
3925          * number of queues in use.
3926          */
3927         for (; v_start < q_vectors; v_start++) {
3928                 struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
3929
3930                 num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
3931
3932                 q_vector->num_ringpairs = num_ringpairs;
3933
3934                 q_vector->rx.count = 0;
3935                 q_vector->tx.count = 0;
3936                 q_vector->rx.ring = NULL;
3937                 q_vector->tx.ring = NULL;
3938
3939                 while (num_ringpairs--) {
3940                         i40e_map_vector_to_qp(vsi, v_start, qp_idx);
3941                         qp_idx++;
3942                         qp_remaining--;
3943                 }
3944         }
3945 }
3946
3947 /**
3948  * i40e_vsi_request_irq - Request IRQ from the OS
3949  * @vsi: the VSI being configured
3950  * @basename: name for the vector
3951  **/
3952 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
3953 {
3954         struct i40e_pf *pf = vsi->back;
3955         int err;
3956
3957         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
3958                 err = i40e_vsi_request_irq_msix(vsi, basename);
3959         else if (pf->flags & I40E_FLAG_MSI_ENABLED)
3960                 err = request_irq(pf->pdev->irq, i40e_intr, 0,
3961                                   pf->int_name, pf);
3962         else
3963                 err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
3964                                   pf->int_name, pf);
3965
3966         if (err)
3967                 dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
3968
3969         return err;
3970 }
3971
3972 #ifdef CONFIG_NET_POLL_CONTROLLER
3973 /**
3974  * i40e_netpoll - A Polling 'interrupt' handler
3975  * @netdev: network interface device structure
3976  *
3977  * This is used by netconsole to send skbs without having to re-enable
3978  * interrupts.  It's not called while the normal interrupt routine is executing.
3979  **/
3980 static void i40e_netpoll(struct net_device *netdev)
3981 {
3982         struct i40e_netdev_priv *np = netdev_priv(netdev);
3983         struct i40e_vsi *vsi = np->vsi;
3984         struct i40e_pf *pf = vsi->back;
3985         int i;
3986
3987         /* if interface is down do nothing */
3988         if (test_bit(__I40E_VSI_DOWN, vsi->state))
3989                 return;
3990
3991         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3992                 for (i = 0; i < vsi->num_q_vectors; i++)
3993                         i40e_msix_clean_rings(0, vsi->q_vectors[i]);
3994         } else {
3995                 i40e_intr(pf->pdev->irq, netdev);
3996         }
3997 }
3998 #endif
3999
4000 #define I40E_QTX_ENA_WAIT_COUNT 50
4001
4002 /**
4003  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4004  * @pf: the PF being configured
4005  * @pf_q: the PF queue
4006  * @enable: enable or disable state of the queue
4007  *
4008  * This routine will wait for the given Tx queue of the PF to reach the
4009  * enabled or disabled state.
4010  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4011  * multiple retries; else will return 0 in case of success.
4012  **/
4013 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4014 {
4015         int i;
4016         u32 tx_reg;
4017
4018         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4019                 tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4020                 if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4021                         break;
4022
4023                 usleep_range(10, 20);
4024         }
4025         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4026                 return -ETIMEDOUT;
4027
4028         return 0;
4029 }
4030
4031 /**
4032  * i40e_control_tx_q - Start or stop a particular Tx queue
4033  * @pf: the PF structure
4034  * @pf_q: the PF queue to configure
4035  * @enable: start or stop the queue
4036  *
4037  * This function enables or disables a single queue. Note that any delay
4038  * required after the operation is expected to be handled by the caller of
4039  * this function.
4040  **/
4041 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4042 {
4043         struct i40e_hw *hw = &pf->hw;
4044         u32 tx_reg;
4045         int i;
4046
4047         /* warn the TX unit of coming changes */
4048         i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4049         if (!enable)
4050                 usleep_range(10, 20);
4051
4052         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4053                 tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4054                 if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4055                     ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4056                         break;
4057                 usleep_range(1000, 2000);
4058         }
4059
4060         /* Skip if the queue is already in the requested state */
4061         if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4062                 return;
4063
4064         /* turn on/off the queue */
4065         if (enable) {
4066                 wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4067                 tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4068         } else {
4069                 tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4070         }
4071
4072         wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4073 }
4074
4075 /**
4076  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4077  * @seid: VSI SEID
4078  * @pf: the PF structure
4079  * @pf_q: the PF queue to configure
4080  * @is_xdp: true if the queue is used for XDP
4081  * @enable: start or stop the queue
4082  **/
4083 static int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4084                                   bool is_xdp, bool enable)
4085 {
4086         int ret;
4087
4088         i40e_control_tx_q(pf, pf_q, enable);
4089
4090         /* wait for the change to finish */
4091         ret = i40e_pf_txq_wait(pf, pf_q, enable);
4092         if (ret) {
4093                 dev_info(&pf->pdev->dev,
4094                          "VSI seid %d %sTx ring %d %sable timeout\n",
4095                          seid, (is_xdp ? "XDP " : ""), pf_q,
4096                          (enable ? "en" : "dis"));
4097         }
4098
4099         return ret;
4100 }
4101
4102 /**
4103  * i40e_vsi_control_tx - Start or stop a VSI's rings
4104  * @vsi: the VSI being configured
4105  * @enable: start or stop the rings
4106  **/
4107 static int i40e_vsi_control_tx(struct i40e_vsi *vsi, bool enable)
4108 {
4109         struct i40e_pf *pf = vsi->back;
4110         int i, pf_q, ret = 0;
4111
4112         pf_q = vsi->base_queue;
4113         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4114                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4115                                              pf_q,
4116                                              false /*is xdp*/, enable);
4117                 if (ret)
4118                         break;
4119
4120                 if (!i40e_enabled_xdp_vsi(vsi))
4121                         continue;
4122
4123                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4124                                              pf_q + vsi->alloc_queue_pairs,
4125                                              true /*is xdp*/, enable);
4126                 if (ret)
4127                         break;
4128         }
4129
4130         return ret;
4131 }
4132
4133 /**
4134  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4135  * @pf: the PF being configured
4136  * @pf_q: the PF queue
4137  * @enable: enable or disable state of the queue
4138  *
4139  * This routine will wait for the given Rx queue of the PF to reach the
4140  * enabled or disabled state.
4141  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4142  * multiple retries; else will return 0 in case of success.
4143  **/
4144 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4145 {
4146         int i;
4147         u32 rx_reg;
4148
4149         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4150                 rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4151                 if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4152                         break;
4153
4154                 usleep_range(10, 20);
4155         }
4156         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4157                 return -ETIMEDOUT;
4158
4159         return 0;
4160 }
4161
4162 /**
4163  * i40e_control_rx_q - Start or stop a particular Rx queue
4164  * @pf: the PF structure
4165  * @pf_q: the PF queue to configure
4166  * @enable: start or stop the queue
4167  *
4168  * This function enables or disables a single queue. Note that any delay
4169  * required after the operation is expected to be handled by the caller of
4170  * this function.
4171  **/
4172 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4173 {
4174         struct i40e_hw *hw = &pf->hw;
4175         u32 rx_reg;
4176         int i;
4177
4178         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4179                 rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4180                 if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4181                     ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4182                         break;
4183                 usleep_range(1000, 2000);
4184         }
4185
4186         /* Skip if the queue is already in the requested state */
4187         if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4188                 return;
4189
4190         /* turn on/off the queue */
4191         if (enable)
4192                 rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4193         else
4194                 rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4195
4196         wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4197 }
4198
4199 /**
4200  * i40e_vsi_control_rx - Start or stop a VSI's rings
4201  * @vsi: the VSI being configured
4202  * @enable: start or stop the rings
4203  **/
4204 static int i40e_vsi_control_rx(struct i40e_vsi *vsi, bool enable)
4205 {
4206         struct i40e_pf *pf = vsi->back;
4207         int i, pf_q, ret = 0;
4208
4209         pf_q = vsi->base_queue;
4210         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4211                 i40e_control_rx_q(pf, pf_q, enable);
4212
4213                 /* wait for the change to finish */
4214                 ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4215                 if (ret) {
4216                         dev_info(&pf->pdev->dev,
4217                                  "VSI seid %d Rx ring %d %sable timeout\n",
4218                                  vsi->seid, pf_q, (enable ? "en" : "dis"));
4219                         break;
4220                 }
4221         }
4222
4223         /* Due to HW errata, on Rx disable only, the register can indicate done
4224          * before it really is. Needs 50ms to be sure
4225          */
4226         if (!enable)
4227                 mdelay(50);
4228
4229         return ret;
4230 }
4231
4232 /**
4233  * i40e_vsi_start_rings - Start a VSI's rings
4234  * @vsi: the VSI being configured
4235  **/
4236 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4237 {
4238         int ret = 0;
4239
4240         /* do rx first for enable and last for disable */
4241         ret = i40e_vsi_control_rx(vsi, true);
4242         if (ret)
4243                 return ret;
4244         ret = i40e_vsi_control_tx(vsi, true);
4245
4246         return ret;
4247 }
4248
4249 /**
4250  * i40e_vsi_stop_rings - Stop a VSI's rings
4251  * @vsi: the VSI being configured
4252  **/
4253 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4254 {
4255         /* When port TX is suspended, don't wait */
4256         if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4257                 return i40e_vsi_stop_rings_no_wait(vsi);
4258
4259         /* do rx first for enable and last for disable
4260          * Ignore return value, we need to shutdown whatever we can
4261          */
4262         i40e_vsi_control_tx(vsi, false);
4263         i40e_vsi_control_rx(vsi, false);
4264 }
4265
4266 /**
4267  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4268  * @vsi: the VSI being shutdown
4269  *
4270  * This function stops all the rings for a VSI but does not delay to verify
4271  * that rings have been disabled. It is expected that the caller is shutting
4272  * down multiple VSIs at once and will delay together for all the VSIs after
4273  * initiating the shutdown. This is particularly useful for shutting down lots
4274  * of VFs together. Otherwise, a large delay can be incurred while configuring
4275  * each VSI in serial.
4276  **/
4277 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4278 {
4279         struct i40e_pf *pf = vsi->back;
4280         int i, pf_q;
4281
4282         pf_q = vsi->base_queue;
4283         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4284                 i40e_control_tx_q(pf, pf_q, false);
4285                 i40e_control_rx_q(pf, pf_q, false);
4286         }
4287 }
4288
4289 /**
4290  * i40e_vsi_free_irq - Free the irq association with the OS
4291  * @vsi: the VSI being configured
4292  **/
4293 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4294 {
4295         struct i40e_pf *pf = vsi->back;
4296         struct i40e_hw *hw = &pf->hw;
4297         int base = vsi->base_vector;
4298         u32 val, qp;
4299         int i;
4300
4301         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4302                 if (!vsi->q_vectors)
4303                         return;
4304
4305                 if (!vsi->irqs_ready)
4306                         return;
4307
4308                 vsi->irqs_ready = false;
4309                 for (i = 0; i < vsi->num_q_vectors; i++) {
4310                         int irq_num;
4311                         u16 vector;
4312
4313                         vector = i + base;
4314                         irq_num = pf->msix_entries[vector].vector;
4315
4316                         /* free only the irqs that were actually requested */
4317                         if (!vsi->q_vectors[i] ||
4318                             !vsi->q_vectors[i]->num_ringpairs)
4319                                 continue;
4320
4321                         /* clear the affinity notifier in the IRQ descriptor */
4322                         irq_set_affinity_notifier(irq_num, NULL);
4323                         /* remove our suggested affinity mask for this IRQ */
4324                         irq_set_affinity_hint(irq_num, NULL);
4325                         synchronize_irq(irq_num);
4326                         free_irq(irq_num, vsi->q_vectors[i]);
4327
4328                         /* Tear down the interrupt queue link list
4329                          *
4330                          * We know that they come in pairs and always
4331                          * the Rx first, then the Tx.  To clear the
4332                          * link list, stick the EOL value into the
4333                          * next_q field of the registers.
4334                          */
4335                         val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4336                         qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4337                                 >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4338                         val |= I40E_QUEUE_END_OF_LIST
4339                                 << I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4340                         wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4341
4342                         while (qp != I40E_QUEUE_END_OF_LIST) {
4343                                 u32 next;
4344
4345                                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4346
4347                                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4348                                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4349                                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4350                                          I40E_QINT_RQCTL_INTEVENT_MASK);
4351
4352                                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4353                                          I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4354
4355                                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4356
4357                                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4358
4359                                 next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
4360                                         >> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
4361
4362                                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4363                                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4364                                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4365                                          I40E_QINT_TQCTL_INTEVENT_MASK);
4366
4367                                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4368                                          I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4369
4370                                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4371                                 qp = next;
4372                         }
4373                 }
4374         } else {
4375                 free_irq(pf->pdev->irq, pf);
4376
4377                 val = rd32(hw, I40E_PFINT_LNKLST0);
4378                 qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4379                         >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4380                 val |= I40E_QUEUE_END_OF_LIST
4381                         << I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
4382                 wr32(hw, I40E_PFINT_LNKLST0, val);
4383
4384                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4385                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4386                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4387                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4388                          I40E_QINT_RQCTL_INTEVENT_MASK);
4389
4390                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4391                         I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4392
4393                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4394
4395                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4396
4397                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4398                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4399                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4400                          I40E_QINT_TQCTL_INTEVENT_MASK);
4401
4402                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4403                         I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4404
4405                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4406         }
4407 }
4408
4409 /**
4410  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
4411  * @vsi: the VSI being configured
4412  * @v_idx: Index of vector to be freed
4413  *
4414  * This function frees the memory allocated to the q_vector.  In addition if
4415  * NAPI is enabled it will delete any references to the NAPI struct prior
4416  * to freeing the q_vector.
4417  **/
4418 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
4419 {
4420         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4421         struct i40e_ring *ring;
4422
4423         if (!q_vector)
4424                 return;
4425
4426         /* disassociate q_vector from rings */
4427         i40e_for_each_ring(ring, q_vector->tx)
4428                 ring->q_vector = NULL;
4429
4430         i40e_for_each_ring(ring, q_vector->rx)
4431                 ring->q_vector = NULL;
4432
4433         /* only VSI w/ an associated netdev is set up w/ NAPI */
4434         if (vsi->netdev)
4435                 netif_napi_del(&q_vector->napi);
4436
4437         vsi->q_vectors[v_idx] = NULL;
4438
4439         kfree_rcu(q_vector, rcu);
4440 }
4441
4442 /**
4443  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
4444  * @vsi: the VSI being un-configured
4445  *
4446  * This frees the memory allocated to the q_vectors and
4447  * deletes references to the NAPI struct.
4448  **/
4449 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
4450 {
4451         int v_idx;
4452
4453         for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
4454                 i40e_free_q_vector(vsi, v_idx);
4455 }
4456
4457 /**
4458  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
4459  * @pf: board private structure
4460  **/
4461 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
4462 {
4463         /* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
4464         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4465                 pci_disable_msix(pf->pdev);
4466                 kfree(pf->msix_entries);
4467                 pf->msix_entries = NULL;
4468                 kfree(pf->irq_pile);
4469                 pf->irq_pile = NULL;
4470         } else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
4471                 pci_disable_msi(pf->pdev);
4472         }
4473         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
4474 }
4475
4476 /**
4477  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
4478  * @pf: board private structure
4479  *
4480  * We go through and clear interrupt specific resources and reset the structure
4481  * to pre-load conditions
4482  **/
4483 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
4484 {
4485         int i;
4486
4487         i40e_stop_misc_vector(pf);
4488         if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4489                 synchronize_irq(pf->msix_entries[0].vector);
4490                 free_irq(pf->msix_entries[0].vector, pf);
4491         }
4492
4493         i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
4494                       I40E_IWARP_IRQ_PILE_ID);
4495
4496         i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
4497         for (i = 0; i < pf->num_alloc_vsi; i++)
4498                 if (pf->vsi[i])
4499                         i40e_vsi_free_q_vectors(pf->vsi[i]);
4500         i40e_reset_interrupt_capability(pf);
4501 }
4502
4503 /**
4504  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
4505  * @vsi: the VSI being configured
4506  **/
4507 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
4508 {
4509         int q_idx;
4510
4511         if (!vsi->netdev)
4512                 return;
4513
4514         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4515                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4516
4517                 if (q_vector->rx.ring || q_vector->tx.ring)
4518                         napi_enable(&q_vector->napi);
4519         }
4520 }
4521
4522 /**
4523  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
4524  * @vsi: the VSI being configured
4525  **/
4526 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
4527 {
4528         int q_idx;
4529
4530         if (!vsi->netdev)
4531                 return;
4532
4533         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4534                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4535
4536                 if (q_vector->rx.ring || q_vector->tx.ring)
4537                         napi_disable(&q_vector->napi);
4538         }
4539 }
4540
4541 /**
4542  * i40e_vsi_close - Shut down a VSI
4543  * @vsi: the vsi to be quelled
4544  **/
4545 static void i40e_vsi_close(struct i40e_vsi *vsi)
4546 {
4547         struct i40e_pf *pf = vsi->back;
4548         if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
4549                 i40e_down(vsi);
4550         i40e_vsi_free_irq(vsi);
4551         i40e_vsi_free_tx_resources(vsi);
4552         i40e_vsi_free_rx_resources(vsi);
4553         vsi->current_netdev_flags = 0;
4554         pf->flags |= I40E_FLAG_SERVICE_CLIENT_REQUESTED;
4555         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4556                 pf->flags |=  I40E_FLAG_CLIENT_RESET;
4557 }
4558
4559 /**
4560  * i40e_quiesce_vsi - Pause a given VSI
4561  * @vsi: the VSI being paused
4562  **/
4563 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
4564 {
4565         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4566                 return;
4567
4568         set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
4569         if (vsi->netdev && netif_running(vsi->netdev))
4570                 vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
4571         else
4572                 i40e_vsi_close(vsi);
4573 }
4574
4575 /**
4576  * i40e_unquiesce_vsi - Resume a given VSI
4577  * @vsi: the VSI being resumed
4578  **/
4579 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
4580 {
4581         if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
4582                 return;
4583
4584         if (vsi->netdev && netif_running(vsi->netdev))
4585                 vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
4586         else
4587                 i40e_vsi_open(vsi);   /* this clears the DOWN bit */
4588 }
4589
4590 /**
4591  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
4592  * @pf: the PF
4593  **/
4594 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
4595 {
4596         int v;
4597
4598         for (v = 0; v < pf->num_alloc_vsi; v++) {
4599                 if (pf->vsi[v])
4600                         i40e_quiesce_vsi(pf->vsi[v]);
4601         }
4602 }
4603
4604 /**
4605  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
4606  * @pf: the PF
4607  **/
4608 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
4609 {
4610         int v;
4611
4612         for (v = 0; v < pf->num_alloc_vsi; v++) {
4613                 if (pf->vsi[v])
4614                         i40e_unquiesce_vsi(pf->vsi[v]);
4615         }
4616 }
4617
4618 /**
4619  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
4620  * @vsi: the VSI being configured
4621  *
4622  * Wait until all queues on a given VSI have been disabled.
4623  **/
4624 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
4625 {
4626         struct i40e_pf *pf = vsi->back;
4627         int i, pf_q, ret;
4628
4629         pf_q = vsi->base_queue;
4630         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4631                 /* Check and wait for the Tx queue */
4632                 ret = i40e_pf_txq_wait(pf, pf_q, false);
4633                 if (ret) {
4634                         dev_info(&pf->pdev->dev,
4635                                  "VSI seid %d Tx ring %d disable timeout\n",
4636                                  vsi->seid, pf_q);
4637                         return ret;
4638                 }
4639
4640                 if (!i40e_enabled_xdp_vsi(vsi))
4641                         goto wait_rx;
4642
4643                 /* Check and wait for the XDP Tx queue */
4644                 ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
4645                                        false);
4646                 if (ret) {
4647                         dev_info(&pf->pdev->dev,
4648                                  "VSI seid %d XDP Tx ring %d disable timeout\n",
4649                                  vsi->seid, pf_q);
4650                         return ret;
4651                 }
4652 wait_rx:
4653                 /* Check and wait for the Rx queue */
4654                 ret = i40e_pf_rxq_wait(pf, pf_q, false);
4655                 if (ret) {
4656                         dev_info(&pf->pdev->dev,
4657                                  "VSI seid %d Rx ring %d disable timeout\n",
4658                                  vsi->seid, pf_q);
4659                         return ret;
4660                 }
4661         }
4662
4663         return 0;
4664 }
4665
4666 #ifdef CONFIG_I40E_DCB
4667 /**
4668  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
4669  * @pf: the PF
4670  *
4671  * This function waits for the queues to be in disabled state for all the
4672  * VSIs that are managed by this PF.
4673  **/
4674 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
4675 {
4676         int v, ret = 0;
4677
4678         for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
4679                 if (pf->vsi[v]) {
4680                         ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
4681                         if (ret)
4682                                 break;
4683                 }
4684         }
4685
4686         return ret;
4687 }
4688
4689 #endif
4690
4691 /**
4692  * i40e_detect_recover_hung_queue - Function to detect and recover hung_queue
4693  * @q_idx: TX queue number
4694  * @vsi: Pointer to VSI struct
4695  *
4696  * This function checks specified queue for given VSI. Detects hung condition.
4697  * We proactively detect hung TX queues by checking if interrupts are disabled
4698  * but there are pending descriptors.  If it appears hung, attempt to recover
4699  * by triggering a SW interrupt.
4700  **/
4701 static void i40e_detect_recover_hung_queue(int q_idx, struct i40e_vsi *vsi)
4702 {
4703         struct i40e_ring *tx_ring = NULL;
4704         struct i40e_pf  *pf;
4705         u32 val, tx_pending;
4706         int i;
4707
4708         pf = vsi->back;
4709
4710         /* now that we have an index, find the tx_ring struct */
4711         for (i = 0; i < vsi->num_queue_pairs; i++) {
4712                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
4713                         if (q_idx == vsi->tx_rings[i]->queue_index) {
4714                                 tx_ring = vsi->tx_rings[i];
4715                                 break;
4716                         }
4717                 }
4718         }
4719
4720         if (!tx_ring)
4721                 return;
4722
4723         /* Read interrupt register */
4724         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4725                 val = rd32(&pf->hw,
4726                            I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
4727                                                tx_ring->vsi->base_vector - 1));
4728         else
4729                 val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
4730
4731         tx_pending = i40e_get_tx_pending(tx_ring);
4732
4733         /* Interrupts are disabled and TX pending is non-zero,
4734          * trigger the SW interrupt (don't wait). Worst case
4735          * there will be one extra interrupt which may result
4736          * into not cleaning any queues because queues are cleaned.
4737          */
4738         if (tx_pending && (!(val & I40E_PFINT_DYN_CTLN_INTENA_MASK)))
4739                 i40e_force_wb(vsi, tx_ring->q_vector);
4740 }
4741
4742 /**
4743  * i40e_detect_recover_hung - Function to detect and recover hung_queues
4744  * @pf:  pointer to PF struct
4745  *
4746  * LAN VSI has netdev and netdev has TX queues. This function is to check
4747  * each of those TX queues if they are hung, trigger recovery by issuing
4748  * SW interrupt.
4749  **/
4750 static void i40e_detect_recover_hung(struct i40e_pf *pf)
4751 {
4752         struct net_device *netdev;
4753         struct i40e_vsi *vsi;
4754         unsigned int i;
4755
4756         /* Only for LAN VSI */
4757         vsi = pf->vsi[pf->lan_vsi];
4758
4759         if (!vsi)
4760                 return;
4761
4762         /* Make sure, VSI state is not DOWN/RECOVERY_PENDING */
4763         if (test_bit(__I40E_VSI_DOWN, vsi->back->state) ||
4764             test_bit(__I40E_RESET_RECOVERY_PENDING, vsi->back->state))
4765                 return;
4766
4767         /* Make sure type is MAIN VSI */
4768         if (vsi->type != I40E_VSI_MAIN)
4769                 return;
4770
4771         netdev = vsi->netdev;
4772         if (!netdev)
4773                 return;
4774
4775         /* Bail out if netif_carrier is not OK */
4776         if (!netif_carrier_ok(netdev))
4777                 return;
4778
4779         /* Go thru' TX queues for netdev */
4780         for (i = 0; i < netdev->num_tx_queues; i++) {
4781                 struct netdev_queue *q;
4782
4783                 q = netdev_get_tx_queue(netdev, i);
4784                 if (q)
4785                         i40e_detect_recover_hung_queue(i, vsi);
4786         }
4787 }
4788
4789 /**
4790  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
4791  * @pf: pointer to PF
4792  *
4793  * Get TC map for ISCSI PF type that will include iSCSI TC
4794  * and LAN TC.
4795  **/
4796 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
4797 {
4798         struct i40e_dcb_app_priority_table app;
4799         struct i40e_hw *hw = &pf->hw;
4800         u8 enabled_tc = 1; /* TC0 is always enabled */
4801         u8 tc, i;
4802         /* Get the iSCSI APP TLV */
4803         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
4804
4805         for (i = 0; i < dcbcfg->numapps; i++) {
4806                 app = dcbcfg->app[i];
4807                 if (app.selector == I40E_APP_SEL_TCPIP &&
4808                     app.protocolid == I40E_APP_PROTOID_ISCSI) {
4809                         tc = dcbcfg->etscfg.prioritytable[app.priority];
4810                         enabled_tc |= BIT(tc);
4811                         break;
4812                 }
4813         }
4814
4815         return enabled_tc;
4816 }
4817
4818 /**
4819  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
4820  * @dcbcfg: the corresponding DCBx configuration structure
4821  *
4822  * Return the number of TCs from given DCBx configuration
4823  **/
4824 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
4825 {
4826         int i, tc_unused = 0;
4827         u8 num_tc = 0;
4828         u8 ret = 0;
4829
4830         /* Scan the ETS Config Priority Table to find
4831          * traffic class enabled for a given priority
4832          * and create a bitmask of enabled TCs
4833          */
4834         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
4835                 num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
4836
4837         /* Now scan the bitmask to check for
4838          * contiguous TCs starting with TC0
4839          */
4840         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
4841                 if (num_tc & BIT(i)) {
4842                         if (!tc_unused) {
4843                                 ret++;
4844                         } else {
4845                                 pr_err("Non-contiguous TC - Disabling DCB\n");
4846                                 return 1;
4847                         }
4848                 } else {
4849                         tc_unused = 1;
4850                 }
4851         }
4852
4853         /* There is always at least TC0 */
4854         if (!ret)
4855                 ret = 1;
4856
4857         return ret;
4858 }
4859
4860 /**
4861  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
4862  * @dcbcfg: the corresponding DCBx configuration structure
4863  *
4864  * Query the current DCB configuration and return the number of
4865  * traffic classes enabled from the given DCBX config
4866  **/
4867 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
4868 {
4869         u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
4870         u8 enabled_tc = 1;
4871         u8 i;
4872
4873         for (i = 0; i < num_tc; i++)
4874                 enabled_tc |= BIT(i);
4875
4876         return enabled_tc;
4877 }
4878
4879 /**
4880  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
4881  * @pf: PF being queried
4882  *
4883  * Return number of traffic classes enabled for the given PF
4884  **/
4885 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
4886 {
4887         struct i40e_hw *hw = &pf->hw;
4888         u8 i, enabled_tc = 1;
4889         u8 num_tc = 0;
4890         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
4891
4892         /* If DCB is not enabled then always in single TC */
4893         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
4894                 return 1;
4895
4896         /* SFP mode will be enabled for all TCs on port */
4897         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
4898                 return i40e_dcb_get_num_tc(dcbcfg);
4899
4900         /* MFP mode return count of enabled TCs for this PF */
4901         if (pf->hw.func_caps.iscsi)
4902                 enabled_tc =  i40e_get_iscsi_tc_map(pf);
4903         else
4904                 return 1; /* Only TC0 */
4905
4906         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
4907                 if (enabled_tc & BIT(i))
4908                         num_tc++;
4909         }
4910         return num_tc;
4911 }
4912
4913 /**
4914  * i40e_pf_get_pf_tc_map - Get bitmap for enabled traffic classes
4915  * @pf: PF being queried
4916  *
4917  * Return a bitmap for enabled traffic classes for this PF.
4918  **/
4919 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
4920 {
4921         /* If DCB is not enabled for this PF then just return default TC */
4922         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
4923                 return I40E_DEFAULT_TRAFFIC_CLASS;
4924
4925         /* SFP mode we want PF to be enabled for all TCs */
4926         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
4927                 return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
4928
4929         /* MFP enabled and iSCSI PF type */
4930         if (pf->hw.func_caps.iscsi)
4931                 return i40e_get_iscsi_tc_map(pf);
4932         else
4933                 return I40E_DEFAULT_TRAFFIC_CLASS;
4934 }
4935
4936 /**
4937  * i40e_vsi_get_bw_info - Query VSI BW Information
4938  * @vsi: the VSI being queried
4939  *
4940  * Returns 0 on success, negative value on failure
4941  **/
4942 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
4943 {
4944         struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
4945         struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
4946         struct i40e_pf *pf = vsi->back;
4947         struct i40e_hw *hw = &pf->hw;
4948         i40e_status ret;
4949         u32 tc_bw_max;
4950         int i;
4951
4952         /* Get the VSI level BW configuration */
4953         ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
4954         if (ret) {
4955                 dev_info(&pf->pdev->dev,
4956                          "couldn't get PF vsi bw config, err %s aq_err %s\n",
4957                          i40e_stat_str(&pf->hw, ret),
4958                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
4959                 return -EINVAL;
4960         }
4961
4962         /* Get the VSI level BW configuration per TC */
4963         ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
4964                                                NULL);
4965         if (ret) {
4966                 dev_info(&pf->pdev->dev,
4967                          "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
4968                          i40e_stat_str(&pf->hw, ret),
4969                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
4970                 return -EINVAL;
4971         }
4972
4973         if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
4974                 dev_info(&pf->pdev->dev,
4975                          "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
4976                          bw_config.tc_valid_bits,
4977                          bw_ets_config.tc_valid_bits);
4978                 /* Still continuing */
4979         }
4980
4981         vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
4982         vsi->bw_max_quanta = bw_config.max_bw;
4983         tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
4984                     (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
4985         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
4986                 vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
4987                 vsi->bw_ets_limit_credits[i] =
4988                                         le16_to_cpu(bw_ets_config.credits[i]);
4989                 /* 3 bits out of 4 for each TC */
4990                 vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
4991         }
4992
4993         return 0;
4994 }
4995
4996 /**
4997  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
4998  * @vsi: the VSI being configured
4999  * @enabled_tc: TC bitmap
5000  * @bw_credits: BW shared credits per TC
5001  *
5002  * Returns 0 on success, negative value on failure
5003  **/
5004 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5005                                        u8 *bw_share)
5006 {
5007         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5008         i40e_status ret;
5009         int i;
5010
5011         bw_data.tc_valid_bits = enabled_tc;
5012         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5013                 bw_data.tc_bw_credits[i] = bw_share[i];
5014
5015         ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, vsi->seid, &bw_data,
5016                                        NULL);
5017         if (ret) {
5018                 dev_info(&vsi->back->pdev->dev,
5019                          "AQ command Config VSI BW allocation per TC failed = %d\n",
5020                          vsi->back->hw.aq.asq_last_status);
5021                 return -EINVAL;
5022         }
5023
5024         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5025                 vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5026
5027         return 0;
5028 }
5029
5030 /**
5031  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5032  * @vsi: the VSI being configured
5033  * @enabled_tc: TC map to be enabled
5034  *
5035  **/
5036 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5037 {
5038         struct net_device *netdev = vsi->netdev;
5039         struct i40e_pf *pf = vsi->back;
5040         struct i40e_hw *hw = &pf->hw;
5041         u8 netdev_tc = 0;
5042         int i;
5043         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5044
5045         if (!netdev)
5046                 return;
5047
5048         if (!enabled_tc) {
5049                 netdev_reset_tc(netdev);
5050                 return;
5051         }
5052
5053         /* Set up actual enabled TCs on the VSI */
5054         if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5055                 return;
5056
5057         /* set per TC queues for the VSI */
5058         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5059                 /* Only set TC queues for enabled tcs
5060                  *
5061                  * e.g. For a VSI that has TC0 and TC3 enabled the
5062                  * enabled_tc bitmap would be 0x00001001; the driver
5063                  * will set the numtc for netdev as 2 that will be
5064                  * referenced by the netdev layer as TC 0 and 1.
5065                  */
5066                 if (vsi->tc_config.enabled_tc & BIT(i))
5067                         netdev_set_tc_queue(netdev,
5068                                         vsi->tc_config.tc_info[i].netdev_tc,
5069                                         vsi->tc_config.tc_info[i].qcount,
5070                                         vsi->tc_config.tc_info[i].qoffset);
5071         }
5072
5073         /* Assign UP2TC map for the VSI */
5074         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5075                 /* Get the actual TC# for the UP */
5076                 u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5077                 /* Get the mapped netdev TC# for the UP */
5078                 netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5079                 netdev_set_prio_tc_map(netdev, i, netdev_tc);
5080         }
5081 }
5082
5083 /**
5084  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5085  * @vsi: the VSI being configured
5086  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5087  **/
5088 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5089                                       struct i40e_vsi_context *ctxt)
5090 {
5091         /* copy just the sections touched not the entire info
5092          * since not all sections are valid as returned by
5093          * update vsi params
5094          */
5095         vsi->info.mapping_flags = ctxt->info.mapping_flags;
5096         memcpy(&vsi->info.queue_mapping,
5097                &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5098         memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5099                sizeof(vsi->info.tc_mapping));
5100 }
5101
5102 /**
5103  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5104  * @vsi: VSI to be configured
5105  * @enabled_tc: TC bitmap
5106  *
5107  * This configures a particular VSI for TCs that are mapped to the
5108  * given TC bitmap. It uses default bandwidth share for TCs across
5109  * VSIs to configure TC for a particular VSI.
5110  *
5111  * NOTE:
5112  * It is expected that the VSI queues have been quisced before calling
5113  * this function.
5114  **/
5115 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5116 {
5117         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5118         struct i40e_vsi_context ctxt;
5119         int ret = 0;
5120         int i;
5121
5122         /* Check if enabled_tc is same as existing or new TCs */
5123         if (vsi->tc_config.enabled_tc == enabled_tc)
5124                 return ret;
5125
5126         /* Enable ETS TCs with equal BW Share for now across all VSIs */
5127         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5128                 if (enabled_tc & BIT(i))
5129                         bw_share[i] = 1;
5130         }
5131
5132         ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5133         if (ret) {
5134                 dev_info(&vsi->back->pdev->dev,
5135                          "Failed configuring TC map %d for VSI %d\n",
5136                          enabled_tc, vsi->seid);
5137                 goto out;
5138         }
5139
5140         /* Update Queue Pairs Mapping for currently enabled UPs */
5141         ctxt.seid = vsi->seid;
5142         ctxt.pf_num = vsi->back->hw.pf_id;
5143         ctxt.vf_num = 0;
5144         ctxt.uplink_seid = vsi->uplink_seid;
5145         ctxt.info = vsi->info;
5146         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5147
5148         if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5149                 ctxt.info.valid_sections |=
5150                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5151                 ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5152         }
5153
5154         /* Update the VSI after updating the VSI queue-mapping information */
5155         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
5156         if (ret) {
5157                 dev_info(&vsi->back->pdev->dev,
5158                          "Update vsi tc config failed, err %s aq_err %s\n",
5159                          i40e_stat_str(&vsi->back->hw, ret),
5160                          i40e_aq_str(&vsi->back->hw,
5161                                      vsi->back->hw.aq.asq_last_status));
5162                 goto out;
5163         }
5164         /* update the local VSI info with updated queue map */
5165         i40e_vsi_update_queue_map(vsi, &ctxt);
5166         vsi->info.valid_sections = 0;
5167
5168         /* Update current VSI BW information */
5169         ret = i40e_vsi_get_bw_info(vsi);
5170         if (ret) {
5171                 dev_info(&vsi->back->pdev->dev,
5172                          "Failed updating vsi bw info, err %s aq_err %s\n",
5173                          i40e_stat_str(&vsi->back->hw, ret),
5174                          i40e_aq_str(&vsi->back->hw,
5175                                      vsi->back->hw.aq.asq_last_status));
5176                 goto out;
5177         }
5178
5179         /* Update the netdev TC setup */
5180         i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5181 out:
5182         return ret;
5183 }
5184
5185 /**
5186  * i40e_veb_config_tc - Configure TCs for given VEB
5187  * @veb: given VEB
5188  * @enabled_tc: TC bitmap
5189  *
5190  * Configures given TC bitmap for VEB (switching) element
5191  **/
5192 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
5193 {
5194         struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
5195         struct i40e_pf *pf = veb->pf;
5196         int ret = 0;
5197         int i;
5198
5199         /* No TCs or already enabled TCs just return */
5200         if (!enabled_tc || veb->enabled_tc == enabled_tc)
5201                 return ret;
5202
5203         bw_data.tc_valid_bits = enabled_tc;
5204         /* bw_data.absolute_credits is not set (relative) */
5205
5206         /* Enable ETS TCs with equal BW Share for now */
5207         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5208                 if (enabled_tc & BIT(i))
5209                         bw_data.tc_bw_share_credits[i] = 1;
5210         }
5211
5212         ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
5213                                                    &bw_data, NULL);
5214         if (ret) {
5215                 dev_info(&pf->pdev->dev,
5216                          "VEB bw config failed, err %s aq_err %s\n",
5217                          i40e_stat_str(&pf->hw, ret),
5218                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5219                 goto out;
5220         }
5221
5222         /* Update the BW information */
5223         ret = i40e_veb_get_bw_info(veb);
5224         if (ret) {
5225                 dev_info(&pf->pdev->dev,
5226                          "Failed getting veb bw config, err %s aq_err %s\n",
5227                          i40e_stat_str(&pf->hw, ret),
5228                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5229         }
5230
5231 out:
5232         return ret;
5233 }
5234
5235 #ifdef CONFIG_I40E_DCB
5236 /**
5237  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
5238  * @pf: PF struct
5239  *
5240  * Reconfigure VEB/VSIs on a given PF; it is assumed that
5241  * the caller would've quiesce all the VSIs before calling
5242  * this function
5243  **/
5244 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
5245 {
5246         u8 tc_map = 0;
5247         int ret;
5248         u8 v;
5249
5250         /* Enable the TCs available on PF to all VEBs */
5251         tc_map = i40e_pf_get_tc_map(pf);
5252         for (v = 0; v < I40E_MAX_VEB; v++) {
5253                 if (!pf->veb[v])
5254                         continue;
5255                 ret = i40e_veb_config_tc(pf->veb[v], tc_map);
5256                 if (ret) {
5257                         dev_info(&pf->pdev->dev,
5258                                  "Failed configuring TC for VEB seid=%d\n",
5259                                  pf->veb[v]->seid);
5260                         /* Will try to configure as many components */
5261                 }
5262         }
5263
5264         /* Update each VSI */
5265         for (v = 0; v < pf->num_alloc_vsi; v++) {
5266                 if (!pf->vsi[v])
5267                         continue;
5268
5269                 /* - Enable all TCs for the LAN VSI
5270                  * - For all others keep them at TC0 for now
5271                  */
5272                 if (v == pf->lan_vsi)
5273                         tc_map = i40e_pf_get_tc_map(pf);
5274                 else
5275                         tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
5276
5277                 ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
5278                 if (ret) {
5279                         dev_info(&pf->pdev->dev,
5280                                  "Failed configuring TC for VSI seid=%d\n",
5281                                  pf->vsi[v]->seid);
5282                         /* Will try to configure as many components */
5283                 } else {
5284                         /* Re-configure VSI vectors based on updated TC map */
5285                         i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
5286                         if (pf->vsi[v]->netdev)
5287                                 i40e_dcbnl_set_all(pf->vsi[v]);
5288                 }
5289         }
5290 }
5291
5292 /**
5293  * i40e_resume_port_tx - Resume port Tx
5294  * @pf: PF struct
5295  *
5296  * Resume a port's Tx and issue a PF reset in case of failure to
5297  * resume.
5298  **/
5299 static int i40e_resume_port_tx(struct i40e_pf *pf)
5300 {
5301         struct i40e_hw *hw = &pf->hw;
5302         int ret;
5303
5304         ret = i40e_aq_resume_port_tx(hw, NULL);
5305         if (ret) {
5306                 dev_info(&pf->pdev->dev,
5307                          "Resume Port Tx failed, err %s aq_err %s\n",
5308                           i40e_stat_str(&pf->hw, ret),
5309                           i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5310                 /* Schedule PF reset to recover */
5311                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
5312                 i40e_service_event_schedule(pf);
5313         }
5314
5315         return ret;
5316 }
5317
5318 /**
5319  * i40e_init_pf_dcb - Initialize DCB configuration
5320  * @pf: PF being configured
5321  *
5322  * Query the current DCB configuration and cache it
5323  * in the hardware structure
5324  **/
5325 static int i40e_init_pf_dcb(struct i40e_pf *pf)
5326 {
5327         struct i40e_hw *hw = &pf->hw;
5328         int err = 0;
5329
5330         /* Do not enable DCB for SW1 and SW2 images even if the FW is capable */
5331         if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT)
5332                 goto out;
5333
5334         /* Get the initial DCB configuration */
5335         err = i40e_init_dcb(hw);
5336         if (!err) {
5337                 /* Device/Function is not DCBX capable */
5338                 if ((!hw->func_caps.dcb) ||
5339                     (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
5340                         dev_info(&pf->pdev->dev,
5341                                  "DCBX offload is not supported or is disabled for this PF.\n");
5342                 } else {
5343                         /* When status is not DISABLED then DCBX in FW */
5344                         pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
5345                                        DCB_CAP_DCBX_VER_IEEE;
5346
5347                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
5348                         /* Enable DCB tagging only when more than one TC
5349                          * or explicitly disable if only one TC
5350                          */
5351                         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
5352                                 pf->flags |= I40E_FLAG_DCB_ENABLED;
5353                         else
5354                                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
5355                         dev_dbg(&pf->pdev->dev,
5356                                 "DCBX offload is supported for this PF.\n");
5357                 }
5358         } else {
5359                 dev_info(&pf->pdev->dev,
5360                          "Query for DCB configuration failed, err %s aq_err %s\n",
5361                          i40e_stat_str(&pf->hw, err),
5362                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5363         }
5364
5365 out:
5366         return err;
5367 }
5368 #endif /* CONFIG_I40E_DCB */
5369 #define SPEED_SIZE 14
5370 #define FC_SIZE 8
5371 /**
5372  * i40e_print_link_message - print link up or down
5373  * @vsi: the VSI for which link needs a message
5374  */
5375 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
5376 {
5377         enum i40e_aq_link_speed new_speed;
5378         char *speed = "Unknown";
5379         char *fc = "Unknown";
5380         char *fec = "";
5381         char *req_fec = "";
5382         char *an = "";
5383
5384         new_speed = vsi->back->hw.phy.link_info.link_speed;
5385
5386         if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
5387                 return;
5388         vsi->current_isup = isup;
5389         vsi->current_speed = new_speed;
5390         if (!isup) {
5391                 netdev_info(vsi->netdev, "NIC Link is Down\n");
5392                 return;
5393         }
5394
5395         /* Warn user if link speed on NPAR enabled partition is not at
5396          * least 10GB
5397          */
5398         if (vsi->back->hw.func_caps.npar_enable &&
5399             (vsi->back->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
5400              vsi->back->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
5401                 netdev_warn(vsi->netdev,
5402                             "The partition detected link speed that is less than 10Gbps\n");
5403
5404         switch (vsi->back->hw.phy.link_info.link_speed) {
5405         case I40E_LINK_SPEED_40GB:
5406                 speed = "40 G";
5407                 break;
5408         case I40E_LINK_SPEED_20GB:
5409                 speed = "20 G";
5410                 break;
5411         case I40E_LINK_SPEED_25GB:
5412                 speed = "25 G";
5413                 break;
5414         case I40E_LINK_SPEED_10GB:
5415                 speed = "10 G";
5416                 break;
5417         case I40E_LINK_SPEED_1GB:
5418                 speed = "1000 M";
5419                 break;
5420         case I40E_LINK_SPEED_100MB:
5421                 speed = "100 M";
5422                 break;
5423         default:
5424                 break;
5425         }
5426
5427         switch (vsi->back->hw.fc.current_mode) {
5428         case I40E_FC_FULL:
5429                 fc = "RX/TX";
5430                 break;
5431         case I40E_FC_TX_PAUSE:
5432                 fc = "TX";
5433                 break;
5434         case I40E_FC_RX_PAUSE:
5435                 fc = "RX";
5436                 break;
5437         default:
5438                 fc = "None";
5439                 break;
5440         }
5441
5442         if (vsi->back->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
5443                 req_fec = ", Requested FEC: None";
5444                 fec = ", FEC: None";
5445                 an = ", Autoneg: False";
5446
5447                 if (vsi->back->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
5448                         an = ", Autoneg: True";
5449
5450                 if (vsi->back->hw.phy.link_info.fec_info &
5451                     I40E_AQ_CONFIG_FEC_KR_ENA)
5452                         fec = ", FEC: CL74 FC-FEC/BASE-R";
5453                 else if (vsi->back->hw.phy.link_info.fec_info &
5454                          I40E_AQ_CONFIG_FEC_RS_ENA)
5455                         fec = ", FEC: CL108 RS-FEC";
5456
5457                 /* 'CL108 RS-FEC' should be displayed when RS is requested, or
5458                  * both RS and FC are requested
5459                  */
5460                 if (vsi->back->hw.phy.link_info.req_fec_info &
5461                     (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
5462                         if (vsi->back->hw.phy.link_info.req_fec_info &
5463                             I40E_AQ_REQUEST_FEC_RS)
5464                                 req_fec = ", Requested FEC: CL108 RS-FEC";
5465                         else
5466                                 req_fec = ", Requested FEC: CL74 FC-FEC/BASE-R";
5467                 }
5468         }
5469
5470         netdev_info(vsi->netdev, "NIC Link is Up, %sbps Full Duplex%s%s%s, Flow Control: %s\n",
5471                     speed, req_fec, fec, an, fc);
5472 }
5473
5474 /**
5475  * i40e_up_complete - Finish the last steps of bringing up a connection
5476  * @vsi: the VSI being configured
5477  **/
5478 static int i40e_up_complete(struct i40e_vsi *vsi)
5479 {
5480         struct i40e_pf *pf = vsi->back;
5481         int err;
5482
5483         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
5484                 i40e_vsi_configure_msix(vsi);
5485         else
5486                 i40e_configure_msi_and_legacy(vsi);
5487
5488         /* start rings */
5489         err = i40e_vsi_start_rings(vsi);
5490         if (err)
5491                 return err;
5492
5493         clear_bit(__I40E_VSI_DOWN, vsi->state);
5494         i40e_napi_enable_all(vsi);
5495         i40e_vsi_enable_irq(vsi);
5496
5497         if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
5498             (vsi->netdev)) {
5499                 i40e_print_link_message(vsi, true);
5500                 netif_tx_start_all_queues(vsi->netdev);
5501                 netif_carrier_on(vsi->netdev);
5502         } else if (vsi->netdev) {
5503                 i40e_print_link_message(vsi, false);
5504                 /* need to check for qualified module here*/
5505                 if ((pf->hw.phy.link_info.link_info &
5506                         I40E_AQ_MEDIA_AVAILABLE) &&
5507                     (!(pf->hw.phy.link_info.an_info &
5508                         I40E_AQ_QUALIFIED_MODULE)))
5509                         netdev_err(vsi->netdev,
5510                                    "the driver failed to link because an unqualified module was detected.");
5511         }
5512
5513         /* replay FDIR SB filters */
5514         if (vsi->type == I40E_VSI_FDIR) {
5515                 /* reset fd counters */
5516                 pf->fd_add_err = 0;
5517                 pf->fd_atr_cnt = 0;
5518                 i40e_fdir_filter_restore(vsi);
5519         }
5520
5521         /* On the next run of the service_task, notify any clients of the new
5522          * opened netdev
5523          */
5524         pf->flags |= I40E_FLAG_SERVICE_CLIENT_REQUESTED;
5525         i40e_service_event_schedule(pf);
5526
5527         return 0;
5528 }
5529
5530 /**
5531  * i40e_vsi_reinit_locked - Reset the VSI
5532  * @vsi: the VSI being configured
5533  *
5534  * Rebuild the ring structs after some configuration
5535  * has changed, e.g. MTU size.
5536  **/
5537 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
5538 {
5539         struct i40e_pf *pf = vsi->back;
5540
5541         WARN_ON(in_interrupt());
5542         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
5543                 usleep_range(1000, 2000);
5544         i40e_down(vsi);
5545
5546         i40e_up(vsi);
5547         clear_bit(__I40E_CONFIG_BUSY, pf->state);
5548 }
5549
5550 /**
5551  * i40e_up - Bring the connection back up after being down
5552  * @vsi: the VSI being configured
5553  **/
5554 int i40e_up(struct i40e_vsi *vsi)
5555 {
5556         int err;
5557
5558         err = i40e_vsi_configure(vsi);
5559         if (!err)
5560                 err = i40e_up_complete(vsi);
5561
5562         return err;
5563 }
5564
5565 /**
5566  * i40e_down - Shutdown the connection processing
5567  * @vsi: the VSI being stopped
5568  **/
5569 void i40e_down(struct i40e_vsi *vsi)
5570 {
5571         int i;
5572
5573         /* It is assumed that the caller of this function
5574          * sets the vsi->state __I40E_VSI_DOWN bit.
5575          */
5576         if (vsi->netdev) {
5577                 netif_carrier_off(vsi->netdev);
5578                 netif_tx_disable(vsi->netdev);
5579         }
5580         i40e_vsi_disable_irq(vsi);
5581         i40e_vsi_stop_rings(vsi);
5582         i40e_napi_disable_all(vsi);
5583
5584         for (i = 0; i < vsi->num_queue_pairs; i++) {
5585                 i40e_clean_tx_ring(vsi->tx_rings[i]);
5586                 if (i40e_enabled_xdp_vsi(vsi))
5587                         i40e_clean_tx_ring(vsi->xdp_rings[i]);
5588                 i40e_clean_rx_ring(vsi->rx_rings[i]);
5589         }
5590
5591 }
5592
5593 /**
5594  * i40e_setup_tc - configure multiple traffic classes
5595  * @netdev: net device to configure
5596  * @tc: number of traffic classes to enable
5597  **/
5598 static int i40e_setup_tc(struct net_device *netdev, u8 tc)
5599 {
5600         struct i40e_netdev_priv *np = netdev_priv(netdev);
5601         struct i40e_vsi *vsi = np->vsi;
5602         struct i40e_pf *pf = vsi->back;
5603         u8 enabled_tc = 0;
5604         int ret = -EINVAL;
5605         int i;
5606
5607         /* Check if DCB enabled to continue */
5608         if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5609                 netdev_info(netdev, "DCB is not enabled for adapter\n");
5610                 goto exit;
5611         }
5612
5613         /* Check if MFP enabled */
5614         if (pf->flags & I40E_FLAG_MFP_ENABLED) {
5615                 netdev_info(netdev, "Configuring TC not supported in MFP mode\n");
5616                 goto exit;
5617         }
5618
5619         /* Check whether tc count is within enabled limit */
5620         if (tc > i40e_pf_get_num_tc(pf)) {
5621                 netdev_info(netdev, "TC count greater than enabled on link for adapter\n");
5622                 goto exit;
5623         }
5624
5625         /* Generate TC map for number of tc requested */
5626         for (i = 0; i < tc; i++)
5627                 enabled_tc |= BIT(i);
5628
5629         /* Requesting same TC configuration as already enabled */
5630         if (enabled_tc == vsi->tc_config.enabled_tc)
5631                 return 0;
5632
5633         /* Quiesce VSI queues */
5634         i40e_quiesce_vsi(vsi);
5635
5636         /* Configure VSI for enabled TCs */
5637         ret = i40e_vsi_config_tc(vsi, enabled_tc);
5638         if (ret) {
5639                 netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
5640                             vsi->seid);
5641                 goto exit;
5642         }
5643
5644         /* Unquiesce VSI */
5645         i40e_unquiesce_vsi(vsi);
5646
5647 exit:
5648         return ret;
5649 }
5650
5651 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
5652                            void *type_data)
5653 {
5654         struct tc_mqprio_qopt *mqprio = type_data;
5655
5656         if (type != TC_SETUP_MQPRIO)
5657                 return -EOPNOTSUPP;
5658
5659         mqprio->hw = TC_MQPRIO_HW_OFFLOAD_TCS;
5660
5661         return i40e_setup_tc(netdev, mqprio->num_tc);
5662 }
5663
5664 /**
5665  * i40e_open - Called when a network interface is made active
5666  * @netdev: network interface device structure
5667  *
5668  * The open entry point is called when a network interface is made
5669  * active by the system (IFF_UP).  At this point all resources needed
5670  * for transmit and receive operations are allocated, the interrupt
5671  * handler is registered with the OS, the netdev watchdog subtask is
5672  * enabled, and the stack is notified that the interface is ready.
5673  *
5674  * Returns 0 on success, negative value on failure
5675  **/
5676 int i40e_open(struct net_device *netdev)
5677 {
5678         struct i40e_netdev_priv *np = netdev_priv(netdev);
5679         struct i40e_vsi *vsi = np->vsi;
5680         struct i40e_pf *pf = vsi->back;
5681         int err;
5682
5683         /* disallow open during test or if eeprom is broken */
5684         if (test_bit(__I40E_TESTING, pf->state) ||
5685             test_bit(__I40E_BAD_EEPROM, pf->state))
5686                 return -EBUSY;
5687
5688         netif_carrier_off(netdev);
5689
5690         err = i40e_vsi_open(vsi);
5691         if (err)
5692                 return err;
5693
5694         /* configure global TSO hardware offload settings */
5695         wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
5696                                                        TCP_FLAG_FIN) >> 16);
5697         wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
5698                                                        TCP_FLAG_FIN |
5699                                                        TCP_FLAG_CWR) >> 16);
5700         wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
5701
5702         udp_tunnel_get_rx_info(netdev);
5703
5704         return 0;
5705 }
5706
5707 /**
5708  * i40e_vsi_open -
5709  * @vsi: the VSI to open
5710  *
5711  * Finish initialization of the VSI.
5712  *
5713  * Returns 0 on success, negative value on failure
5714  *
5715  * Note: expects to be called while under rtnl_lock()
5716  **/
5717 int i40e_vsi_open(struct i40e_vsi *vsi)
5718 {
5719         struct i40e_pf *pf = vsi->back;
5720         char int_name[I40E_INT_NAME_STR_LEN];
5721         int err;
5722
5723         /* allocate descriptors */
5724         err = i40e_vsi_setup_tx_resources(vsi);
5725         if (err)
5726                 goto err_setup_tx;
5727         err = i40e_vsi_setup_rx_resources(vsi);
5728         if (err)
5729                 goto err_setup_rx;
5730
5731         err = i40e_vsi_configure(vsi);
5732         if (err)
5733                 goto err_setup_rx;
5734
5735         if (vsi->netdev) {
5736                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
5737                          dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
5738                 err = i40e_vsi_request_irq(vsi, int_name);
5739                 if (err)
5740                         goto err_setup_rx;
5741
5742                 /* Notify the stack of the actual queue counts. */
5743                 err = netif_set_real_num_tx_queues(vsi->netdev,
5744                                                    vsi->num_queue_pairs);
5745                 if (err)
5746                         goto err_set_queues;
5747
5748                 err = netif_set_real_num_rx_queues(vsi->netdev,
5749                                                    vsi->num_queue_pairs);
5750                 if (err)
5751                         goto err_set_queues;
5752
5753         } else if (vsi->type == I40E_VSI_FDIR) {
5754                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
5755                          dev_driver_string(&pf->pdev->dev),
5756                          dev_name(&pf->pdev->dev));
5757                 err = i40e_vsi_request_irq(vsi, int_name);
5758
5759         } else {
5760                 err = -EINVAL;
5761                 goto err_setup_rx;
5762         }
5763
5764         err = i40e_up_complete(vsi);
5765         if (err)
5766                 goto err_up_complete;
5767
5768         return 0;
5769
5770 err_up_complete:
5771         i40e_down(vsi);
5772 err_set_queues:
5773         i40e_vsi_free_irq(vsi);
5774 err_setup_rx:
5775         i40e_vsi_free_rx_resources(vsi);
5776 err_setup_tx:
5777         i40e_vsi_free_tx_resources(vsi);
5778         if (vsi == pf->vsi[pf->lan_vsi])
5779                 i40e_do_reset(pf, BIT_ULL(__I40E_PF_RESET_REQUESTED), true);
5780
5781         return err;
5782 }
5783
5784 /**
5785  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
5786  * @pf: Pointer to PF
5787  *
5788  * This function destroys the hlist where all the Flow Director
5789  * filters were saved.
5790  **/
5791 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
5792 {
5793         struct i40e_fdir_filter *filter;
5794         struct i40e_flex_pit *pit_entry, *tmp;
5795         struct hlist_node *node2;
5796
5797         hlist_for_each_entry_safe(filter, node2,
5798                                   &pf->fdir_filter_list, fdir_node) {
5799                 hlist_del(&filter->fdir_node);
5800                 kfree(filter);
5801         }
5802
5803         list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
5804                 list_del(&pit_entry->list);
5805                 kfree(pit_entry);
5806         }
5807         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
5808
5809         list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
5810                 list_del(&pit_entry->list);
5811                 kfree(pit_entry);
5812         }
5813         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
5814
5815         pf->fdir_pf_active_filters = 0;
5816         pf->fd_tcp4_filter_cnt = 0;
5817         pf->fd_udp4_filter_cnt = 0;
5818         pf->fd_sctp4_filter_cnt = 0;
5819         pf->fd_ip4_filter_cnt = 0;
5820
5821         /* Reprogram the default input set for TCP/IPv4 */
5822         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
5823                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
5824                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
5825
5826         /* Reprogram the default input set for UDP/IPv4 */
5827         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
5828                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
5829                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
5830
5831         /* Reprogram the default input set for SCTP/IPv4 */
5832         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
5833                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
5834                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
5835
5836         /* Reprogram the default input set for Other/IPv4 */
5837         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
5838                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
5839
5840         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
5841                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
5842 }
5843
5844 /**
5845  * i40e_close - Disables a network interface
5846  * @netdev: network interface device structure
5847  *
5848  * The close entry point is called when an interface is de-activated
5849  * by the OS.  The hardware is still under the driver's control, but
5850  * this netdev interface is disabled.
5851  *
5852  * Returns 0, this is not allowed to fail
5853  **/
5854 int i40e_close(struct net_device *netdev)
5855 {
5856         struct i40e_netdev_priv *np = netdev_priv(netdev);
5857         struct i40e_vsi *vsi = np->vsi;
5858
5859         i40e_vsi_close(vsi);
5860
5861         return 0;
5862 }
5863
5864 /**
5865  * i40e_do_reset - Start a PF or Core Reset sequence
5866  * @pf: board private structure
5867  * @reset_flags: which reset is requested
5868  * @lock_acquired: indicates whether or not the lock has been acquired
5869  * before this function was called.
5870  *
5871  * The essential difference in resets is that the PF Reset
5872  * doesn't clear the packet buffers, doesn't reset the PE
5873  * firmware, and doesn't bother the other PFs on the chip.
5874  **/
5875 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
5876 {
5877         u32 val;
5878
5879         WARN_ON(in_interrupt());
5880
5881
5882         /* do the biggest reset indicated */
5883         if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
5884
5885                 /* Request a Global Reset
5886                  *
5887                  * This will start the chip's countdown to the actual full
5888                  * chip reset event, and a warning interrupt to be sent
5889                  * to all PFs, including the requestor.  Our handler
5890                  * for the warning interrupt will deal with the shutdown
5891                  * and recovery of the switch setup.
5892                  */
5893                 dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
5894                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
5895                 val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
5896                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
5897
5898         } else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
5899
5900                 /* Request a Core Reset
5901                  *
5902                  * Same as Global Reset, except does *not* include the MAC/PHY
5903                  */
5904                 dev_dbg(&pf->pdev->dev, "CoreR requested\n");
5905                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
5906                 val |= I40E_GLGEN_RTRIG_CORER_MASK;
5907                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
5908                 i40e_flush(&pf->hw);
5909
5910         } else if (reset_flags & BIT_ULL(__I40E_PF_RESET_REQUESTED)) {
5911
5912                 /* Request a PF Reset
5913                  *
5914                  * Resets only the PF-specific registers
5915                  *
5916                  * This goes directly to the tear-down and rebuild of
5917                  * the switch, since we need to do all the recovery as
5918                  * for the Core Reset.
5919                  */
5920                 dev_dbg(&pf->pdev->dev, "PFR requested\n");
5921                 i40e_handle_reset_warning(pf, lock_acquired);
5922
5923         } else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
5924                 int v;
5925
5926                 /* Find the VSI(s) that requested a re-init */
5927                 dev_info(&pf->pdev->dev,
5928                          "VSI reinit requested\n");
5929                 for (v = 0; v < pf->num_alloc_vsi; v++) {
5930                         struct i40e_vsi *vsi = pf->vsi[v];
5931
5932                         if (vsi != NULL &&
5933                             test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
5934                                                vsi->state))
5935                                 i40e_vsi_reinit_locked(pf->vsi[v]);
5936                 }
5937         } else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
5938                 int v;
5939
5940                 /* Find the VSI(s) that needs to be brought down */
5941                 dev_info(&pf->pdev->dev, "VSI down requested\n");
5942                 for (v = 0; v < pf->num_alloc_vsi; v++) {
5943                         struct i40e_vsi *vsi = pf->vsi[v];
5944
5945                         if (vsi != NULL &&
5946                             test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
5947                                                vsi->state)) {
5948                                 set_bit(__I40E_VSI_DOWN, vsi->state);
5949                                 i40e_down(vsi);
5950                         }
5951                 }
5952         } else {
5953                 dev_info(&pf->pdev->dev,
5954                          "bad reset request 0x%08x\n", reset_flags);
5955         }
5956 }
5957
5958 #ifdef CONFIG_I40E_DCB
5959 /**
5960  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
5961  * @pf: board private structure
5962  * @old_cfg: current DCB config
5963  * @new_cfg: new DCB config
5964  **/
5965 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
5966                             struct i40e_dcbx_config *old_cfg,
5967                             struct i40e_dcbx_config *new_cfg)
5968 {
5969         bool need_reconfig = false;
5970
5971         /* Check if ETS configuration has changed */
5972         if (memcmp(&new_cfg->etscfg,
5973                    &old_cfg->etscfg,
5974                    sizeof(new_cfg->etscfg))) {
5975                 /* If Priority Table has changed reconfig is needed */
5976                 if (memcmp(&new_cfg->etscfg.prioritytable,
5977                            &old_cfg->etscfg.prioritytable,
5978                            sizeof(new_cfg->etscfg.prioritytable))) {
5979                         need_reconfig = true;
5980                         dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
5981                 }
5982
5983                 if (memcmp(&new_cfg->etscfg.tcbwtable,
5984                            &old_cfg->etscfg.tcbwtable,
5985                            sizeof(new_cfg->etscfg.tcbwtable)))
5986                         dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
5987
5988                 if (memcmp(&new_cfg->etscfg.tsatable,
5989                            &old_cfg->etscfg.tsatable,
5990                            sizeof(new_cfg->etscfg.tsatable)))
5991                         dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
5992         }
5993
5994         /* Check if PFC configuration has changed */
5995         if (memcmp(&new_cfg->pfc,
5996                    &old_cfg->pfc,
5997                    sizeof(new_cfg->pfc))) {
5998                 need_reconfig = true;
5999                 dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
6000         }
6001
6002         /* Check if APP Table has changed */
6003         if (memcmp(&new_cfg->app,
6004                    &old_cfg->app,
6005                    sizeof(new_cfg->app))) {
6006                 need_reconfig = true;
6007                 dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
6008         }
6009
6010         dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
6011         return need_reconfig;
6012 }
6013
6014 /**
6015  * i40e_handle_lldp_event - Handle LLDP Change MIB event
6016  * @pf: board private structure
6017  * @e: event info posted on ARQ
6018  **/
6019 static int i40e_handle_lldp_event(struct i40e_pf *pf,
6020                                   struct i40e_arq_event_info *e)
6021 {
6022         struct i40e_aqc_lldp_get_mib *mib =
6023                 (struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
6024         struct i40e_hw *hw = &pf->hw;
6025         struct i40e_dcbx_config tmp_dcbx_cfg;
6026         bool need_reconfig = false;
6027         int ret = 0;
6028         u8 type;
6029
6030         /* Not DCB capable or capability disabled */
6031         if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
6032                 return ret;
6033
6034         /* Ignore if event is not for Nearest Bridge */
6035         type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
6036                 & I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
6037         dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
6038         if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
6039                 return ret;
6040
6041         /* Check MIB Type and return if event for Remote MIB update */
6042         type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
6043         dev_dbg(&pf->pdev->dev,
6044                 "LLDP event mib type %s\n", type ? "remote" : "local");
6045         if (type == I40E_AQ_LLDP_MIB_REMOTE) {
6046                 /* Update the remote cached instance and return */
6047                 ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
6048                                 I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
6049                                 &hw->remote_dcbx_config);
6050                 goto exit;
6051         }
6052
6053         /* Store the old configuration */
6054         tmp_dcbx_cfg = hw->local_dcbx_config;
6055
6056         /* Reset the old DCBx configuration data */
6057         memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
6058         /* Get updated DCBX data from firmware */
6059         ret = i40e_get_dcb_config(&pf->hw);
6060         if (ret) {
6061                 dev_info(&pf->pdev->dev,
6062                          "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
6063                          i40e_stat_str(&pf->hw, ret),
6064                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6065                 goto exit;
6066         }
6067
6068         /* No change detected in DCBX configs */
6069         if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
6070                     sizeof(tmp_dcbx_cfg))) {
6071                 dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
6072                 goto exit;
6073         }
6074
6075         need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
6076                                                &hw->local_dcbx_config);
6077
6078         i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
6079
6080         if (!need_reconfig)
6081                 goto exit;
6082
6083         /* Enable DCB tagging only when more than one TC */
6084         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
6085                 pf->flags |= I40E_FLAG_DCB_ENABLED;
6086         else
6087                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6088
6089         set_bit(__I40E_PORT_SUSPENDED, pf->state);
6090         /* Reconfiguration needed quiesce all VSIs */
6091         i40e_pf_quiesce_all_vsi(pf);
6092
6093         /* Changes in configuration update VEB/VSI */
6094         i40e_dcb_reconfigure(pf);
6095
6096         ret = i40e_resume_port_tx(pf);
6097
6098         clear_bit(__I40E_PORT_SUSPENDED, pf->state);
6099         /* In case of error no point in resuming VSIs */
6100         if (ret)
6101                 goto exit;
6102
6103         /* Wait for the PF's queues to be disabled */
6104         ret = i40e_pf_wait_queues_disabled(pf);
6105         if (ret) {
6106                 /* Schedule PF reset to recover */
6107                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6108                 i40e_service_event_schedule(pf);
6109         } else {
6110                 i40e_pf_unquiesce_all_vsi(pf);
6111         pf->flags |= (I40E_FLAG_SERVICE_CLIENT_REQUESTED |
6112                       I40E_FLAG_CLIENT_L2_CHANGE);
6113         }
6114
6115 exit:
6116         return ret;
6117 }
6118 #endif /* CONFIG_I40E_DCB */
6119
6120 /**
6121  * i40e_do_reset_safe - Protected reset path for userland calls.
6122  * @pf: board private structure
6123  * @reset_flags: which reset is requested
6124  *
6125  **/
6126 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
6127 {
6128         rtnl_lock();
6129         i40e_do_reset(pf, reset_flags, true);
6130         rtnl_unlock();
6131 }
6132
6133 /**
6134  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
6135  * @pf: board private structure
6136  * @e: event info posted on ARQ
6137  *
6138  * Handler for LAN Queue Overflow Event generated by the firmware for PF
6139  * and VF queues
6140  **/
6141 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
6142                                            struct i40e_arq_event_info *e)
6143 {
6144         struct i40e_aqc_lan_overflow *data =
6145                 (struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
6146         u32 queue = le32_to_cpu(data->prtdcb_rupto);
6147         u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
6148         struct i40e_hw *hw = &pf->hw;
6149         struct i40e_vf *vf;
6150         u16 vf_id;
6151
6152         dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
6153                 queue, qtx_ctl);
6154
6155         /* Queue belongs to VF, find the VF and issue VF reset */
6156         if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
6157             >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
6158                 vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
6159                          >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
6160                 vf_id -= hw->func_caps.vf_base_id;
6161                 vf = &pf->vf[vf_id];
6162                 i40e_vc_notify_vf_reset(vf);
6163                 /* Allow VF to process pending reset notification */
6164                 msleep(20);
6165                 i40e_reset_vf(vf, false);
6166         }
6167 }
6168
6169 /**
6170  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
6171  * @pf: board private structure
6172  **/
6173 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
6174 {
6175         u32 val, fcnt_prog;
6176
6177         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
6178         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
6179         return fcnt_prog;
6180 }
6181
6182 /**
6183  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
6184  * @pf: board private structure
6185  **/
6186 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
6187 {
6188         u32 val, fcnt_prog;
6189
6190         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
6191         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
6192                     ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
6193                       I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
6194         return fcnt_prog;
6195 }
6196
6197 /**
6198  * i40e_get_global_fd_count - Get total FD filters programmed on device
6199  * @pf: board private structure
6200  **/
6201 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
6202 {
6203         u32 val, fcnt_prog;
6204
6205         val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
6206         fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
6207                     ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
6208                      I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
6209         return fcnt_prog;
6210 }
6211
6212 /**
6213  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
6214  * @pf: board private structure
6215  **/
6216 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
6217 {
6218         struct i40e_fdir_filter *filter;
6219         u32 fcnt_prog, fcnt_avail;
6220         struct hlist_node *node;
6221
6222         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
6223                 return;
6224
6225         /* Check if we have enough room to re-enable FDir SB capability. */
6226         fcnt_prog = i40e_get_global_fd_count(pf);
6227         fcnt_avail = pf->fdir_pf_filter_count;
6228         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
6229             (pf->fd_add_err == 0) ||
6230             (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt)) {
6231                 if (pf->flags & I40E_FLAG_FD_SB_AUTO_DISABLED) {
6232                         pf->flags &= ~I40E_FLAG_FD_SB_AUTO_DISABLED;
6233                         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
6234                             (I40E_DEBUG_FD & pf->hw.debug_mask))
6235                                 dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
6236                 }
6237         }
6238
6239         /* We should wait for even more space before re-enabling ATR.
6240          * Additionally, we cannot enable ATR as long as we still have TCP SB
6241          * rules active.
6242          */
6243         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
6244             (pf->fd_tcp4_filter_cnt == 0)) {
6245                 if (pf->flags & I40E_FLAG_FD_ATR_AUTO_DISABLED) {
6246                         pf->flags &= ~I40E_FLAG_FD_ATR_AUTO_DISABLED;
6247                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
6248                             (I40E_DEBUG_FD & pf->hw.debug_mask))
6249                                 dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
6250                 }
6251         }
6252
6253         /* if hw had a problem adding a filter, delete it */
6254         if (pf->fd_inv > 0) {
6255                 hlist_for_each_entry_safe(filter, node,
6256                                           &pf->fdir_filter_list, fdir_node) {
6257                         if (filter->fd_id == pf->fd_inv) {
6258                                 hlist_del(&filter->fdir_node);
6259                                 kfree(filter);
6260                                 pf->fdir_pf_active_filters--;
6261                         }
6262                 }
6263         }
6264 }
6265
6266 #define I40E_MIN_FD_FLUSH_INTERVAL 10
6267 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
6268 /**
6269  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
6270  * @pf: board private structure
6271  **/
6272 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
6273 {
6274         unsigned long min_flush_time;
6275         int flush_wait_retry = 50;
6276         bool disable_atr = false;
6277         int fd_room;
6278         int reg;
6279
6280         if (!time_after(jiffies, pf->fd_flush_timestamp +
6281                                  (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
6282                 return;
6283
6284         /* If the flush is happening too quick and we have mostly SB rules we
6285          * should not re-enable ATR for some time.
6286          */
6287         min_flush_time = pf->fd_flush_timestamp +
6288                          (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
6289         fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
6290
6291         if (!(time_after(jiffies, min_flush_time)) &&
6292             (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
6293                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
6294                         dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
6295                 disable_atr = true;
6296         }
6297
6298         pf->fd_flush_timestamp = jiffies;
6299         pf->flags |= I40E_FLAG_FD_ATR_AUTO_DISABLED;
6300         /* flush all filters */
6301         wr32(&pf->hw, I40E_PFQF_CTL_1,
6302              I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
6303         i40e_flush(&pf->hw);
6304         pf->fd_flush_cnt++;
6305         pf->fd_add_err = 0;
6306         do {
6307                 /* Check FD flush status every 5-6msec */
6308                 usleep_range(5000, 6000);
6309                 reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
6310                 if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
6311                         break;
6312         } while (flush_wait_retry--);
6313         if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
6314                 dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
6315         } else {
6316                 /* replay sideband filters */
6317                 i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
6318                 if (!disable_atr && !pf->fd_tcp4_filter_cnt)
6319                         pf->flags &= ~I40E_FLAG_FD_ATR_AUTO_DISABLED;
6320                 clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
6321                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
6322                         dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
6323         }
6324 }
6325
6326 /**
6327  * i40e_get_current_atr_count - Get the count of total FD ATR filters programmed
6328  * @pf: board private structure
6329  **/
6330 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
6331 {
6332         return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
6333 }
6334
6335 /* We can see up to 256 filter programming desc in transit if the filters are
6336  * being applied really fast; before we see the first
6337  * filter miss error on Rx queue 0. Accumulating enough error messages before
6338  * reacting will make sure we don't cause flush too often.
6339  */
6340 #define I40E_MAX_FD_PROGRAM_ERROR 256
6341
6342 /**
6343  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
6344  * @pf: board private structure
6345  **/
6346 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
6347 {
6348
6349         /* if interface is down do nothing */
6350         if (test_bit(__I40E_DOWN, pf->state))
6351                 return;
6352
6353         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
6354                 i40e_fdir_flush_and_replay(pf);
6355
6356         i40e_fdir_check_and_reenable(pf);
6357
6358 }
6359
6360 /**
6361  * i40e_vsi_link_event - notify VSI of a link event
6362  * @vsi: vsi to be notified
6363  * @link_up: link up or down
6364  **/
6365 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
6366 {
6367         if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
6368                 return;
6369
6370         switch (vsi->type) {
6371         case I40E_VSI_MAIN:
6372                 if (!vsi->netdev || !vsi->netdev_registered)
6373                         break;
6374
6375                 if (link_up) {
6376                         netif_carrier_on(vsi->netdev);
6377                         netif_tx_wake_all_queues(vsi->netdev);
6378                 } else {
6379                         netif_carrier_off(vsi->netdev);
6380                         netif_tx_stop_all_queues(vsi->netdev);
6381                 }
6382                 break;
6383
6384         case I40E_VSI_SRIOV:
6385         case I40E_VSI_VMDQ2:
6386         case I40E_VSI_CTRL:
6387         case I40E_VSI_IWARP:
6388         case I40E_VSI_MIRROR:
6389         default:
6390                 /* there is no notification for other VSIs */
6391                 break;
6392         }
6393 }
6394
6395 /**
6396  * i40e_veb_link_event - notify elements on the veb of a link event
6397  * @veb: veb to be notified
6398  * @link_up: link up or down
6399  **/
6400 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
6401 {
6402         struct i40e_pf *pf;
6403         int i;
6404
6405         if (!veb || !veb->pf)
6406                 return;
6407         pf = veb->pf;
6408
6409         /* depth first... */
6410         for (i = 0; i < I40E_MAX_VEB; i++)
6411                 if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
6412                         i40e_veb_link_event(pf->veb[i], link_up);
6413
6414         /* ... now the local VSIs */
6415         for (i = 0; i < pf->num_alloc_vsi; i++)
6416                 if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
6417                         i40e_vsi_link_event(pf->vsi[i], link_up);
6418 }
6419
6420 /**
6421  * i40e_link_event - Update netif_carrier status
6422  * @pf: board private structure
6423  **/
6424 static void i40e_link_event(struct i40e_pf *pf)
6425 {
6426         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
6427         u8 new_link_speed, old_link_speed;
6428         i40e_status status;
6429         bool new_link, old_link;
6430
6431         /* save off old link status information */
6432         pf->hw.phy.link_info_old = pf->hw.phy.link_info;
6433
6434         /* set this to force the get_link_status call to refresh state */
6435         pf->hw.phy.get_link_info = true;
6436
6437         old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
6438
6439         status = i40e_get_link_status(&pf->hw, &new_link);
6440
6441         /* On success, disable temp link polling */
6442         if (status == I40E_SUCCESS) {
6443                 if (pf->flags & I40E_FLAG_TEMP_LINK_POLLING)
6444                         pf->flags &= ~I40E_FLAG_TEMP_LINK_POLLING;
6445         } else {
6446                 /* Enable link polling temporarily until i40e_get_link_status
6447                  * returns I40E_SUCCESS
6448                  */
6449                 pf->flags |= I40E_FLAG_TEMP_LINK_POLLING;
6450                 dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
6451                         status);
6452                 return;
6453         }
6454
6455         old_link_speed = pf->hw.phy.link_info_old.link_speed;
6456         new_link_speed = pf->hw.phy.link_info.link_speed;
6457
6458         if (new_link == old_link &&
6459             new_link_speed == old_link_speed &&
6460             (test_bit(__I40E_VSI_DOWN, vsi->state) ||
6461              new_link == netif_carrier_ok(vsi->netdev)))
6462                 return;
6463
6464         if (!test_bit(__I40E_VSI_DOWN, vsi->state))
6465                 i40e_print_link_message(vsi, new_link);
6466
6467         /* Notify the base of the switch tree connected to
6468          * the link.  Floating VEBs are not notified.
6469          */
6470         if (pf->lan_veb != I40E_NO_VEB && pf->veb[pf->lan_veb])
6471                 i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
6472         else
6473                 i40e_vsi_link_event(vsi, new_link);
6474
6475         if (pf->vf)
6476                 i40e_vc_notify_link_state(pf);
6477
6478         if (pf->flags & I40E_FLAG_PTP)
6479                 i40e_ptp_set_increment(pf);
6480 }
6481
6482 /**
6483  * i40e_watchdog_subtask - periodic checks not using event driven response
6484  * @pf: board private structure
6485  **/
6486 static void i40e_watchdog_subtask(struct i40e_pf *pf)
6487 {
6488         int i;
6489
6490         /* if interface is down do nothing */
6491         if (test_bit(__I40E_DOWN, pf->state) ||
6492             test_bit(__I40E_CONFIG_BUSY, pf->state))
6493                 return;
6494
6495         /* make sure we don't do these things too often */
6496         if (time_before(jiffies, (pf->service_timer_previous +
6497                                   pf->service_timer_period)))
6498                 return;
6499         pf->service_timer_previous = jiffies;
6500
6501         if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
6502             (pf->flags & I40E_FLAG_TEMP_LINK_POLLING))
6503                 i40e_link_event(pf);
6504
6505         /* Update the stats for active netdevs so the network stack
6506          * can look at updated numbers whenever it cares to
6507          */
6508         for (i = 0; i < pf->num_alloc_vsi; i++)
6509                 if (pf->vsi[i] && pf->vsi[i]->netdev)
6510                         i40e_update_stats(pf->vsi[i]);
6511
6512         if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
6513                 /* Update the stats for the active switching components */
6514                 for (i = 0; i < I40E_MAX_VEB; i++)
6515                         if (pf->veb[i])
6516                                 i40e_update_veb_stats(pf->veb[i]);
6517         }
6518
6519         i40e_ptp_rx_hang(pf);
6520         i40e_ptp_tx_hang(pf);
6521 }
6522
6523 /**
6524  * i40e_reset_subtask - Set up for resetting the device and driver
6525  * @pf: board private structure
6526  **/
6527 static void i40e_reset_subtask(struct i40e_pf *pf)
6528 {
6529         u32 reset_flags = 0;
6530
6531         if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
6532                 reset_flags |= BIT(__I40E_REINIT_REQUESTED);
6533                 clear_bit(__I40E_REINIT_REQUESTED, pf->state);
6534         }
6535         if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
6536                 reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
6537                 clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6538         }
6539         if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
6540                 reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
6541                 clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
6542         }
6543         if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
6544                 reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
6545                 clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
6546         }
6547         if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
6548                 reset_flags |= BIT(__I40E_DOWN_REQUESTED);
6549                 clear_bit(__I40E_DOWN_REQUESTED, pf->state);
6550         }
6551
6552         /* If there's a recovery already waiting, it takes
6553          * precedence before starting a new reset sequence.
6554          */
6555         if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
6556                 i40e_prep_for_reset(pf, false);
6557                 i40e_reset(pf);
6558                 i40e_rebuild(pf, false, false);
6559         }
6560
6561         /* If we're already down or resetting, just bail */
6562         if (reset_flags &&
6563             !test_bit(__I40E_DOWN, pf->state) &&
6564             !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
6565                 i40e_do_reset(pf, reset_flags, false);
6566         }
6567 }
6568
6569 /**
6570  * i40e_handle_link_event - Handle link event
6571  * @pf: board private structure
6572  * @e: event info posted on ARQ
6573  **/
6574 static void i40e_handle_link_event(struct i40e_pf *pf,
6575                                    struct i40e_arq_event_info *e)
6576 {
6577         struct i40e_aqc_get_link_status *status =
6578                 (struct i40e_aqc_get_link_status *)&e->desc.params.raw;
6579
6580         /* Do a new status request to re-enable LSE reporting
6581          * and load new status information into the hw struct
6582          * This completely ignores any state information
6583          * in the ARQ event info, instead choosing to always
6584          * issue the AQ update link status command.
6585          */
6586         i40e_link_event(pf);
6587
6588         /* check for unqualified module, if link is down */
6589         if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
6590             (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
6591             (!(status->link_info & I40E_AQ_LINK_UP)))
6592                 dev_err(&pf->pdev->dev,
6593                         "The driver failed to link because an unqualified module was detected.\n");
6594 }
6595
6596 /**
6597  * i40e_clean_adminq_subtask - Clean the AdminQ rings
6598  * @pf: board private structure
6599  **/
6600 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
6601 {
6602         struct i40e_arq_event_info event;
6603         struct i40e_hw *hw = &pf->hw;
6604         u16 pending, i = 0;
6605         i40e_status ret;
6606         u16 opcode;
6607         u32 oldval;
6608         u32 val;
6609
6610         /* Do not run clean AQ when PF reset fails */
6611         if (test_bit(__I40E_RESET_FAILED, pf->state))
6612                 return;
6613
6614         /* check for error indications */
6615         val = rd32(&pf->hw, pf->hw.aq.arq.len);
6616         oldval = val;
6617         if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
6618                 if (hw->debug_mask & I40E_DEBUG_AQ)
6619                         dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
6620                 val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
6621         }
6622         if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
6623                 if (hw->debug_mask & I40E_DEBUG_AQ)
6624                         dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
6625                 val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
6626                 pf->arq_overflows++;
6627         }
6628         if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
6629                 if (hw->debug_mask & I40E_DEBUG_AQ)
6630                         dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
6631                 val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
6632         }
6633         if (oldval != val)
6634                 wr32(&pf->hw, pf->hw.aq.arq.len, val);
6635
6636         val = rd32(&pf->hw, pf->hw.aq.asq.len);
6637         oldval = val;
6638         if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
6639                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
6640                         dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
6641                 val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
6642         }
6643         if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
6644                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
6645                         dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
6646                 val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
6647         }
6648         if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
6649                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
6650                         dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
6651                 val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
6652         }
6653         if (oldval != val)
6654                 wr32(&pf->hw, pf->hw.aq.asq.len, val);
6655
6656         event.buf_len = I40E_MAX_AQ_BUF_SIZE;
6657         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
6658         if (!event.msg_buf)
6659                 return;
6660
6661         do {
6662                 ret = i40e_clean_arq_element(hw, &event, &pending);
6663                 if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
6664                         break;
6665                 else if (ret) {
6666                         dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
6667                         break;
6668                 }
6669
6670                 opcode = le16_to_cpu(event.desc.opcode);
6671                 switch (opcode) {
6672
6673                 case i40e_aqc_opc_get_link_status:
6674                         i40e_handle_link_event(pf, &event);
6675                         break;
6676                 case i40e_aqc_opc_send_msg_to_pf:
6677                         ret = i40e_vc_process_vf_msg(pf,
6678                                         le16_to_cpu(event.desc.retval),
6679                                         le32_to_cpu(event.desc.cookie_high),
6680                                         le32_to_cpu(event.desc.cookie_low),
6681                                         event.msg_buf,
6682                                         event.msg_len);
6683                         break;
6684                 case i40e_aqc_opc_lldp_update_mib:
6685                         dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
6686 #ifdef CONFIG_I40E_DCB
6687                         rtnl_lock();
6688                         ret = i40e_handle_lldp_event(pf, &event);
6689                         rtnl_unlock();
6690 #endif /* CONFIG_I40E_DCB */
6691                         break;
6692                 case i40e_aqc_opc_event_lan_overflow:
6693                         dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
6694                         i40e_handle_lan_overflow_event(pf, &event);
6695                         break;
6696                 case i40e_aqc_opc_send_msg_to_peer:
6697                         dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
6698                         break;
6699                 case i40e_aqc_opc_nvm_erase:
6700                 case i40e_aqc_opc_nvm_update:
6701                 case i40e_aqc_opc_oem_post_update:
6702                         i40e_debug(&pf->hw, I40E_DEBUG_NVM,
6703                                    "ARQ NVM operation 0x%04x completed\n",
6704                                    opcode);
6705                         break;
6706                 default:
6707                         dev_info(&pf->pdev->dev,
6708                                  "ARQ: Unknown event 0x%04x ignored\n",
6709                                  opcode);
6710                         break;
6711                 }
6712         } while (i++ < pf->adminq_work_limit);
6713
6714         if (i < pf->adminq_work_limit)
6715                 clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
6716
6717         /* re-enable Admin queue interrupt cause */
6718         val = rd32(hw, I40E_PFINT_ICR0_ENA);
6719         val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
6720         wr32(hw, I40E_PFINT_ICR0_ENA, val);
6721         i40e_flush(hw);
6722
6723         kfree(event.msg_buf);
6724 }
6725
6726 /**
6727  * i40e_verify_eeprom - make sure eeprom is good to use
6728  * @pf: board private structure
6729  **/
6730 static void i40e_verify_eeprom(struct i40e_pf *pf)
6731 {
6732         int err;
6733
6734         err = i40e_diag_eeprom_test(&pf->hw);
6735         if (err) {
6736                 /* retry in case of garbage read */
6737                 err = i40e_diag_eeprom_test(&pf->hw);
6738                 if (err) {
6739                         dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
6740                                  err);
6741                         set_bit(__I40E_BAD_EEPROM, pf->state);
6742                 }
6743         }
6744
6745         if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
6746                 dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
6747                 clear_bit(__I40E_BAD_EEPROM, pf->state);
6748         }
6749 }
6750
6751 /**
6752  * i40e_enable_pf_switch_lb
6753  * @pf: pointer to the PF structure
6754  *
6755  * enable switch loop back or die - no point in a return value
6756  **/
6757 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
6758 {
6759         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
6760         struct i40e_vsi_context ctxt;
6761         int ret;
6762
6763         ctxt.seid = pf->main_vsi_seid;
6764         ctxt.pf_num = pf->hw.pf_id;
6765         ctxt.vf_num = 0;
6766         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
6767         if (ret) {
6768                 dev_info(&pf->pdev->dev,
6769                          "couldn't get PF vsi config, err %s aq_err %s\n",
6770                          i40e_stat_str(&pf->hw, ret),
6771                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6772                 return;
6773         }
6774         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
6775         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6776         ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6777
6778         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
6779         if (ret) {
6780                 dev_info(&pf->pdev->dev,
6781                          "update vsi switch failed, err %s aq_err %s\n",
6782                          i40e_stat_str(&pf->hw, ret),
6783                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6784         }
6785 }
6786
6787 /**
6788  * i40e_disable_pf_switch_lb
6789  * @pf: pointer to the PF structure
6790  *
6791  * disable switch loop back or die - no point in a return value
6792  **/
6793 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
6794 {
6795         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
6796         struct i40e_vsi_context ctxt;
6797         int ret;
6798
6799         ctxt.seid = pf->main_vsi_seid;
6800         ctxt.pf_num = pf->hw.pf_id;
6801         ctxt.vf_num = 0;
6802         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
6803         if (ret) {
6804                 dev_info(&pf->pdev->dev,
6805                          "couldn't get PF vsi config, err %s aq_err %s\n",
6806                          i40e_stat_str(&pf->hw, ret),
6807                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6808                 return;
6809         }
6810         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
6811         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6812         ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6813
6814         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
6815         if (ret) {
6816                 dev_info(&pf->pdev->dev,
6817                          "update vsi switch failed, err %s aq_err %s\n",
6818                          i40e_stat_str(&pf->hw, ret),
6819                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6820         }
6821 }
6822
6823 /**
6824  * i40e_config_bridge_mode - Configure the HW bridge mode
6825  * @veb: pointer to the bridge instance
6826  *
6827  * Configure the loop back mode for the LAN VSI that is downlink to the
6828  * specified HW bridge instance. It is expected this function is called
6829  * when a new HW bridge is instantiated.
6830  **/
6831 static void i40e_config_bridge_mode(struct i40e_veb *veb)
6832 {
6833         struct i40e_pf *pf = veb->pf;
6834
6835         if (pf->hw.debug_mask & I40E_DEBUG_LAN)
6836                 dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
6837                          veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
6838         if (veb->bridge_mode & BRIDGE_MODE_VEPA)
6839                 i40e_disable_pf_switch_lb(pf);
6840         else
6841                 i40e_enable_pf_switch_lb(pf);
6842 }
6843
6844 /**
6845  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
6846  * @veb: pointer to the VEB instance
6847  *
6848  * This is a recursive function that first builds the attached VSIs then
6849  * recurses in to build the next layer of VEB.  We track the connections
6850  * through our own index numbers because the seid's from the HW could
6851  * change across the reset.
6852  **/
6853 static int i40e_reconstitute_veb(struct i40e_veb *veb)
6854 {
6855         struct i40e_vsi *ctl_vsi = NULL;
6856         struct i40e_pf *pf = veb->pf;
6857         int v, veb_idx;
6858         int ret;
6859
6860         /* build VSI that owns this VEB, temporarily attached to base VEB */
6861         for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
6862                 if (pf->vsi[v] &&
6863                     pf->vsi[v]->veb_idx == veb->idx &&
6864                     pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
6865                         ctl_vsi = pf->vsi[v];
6866                         break;
6867                 }
6868         }
6869         if (!ctl_vsi) {
6870                 dev_info(&pf->pdev->dev,
6871                          "missing owner VSI for veb_idx %d\n", veb->idx);
6872                 ret = -ENOENT;
6873                 goto end_reconstitute;
6874         }
6875         if (ctl_vsi != pf->vsi[pf->lan_vsi])
6876                 ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6877         ret = i40e_add_vsi(ctl_vsi);
6878         if (ret) {
6879                 dev_info(&pf->pdev->dev,
6880                          "rebuild of veb_idx %d owner VSI failed: %d\n",
6881                          veb->idx, ret);
6882                 goto end_reconstitute;
6883         }
6884         i40e_vsi_reset_stats(ctl_vsi);
6885
6886         /* create the VEB in the switch and move the VSI onto the VEB */
6887         ret = i40e_add_veb(veb, ctl_vsi);
6888         if (ret)
6889                 goto end_reconstitute;
6890
6891         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
6892                 veb->bridge_mode = BRIDGE_MODE_VEB;
6893         else
6894                 veb->bridge_mode = BRIDGE_MODE_VEPA;
6895         i40e_config_bridge_mode(veb);
6896
6897         /* create the remaining VSIs attached to this VEB */
6898         for (v = 0; v < pf->num_alloc_vsi; v++) {
6899                 if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
6900                         continue;
6901
6902                 if (pf->vsi[v]->veb_idx == veb->idx) {
6903                         struct i40e_vsi *vsi = pf->vsi[v];
6904
6905                         vsi->uplink_seid = veb->seid;
6906                         ret = i40e_add_vsi(vsi);
6907                         if (ret) {
6908                                 dev_info(&pf->pdev->dev,
6909                                          "rebuild of vsi_idx %d failed: %d\n",
6910                                          v, ret);
6911                                 goto end_reconstitute;
6912                         }
6913                         i40e_vsi_reset_stats(vsi);
6914                 }
6915         }
6916
6917         /* create any VEBs attached to this VEB - RECURSION */
6918         for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
6919                 if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
6920                         pf->veb[veb_idx]->uplink_seid = veb->seid;
6921                         ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
6922                         if (ret)
6923                                 break;
6924                 }
6925         }
6926
6927 end_reconstitute:
6928         return ret;
6929 }
6930
6931 /**
6932  * i40e_get_capabilities - get info about the HW
6933  * @pf: the PF struct
6934  **/
6935 static int i40e_get_capabilities(struct i40e_pf *pf)
6936 {
6937         struct i40e_aqc_list_capabilities_element_resp *cap_buf;
6938         u16 data_size;
6939         int buf_len;
6940         int err;
6941
6942         buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
6943         do {
6944                 cap_buf = kzalloc(buf_len, GFP_KERNEL);
6945                 if (!cap_buf)
6946                         return -ENOMEM;
6947
6948                 /* this loads the data into the hw struct for us */
6949                 err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
6950                                             &data_size,
6951                                             i40e_aqc_opc_list_func_capabilities,
6952                                             NULL);
6953                 /* data loaded, buffer no longer needed */
6954                 kfree(cap_buf);
6955
6956                 if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
6957                         /* retry with a larger buffer */
6958                         buf_len = data_size;
6959                 } else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK) {
6960                         dev_info(&pf->pdev->dev,
6961                                  "capability discovery failed, err %s aq_err %s\n",
6962                                  i40e_stat_str(&pf->hw, err),
6963                                  i40e_aq_str(&pf->hw,
6964                                              pf->hw.aq.asq_last_status));
6965                         return -ENODEV;
6966                 }
6967         } while (err);
6968
6969         if (pf->hw.debug_mask & I40E_DEBUG_USER)
6970                 dev_info(&pf->pdev->dev,
6971                          "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",
6972                          pf->hw.pf_id, pf->hw.func_caps.num_vfs,
6973                          pf->hw.func_caps.num_msix_vectors,
6974                          pf->hw.func_caps.num_msix_vectors_vf,
6975                          pf->hw.func_caps.fd_filters_guaranteed,
6976                          pf->hw.func_caps.fd_filters_best_effort,
6977                          pf->hw.func_caps.num_tx_qp,
6978                          pf->hw.func_caps.num_vsis);
6979
6980 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
6981                        + pf->hw.func_caps.num_vfs)
6982         if (pf->hw.revision_id == 0 && (DEF_NUM_VSI > pf->hw.func_caps.num_vsis)) {
6983                 dev_info(&pf->pdev->dev,
6984                          "got num_vsis %d, setting num_vsis to %d\n",
6985                          pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
6986                 pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
6987         }
6988
6989         return 0;
6990 }
6991
6992 static int i40e_vsi_clear(struct i40e_vsi *vsi);
6993
6994 /**
6995  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
6996  * @pf: board private structure
6997  **/
6998 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
6999 {
7000         struct i40e_vsi *vsi;
7001
7002         /* quick workaround for an NVM issue that leaves a critical register
7003          * uninitialized
7004          */
7005         if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
7006                 static const u32 hkey[] = {
7007                         0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
7008                         0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
7009                         0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
7010                         0x95b3a76d};
7011                 int i;
7012
7013                 for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
7014                         wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
7015         }
7016
7017         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
7018                 return;
7019
7020         /* find existing VSI and see if it needs configuring */
7021         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
7022
7023         /* create a new VSI if none exists */
7024         if (!vsi) {
7025                 vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
7026                                      pf->vsi[pf->lan_vsi]->seid, 0);
7027                 if (!vsi) {
7028                         dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
7029                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
7030                         return;
7031                 }
7032         }
7033
7034         i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
7035 }
7036
7037 /**
7038  * i40e_fdir_teardown - release the Flow Director resources
7039  * @pf: board private structure
7040  **/
7041 static void i40e_fdir_teardown(struct i40e_pf *pf)
7042 {
7043         struct i40e_vsi *vsi;
7044
7045         i40e_fdir_filter_exit(pf);
7046         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
7047         if (vsi)
7048                 i40e_vsi_release(vsi);
7049 }
7050
7051 /**
7052  * i40e_prep_for_reset - prep for the core to reset
7053  * @pf: board private structure
7054  * @lock_acquired: indicates whether or not the lock has been acquired
7055  * before this function was called.
7056  *
7057  * Close up the VFs and other things in prep for PF Reset.
7058   **/
7059 static void i40e_prep_for_reset(struct i40e_pf *pf, bool lock_acquired)
7060 {
7061         struct i40e_hw *hw = &pf->hw;
7062         i40e_status ret = 0;
7063         u32 v;
7064
7065         clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
7066         if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
7067                 return;
7068         if (i40e_check_asq_alive(&pf->hw))
7069                 i40e_vc_notify_reset(pf);
7070
7071         dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
7072
7073         /* quiesce the VSIs and their queues that are not already DOWN */
7074         /* pf_quiesce_all_vsi modifies netdev structures -rtnl_lock needed */
7075         if (!lock_acquired)
7076                 rtnl_lock();
7077         i40e_pf_quiesce_all_vsi(pf);
7078         if (!lock_acquired)
7079                 rtnl_unlock();
7080
7081         for (v = 0; v < pf->num_alloc_vsi; v++) {
7082                 if (pf->vsi[v])
7083                         pf->vsi[v]->seid = 0;
7084         }
7085
7086         i40e_shutdown_adminq(&pf->hw);
7087
7088         /* call shutdown HMC */
7089         if (hw->hmc.hmc_obj) {
7090                 ret = i40e_shutdown_lan_hmc(hw);
7091                 if (ret)
7092                         dev_warn(&pf->pdev->dev,
7093                                  "shutdown_lan_hmc failed: %d\n", ret);
7094         }
7095 }
7096
7097 /**
7098  * i40e_send_version - update firmware with driver version
7099  * @pf: PF struct
7100  */
7101 static void i40e_send_version(struct i40e_pf *pf)
7102 {
7103         struct i40e_driver_version dv;
7104
7105         dv.major_version = DRV_VERSION_MAJOR;
7106         dv.minor_version = DRV_VERSION_MINOR;
7107         dv.build_version = DRV_VERSION_BUILD;
7108         dv.subbuild_version = 0;
7109         strlcpy(dv.driver_string, DRV_VERSION, sizeof(dv.driver_string));
7110         i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
7111 }
7112
7113 /**
7114  * i40e_get_oem_version - get OEM specific version information
7115  * @hw: pointer to the hardware structure
7116  **/
7117 static void i40e_get_oem_version(struct i40e_hw *hw)
7118 {
7119         u16 block_offset = 0xffff;
7120         u16 block_length = 0;
7121         u16 capabilities = 0;
7122         u16 gen_snap = 0;
7123         u16 release = 0;
7124
7125 #define I40E_SR_NVM_OEM_VERSION_PTR             0x1B
7126 #define I40E_NVM_OEM_LENGTH_OFFSET              0x00
7127 #define I40E_NVM_OEM_CAPABILITIES_OFFSET        0x01
7128 #define I40E_NVM_OEM_GEN_OFFSET                 0x02
7129 #define I40E_NVM_OEM_RELEASE_OFFSET             0x03
7130 #define I40E_NVM_OEM_CAPABILITIES_MASK          0x000F
7131 #define I40E_NVM_OEM_LENGTH                     3
7132
7133         /* Check if pointer to OEM version block is valid. */
7134         i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
7135         if (block_offset == 0xffff)
7136                 return;
7137
7138         /* Check if OEM version block has correct length. */
7139         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
7140                            &block_length);
7141         if (block_length < I40E_NVM_OEM_LENGTH)
7142                 return;
7143
7144         /* Check if OEM version format is as expected. */
7145         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
7146                            &capabilities);
7147         if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
7148                 return;
7149
7150         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
7151                            &gen_snap);
7152         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
7153                            &release);
7154         hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
7155         hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
7156 }
7157
7158 /**
7159  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
7160  * @pf: board private structure
7161  **/
7162 static int i40e_reset(struct i40e_pf *pf)
7163 {
7164         struct i40e_hw *hw = &pf->hw;
7165         i40e_status ret;
7166
7167         ret = i40e_pf_reset(hw);
7168         if (ret) {
7169                 dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
7170                 set_bit(__I40E_RESET_FAILED, pf->state);
7171                 clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
7172         } else {
7173                 pf->pfr_count++;
7174         }
7175         return ret;
7176 }
7177
7178 /**
7179  * i40e_rebuild - rebuild using a saved config
7180  * @pf: board private structure
7181  * @reinit: if the Main VSI needs to re-initialized.
7182  * @lock_acquired: indicates whether or not the lock has been acquired
7183  * before this function was called.
7184  **/
7185 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
7186 {
7187         struct i40e_hw *hw = &pf->hw;
7188         u8 set_fc_aq_fail = 0;
7189         i40e_status ret;
7190         u32 val;
7191         int v;
7192
7193         if (test_bit(__I40E_DOWN, pf->state))
7194                 goto clear_recovery;
7195         dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
7196
7197         /* rebuild the basics for the AdminQ, HMC, and initial HW switch */
7198         ret = i40e_init_adminq(&pf->hw);
7199         if (ret) {
7200                 dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
7201                          i40e_stat_str(&pf->hw, ret),
7202                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7203                 goto clear_recovery;
7204         }
7205         i40e_get_oem_version(&pf->hw);
7206
7207         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
7208             ((hw->aq.fw_maj_ver == 4 && hw->aq.fw_min_ver <= 33) ||
7209              hw->aq.fw_maj_ver < 4) && hw->mac.type == I40E_MAC_XL710) {
7210                 /* The following delay is necessary for 4.33 firmware and older
7211                  * to recover after EMP reset. 200 ms should suffice but we
7212                  * put here 300 ms to be sure that FW is ready to operate
7213                  * after reset.
7214                  */
7215                 mdelay(300);
7216         }
7217
7218         /* re-verify the eeprom if we just had an EMP reset */
7219         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
7220                 i40e_verify_eeprom(pf);
7221
7222         i40e_clear_pxe_mode(hw);
7223         ret = i40e_get_capabilities(pf);
7224         if (ret)
7225                 goto end_core_reset;
7226
7227         ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
7228                                 hw->func_caps.num_rx_qp, 0, 0);
7229         if (ret) {
7230                 dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
7231                 goto end_core_reset;
7232         }
7233         ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
7234         if (ret) {
7235                 dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
7236                 goto end_core_reset;
7237         }
7238
7239 #ifdef CONFIG_I40E_DCB
7240         ret = i40e_init_pf_dcb(pf);
7241         if (ret) {
7242                 dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n", ret);
7243                 pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
7244                 /* Continue without DCB enabled */
7245         }
7246 #endif /* CONFIG_I40E_DCB */
7247         /* do basic switch setup */
7248         if (!lock_acquired)
7249                 rtnl_lock();
7250         ret = i40e_setup_pf_switch(pf, reinit);
7251         if (ret)
7252                 goto end_unlock;
7253
7254         /* The driver only wants link up/down and module qualification
7255          * reports from firmware.  Note the negative logic.
7256          */
7257         ret = i40e_aq_set_phy_int_mask(&pf->hw,
7258                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
7259                                          I40E_AQ_EVENT_MEDIA_NA |
7260                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
7261         if (ret)
7262                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
7263                          i40e_stat_str(&pf->hw, ret),
7264                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7265
7266         /* make sure our flow control settings are restored */
7267         ret = i40e_set_fc(&pf->hw, &set_fc_aq_fail, true);
7268         if (ret)
7269                 dev_dbg(&pf->pdev->dev, "setting flow control: ret = %s last_status = %s\n",
7270                         i40e_stat_str(&pf->hw, ret),
7271                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7272
7273         /* Rebuild the VSIs and VEBs that existed before reset.
7274          * They are still in our local switch element arrays, so only
7275          * need to rebuild the switch model in the HW.
7276          *
7277          * If there were VEBs but the reconstitution failed, we'll try
7278          * try to recover minimal use by getting the basic PF VSI working.
7279          */
7280         if (pf->vsi[pf->lan_vsi]->uplink_seid != pf->mac_seid) {
7281                 dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
7282                 /* find the one VEB connected to the MAC, and find orphans */
7283                 for (v = 0; v < I40E_MAX_VEB; v++) {
7284                         if (!pf->veb[v])
7285                                 continue;
7286
7287                         if (pf->veb[v]->uplink_seid == pf->mac_seid ||
7288                             pf->veb[v]->uplink_seid == 0) {
7289                                 ret = i40e_reconstitute_veb(pf->veb[v]);
7290
7291                                 if (!ret)
7292                                         continue;
7293
7294                                 /* If Main VEB failed, we're in deep doodoo,
7295                                  * so give up rebuilding the switch and set up
7296                                  * for minimal rebuild of PF VSI.
7297                                  * If orphan failed, we'll report the error
7298                                  * but try to keep going.
7299                                  */
7300                                 if (pf->veb[v]->uplink_seid == pf->mac_seid) {
7301                                         dev_info(&pf->pdev->dev,
7302                                                  "rebuild of switch failed: %d, will try to set up simple PF connection\n",
7303                                                  ret);
7304                                         pf->vsi[pf->lan_vsi]->uplink_seid
7305                                                                 = pf->mac_seid;
7306                                         break;
7307                                 } else if (pf->veb[v]->uplink_seid == 0) {
7308                                         dev_info(&pf->pdev->dev,
7309                                                  "rebuild of orphan VEB failed: %d\n",
7310                                                  ret);
7311                                 }
7312                         }
7313                 }
7314         }
7315
7316         if (pf->vsi[pf->lan_vsi]->uplink_seid == pf->mac_seid) {
7317                 dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
7318                 /* no VEB, so rebuild only the Main VSI */
7319                 ret = i40e_add_vsi(pf->vsi[pf->lan_vsi]);
7320                 if (ret) {
7321                         dev_info(&pf->pdev->dev,
7322                                  "rebuild of Main VSI failed: %d\n", ret);
7323                         goto end_unlock;
7324                 }
7325         }
7326
7327         /* Reconfigure hardware for allowing smaller MSS in the case
7328          * of TSO, so that we avoid the MDD being fired and causing
7329          * a reset in the case of small MSS+TSO.
7330          */
7331 #define I40E_REG_MSS          0x000E64DC
7332 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
7333 #define I40E_64BYTE_MSS       0x400000
7334         val = rd32(hw, I40E_REG_MSS);
7335         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
7336                 val &= ~I40E_REG_MSS_MIN_MASK;
7337                 val |= I40E_64BYTE_MSS;
7338                 wr32(hw, I40E_REG_MSS, val);
7339         }
7340
7341         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
7342                 msleep(75);
7343                 ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
7344                 if (ret)
7345                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
7346                                  i40e_stat_str(&pf->hw, ret),
7347                                  i40e_aq_str(&pf->hw,
7348                                              pf->hw.aq.asq_last_status));
7349         }
7350         /* reinit the misc interrupt */
7351         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7352                 ret = i40e_setup_misc_vector(pf);
7353
7354         /* Add a filter to drop all Flow control frames from any VSI from being
7355          * transmitted. By doing so we stop a malicious VF from sending out
7356          * PAUSE or PFC frames and potentially controlling traffic for other
7357          * PF/VF VSIs.
7358          * The FW can still send Flow control frames if enabled.
7359          */
7360         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
7361                                                        pf->main_vsi_seid);
7362
7363         /* restart the VSIs that were rebuilt and running before the reset */
7364         i40e_pf_unquiesce_all_vsi(pf);
7365
7366         /* Release the RTNL lock before we start resetting VFs */
7367         if (!lock_acquired)
7368                 rtnl_unlock();
7369
7370         i40e_reset_all_vfs(pf, true);
7371
7372         /* tell the firmware that we're starting */
7373         i40e_send_version(pf);
7374
7375         /* We've already released the lock, so don't do it again */
7376         goto end_core_reset;
7377
7378 end_unlock:
7379         if (!lock_acquired)
7380                 rtnl_unlock();
7381 end_core_reset:
7382         clear_bit(__I40E_RESET_FAILED, pf->state);
7383 clear_recovery:
7384         clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
7385 }
7386
7387 /**
7388  * i40e_reset_and_rebuild - reset and rebuild using a saved config
7389  * @pf: board private structure
7390  * @reinit: if the Main VSI needs to re-initialized.
7391  * @lock_acquired: indicates whether or not the lock has been acquired
7392  * before this function was called.
7393  **/
7394 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
7395                                    bool lock_acquired)
7396 {
7397         int ret;
7398         /* Now we wait for GRST to settle out.
7399          * We don't have to delete the VEBs or VSIs from the hw switch
7400          * because the reset will make them disappear.
7401          */
7402         ret = i40e_reset(pf);
7403         if (!ret)
7404                 i40e_rebuild(pf, reinit, lock_acquired);
7405 }
7406
7407 /**
7408  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
7409  * @pf: board private structure
7410  *
7411  * Close up the VFs and other things in prep for a Core Reset,
7412  * then get ready to rebuild the world.
7413  * @lock_acquired: indicates whether or not the lock has been acquired
7414  * before this function was called.
7415  **/
7416 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
7417 {
7418         i40e_prep_for_reset(pf, lock_acquired);
7419         i40e_reset_and_rebuild(pf, false, lock_acquired);
7420 }
7421
7422 /**
7423  * i40e_handle_mdd_event
7424  * @pf: pointer to the PF structure
7425  *
7426  * Called from the MDD irq handler to identify possibly malicious vfs
7427  **/
7428 static void i40e_handle_mdd_event(struct i40e_pf *pf)
7429 {
7430         struct i40e_hw *hw = &pf->hw;
7431         bool mdd_detected = false;
7432         bool pf_mdd_detected = false;
7433         struct i40e_vf *vf;
7434         u32 reg;
7435         int i;
7436
7437         if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
7438                 return;
7439
7440         /* find what triggered the MDD event */
7441         reg = rd32(hw, I40E_GL_MDET_TX);
7442         if (reg & I40E_GL_MDET_TX_VALID_MASK) {
7443                 u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
7444                                 I40E_GL_MDET_TX_PF_NUM_SHIFT;
7445                 u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
7446                                 I40E_GL_MDET_TX_VF_NUM_SHIFT;
7447                 u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
7448                                 I40E_GL_MDET_TX_EVENT_SHIFT;
7449                 u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
7450                                 I40E_GL_MDET_TX_QUEUE_SHIFT) -
7451                                 pf->hw.func_caps.base_queue;
7452                 if (netif_msg_tx_err(pf))
7453                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
7454                                  event, queue, pf_num, vf_num);
7455                 wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
7456                 mdd_detected = true;
7457         }
7458         reg = rd32(hw, I40E_GL_MDET_RX);
7459         if (reg & I40E_GL_MDET_RX_VALID_MASK) {
7460                 u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
7461                                 I40E_GL_MDET_RX_FUNCTION_SHIFT;
7462                 u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
7463                                 I40E_GL_MDET_RX_EVENT_SHIFT;
7464                 u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
7465                                 I40E_GL_MDET_RX_QUEUE_SHIFT) -
7466                                 pf->hw.func_caps.base_queue;
7467                 if (netif_msg_rx_err(pf))
7468                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
7469                                  event, queue, func);
7470                 wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
7471                 mdd_detected = true;
7472         }
7473
7474         if (mdd_detected) {
7475                 reg = rd32(hw, I40E_PF_MDET_TX);
7476                 if (reg & I40E_PF_MDET_TX_VALID_MASK) {
7477                         wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
7478                         dev_info(&pf->pdev->dev, "TX driver issue detected, PF reset issued\n");
7479                         pf_mdd_detected = true;
7480                 }
7481                 reg = rd32(hw, I40E_PF_MDET_RX);
7482                 if (reg & I40E_PF_MDET_RX_VALID_MASK) {
7483                         wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
7484                         dev_info(&pf->pdev->dev, "RX driver issue detected, PF reset issued\n");
7485                         pf_mdd_detected = true;
7486                 }
7487                 /* Queue belongs to the PF, initiate a reset */
7488                 if (pf_mdd_detected) {
7489                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7490                         i40e_service_event_schedule(pf);
7491                 }
7492         }
7493
7494         /* see if one of the VFs needs its hand slapped */
7495         for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
7496                 vf = &(pf->vf[i]);
7497                 reg = rd32(hw, I40E_VP_MDET_TX(i));
7498                 if (reg & I40E_VP_MDET_TX_VALID_MASK) {
7499                         wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
7500                         vf->num_mdd_events++;
7501                         dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
7502                                  i);
7503                 }
7504
7505                 reg = rd32(hw, I40E_VP_MDET_RX(i));
7506                 if (reg & I40E_VP_MDET_RX_VALID_MASK) {
7507                         wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
7508                         vf->num_mdd_events++;
7509                         dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
7510                                  i);
7511                 }
7512
7513                 if (vf->num_mdd_events > I40E_DEFAULT_NUM_MDD_EVENTS_ALLOWED) {
7514                         dev_info(&pf->pdev->dev,
7515                                  "Too many MDD events on VF %d, disabled\n", i);
7516                         dev_info(&pf->pdev->dev,
7517                                  "Use PF Control I/F to re-enable the VF\n");
7518                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
7519                 }
7520         }
7521
7522         /* re-enable mdd interrupt cause */
7523         clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
7524         reg = rd32(hw, I40E_PFINT_ICR0_ENA);
7525         reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
7526         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
7527         i40e_flush(hw);
7528 }
7529
7530 static const char *i40e_tunnel_name(struct i40e_udp_port_config *port)
7531 {
7532         switch (port->type) {
7533         case UDP_TUNNEL_TYPE_VXLAN:
7534                 return "vxlan";
7535         case UDP_TUNNEL_TYPE_GENEVE:
7536                 return "geneve";
7537         default:
7538                 return "unknown";
7539         }
7540 }
7541
7542 /**
7543  * i40e_sync_udp_filters - Trigger a sync event for existing UDP filters
7544  * @pf: board private structure
7545  **/
7546 static void i40e_sync_udp_filters(struct i40e_pf *pf)
7547 {
7548         int i;
7549
7550         /* loop through and set pending bit for all active UDP filters */
7551         for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
7552                 if (pf->udp_ports[i].port)
7553                         pf->pending_udp_bitmap |= BIT_ULL(i);
7554         }
7555
7556         pf->flags |= I40E_FLAG_UDP_FILTER_SYNC;
7557 }
7558
7559 /**
7560  * i40e_sync_udp_filters_subtask - Sync the VSI filter list with HW
7561  * @pf: board private structure
7562  **/
7563 static void i40e_sync_udp_filters_subtask(struct i40e_pf *pf)
7564 {
7565         struct i40e_hw *hw = &pf->hw;
7566         i40e_status ret;
7567         u16 port;
7568         int i;
7569
7570         if (!(pf->flags & I40E_FLAG_UDP_FILTER_SYNC))
7571                 return;
7572
7573         pf->flags &= ~I40E_FLAG_UDP_FILTER_SYNC;
7574
7575         for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
7576                 if (pf->pending_udp_bitmap & BIT_ULL(i)) {
7577                         pf->pending_udp_bitmap &= ~BIT_ULL(i);
7578                         port = pf->udp_ports[i].port;
7579                         if (port)
7580                                 ret = i40e_aq_add_udp_tunnel(hw, port,
7581                                                         pf->udp_ports[i].type,
7582                                                         NULL, NULL);
7583                         else
7584                                 ret = i40e_aq_del_udp_tunnel(hw, i, NULL);
7585
7586                         if (ret) {
7587                                 dev_info(&pf->pdev->dev,
7588                                          "%s %s port %d, index %d failed, err %s aq_err %s\n",
7589                                          i40e_tunnel_name(&pf->udp_ports[i]),
7590                                          port ? "add" : "delete",
7591                                          port, i,
7592                                          i40e_stat_str(&pf->hw, ret),
7593                                          i40e_aq_str(&pf->hw,
7594                                                      pf->hw.aq.asq_last_status));
7595                                 pf->udp_ports[i].port = 0;
7596                         }
7597                 }
7598         }
7599 }
7600
7601 /**
7602  * i40e_service_task - Run the driver's async subtasks
7603  * @work: pointer to work_struct containing our data
7604  **/
7605 static void i40e_service_task(struct work_struct *work)
7606 {
7607         struct i40e_pf *pf = container_of(work,
7608                                           struct i40e_pf,
7609                                           service_task);
7610         unsigned long start_time = jiffies;
7611
7612         /* don't bother with service tasks if a reset is in progress */
7613         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
7614                 return;
7615
7616         if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
7617                 return;
7618
7619         i40e_detect_recover_hung(pf);
7620         i40e_sync_filters_subtask(pf);
7621         i40e_reset_subtask(pf);
7622         i40e_handle_mdd_event(pf);
7623         i40e_vc_process_vflr_event(pf);
7624         i40e_watchdog_subtask(pf);
7625         i40e_fdir_reinit_subtask(pf);
7626         if (pf->flags & I40E_FLAG_CLIENT_RESET) {
7627                 /* Client subtask will reopen next time through. */
7628                 i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], true);
7629                 pf->flags &= ~I40E_FLAG_CLIENT_RESET;
7630         } else {
7631                 i40e_client_subtask(pf);
7632                 if (pf->flags & I40E_FLAG_CLIENT_L2_CHANGE) {
7633                         i40e_notify_client_of_l2_param_changes(
7634                                                         pf->vsi[pf->lan_vsi]);
7635                         pf->flags &= ~I40E_FLAG_CLIENT_L2_CHANGE;
7636                 }
7637         }
7638         i40e_sync_filters_subtask(pf);
7639         i40e_sync_udp_filters_subtask(pf);
7640         i40e_clean_adminq_subtask(pf);
7641
7642         /* flush memory to make sure state is correct before next watchdog */
7643         smp_mb__before_atomic();
7644         clear_bit(__I40E_SERVICE_SCHED, pf->state);
7645
7646         /* If the tasks have taken longer than one timer cycle or there
7647          * is more work to be done, reschedule the service task now
7648          * rather than wait for the timer to tick again.
7649          */
7650         if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
7651             test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)             ||
7652             test_bit(__I40E_MDD_EVENT_PENDING, pf->state)                ||
7653             test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
7654                 i40e_service_event_schedule(pf);
7655 }
7656
7657 /**
7658  * i40e_service_timer - timer callback
7659  * @data: pointer to PF struct
7660  **/
7661 static void i40e_service_timer(unsigned long data)
7662 {
7663         struct i40e_pf *pf = (struct i40e_pf *)data;
7664
7665         mod_timer(&pf->service_timer,
7666                   round_jiffies(jiffies + pf->service_timer_period));
7667         i40e_service_event_schedule(pf);
7668 }
7669
7670 /**
7671  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
7672  * @vsi: the VSI being configured
7673  **/
7674 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
7675 {
7676         struct i40e_pf *pf = vsi->back;
7677
7678         switch (vsi->type) {
7679         case I40E_VSI_MAIN:
7680                 vsi->alloc_queue_pairs = pf->num_lan_qps;
7681                 vsi->num_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
7682                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7683                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7684                         vsi->num_q_vectors = pf->num_lan_msix;
7685                 else
7686                         vsi->num_q_vectors = 1;
7687
7688                 break;
7689
7690         case I40E_VSI_FDIR:
7691                 vsi->alloc_queue_pairs = 1;
7692                 vsi->num_desc = ALIGN(I40E_FDIR_RING_COUNT,
7693                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7694                 vsi->num_q_vectors = pf->num_fdsb_msix;
7695                 break;
7696
7697         case I40E_VSI_VMDQ2:
7698                 vsi->alloc_queue_pairs = pf->num_vmdq_qps;
7699                 vsi->num_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
7700                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7701                 vsi->num_q_vectors = pf->num_vmdq_msix;
7702                 break;
7703
7704         case I40E_VSI_SRIOV:
7705                 vsi->alloc_queue_pairs = pf->num_vf_qps;
7706                 vsi->num_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
7707                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7708                 break;
7709
7710         default:
7711                 WARN_ON(1);
7712                 return -ENODATA;
7713         }
7714
7715         return 0;
7716 }
7717
7718 /**
7719  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
7720  * @type: VSI pointer
7721  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
7722  *
7723  * On error: returns error code (negative)
7724  * On success: returns 0
7725  **/
7726 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
7727 {
7728         struct i40e_ring **next_rings;
7729         int size;
7730         int ret = 0;
7731
7732         /* allocate memory for both Tx, XDP Tx and Rx ring pointers */
7733         size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
7734                (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
7735         vsi->tx_rings = kzalloc(size, GFP_KERNEL);
7736         if (!vsi->tx_rings)
7737                 return -ENOMEM;
7738         next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
7739         if (i40e_enabled_xdp_vsi(vsi)) {
7740                 vsi->xdp_rings = next_rings;
7741                 next_rings += vsi->alloc_queue_pairs;
7742         }
7743         vsi->rx_rings = next_rings;
7744
7745         if (alloc_qvectors) {
7746                 /* allocate memory for q_vector pointers */
7747                 size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
7748                 vsi->q_vectors = kzalloc(size, GFP_KERNEL);
7749                 if (!vsi->q_vectors) {
7750                         ret = -ENOMEM;
7751                         goto err_vectors;
7752                 }
7753         }
7754         return ret;
7755
7756 err_vectors:
7757         kfree(vsi->tx_rings);
7758         return ret;
7759 }
7760
7761 /**
7762  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
7763  * @pf: board private structure
7764  * @type: type of VSI
7765  *
7766  * On error: returns error code (negative)
7767  * On success: returns vsi index in PF (positive)
7768  **/
7769 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
7770 {
7771         int ret = -ENODEV;
7772         struct i40e_vsi *vsi;
7773         int vsi_idx;
7774         int i;
7775
7776         /* Need to protect the allocation of the VSIs at the PF level */
7777         mutex_lock(&pf->switch_mutex);
7778
7779         /* VSI list may be fragmented if VSI creation/destruction has
7780          * been happening.  We can afford to do a quick scan to look
7781          * for any free VSIs in the list.
7782          *
7783          * find next empty vsi slot, looping back around if necessary
7784          */
7785         i = pf->next_vsi;
7786         while (i < pf->num_alloc_vsi && pf->vsi[i])
7787                 i++;
7788         if (i >= pf->num_alloc_vsi) {
7789                 i = 0;
7790                 while (i < pf->next_vsi && pf->vsi[i])
7791                         i++;
7792         }
7793
7794         if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
7795                 vsi_idx = i;             /* Found one! */
7796         } else {
7797                 ret = -ENODEV;
7798                 goto unlock_pf;  /* out of VSI slots! */
7799         }
7800         pf->next_vsi = ++i;
7801
7802         vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
7803         if (!vsi) {
7804                 ret = -ENOMEM;
7805                 goto unlock_pf;
7806         }
7807         vsi->type = type;
7808         vsi->back = pf;
7809         set_bit(__I40E_VSI_DOWN, vsi->state);
7810         vsi->flags = 0;
7811         vsi->idx = vsi_idx;
7812         vsi->int_rate_limit = 0;
7813         vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
7814                                 pf->rss_table_size : 64;
7815         vsi->netdev_registered = false;
7816         vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
7817         hash_init(vsi->mac_filter_hash);
7818         vsi->irqs_ready = false;
7819
7820         ret = i40e_set_num_rings_in_vsi(vsi);
7821         if (ret)
7822                 goto err_rings;
7823
7824         ret = i40e_vsi_alloc_arrays(vsi, true);
7825         if (ret)
7826                 goto err_rings;
7827
7828         /* Setup default MSIX irq handler for VSI */
7829         i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
7830
7831         /* Initialize VSI lock */
7832         spin_lock_init(&vsi->mac_filter_hash_lock);
7833         pf->vsi[vsi_idx] = vsi;
7834         ret = vsi_idx;
7835         goto unlock_pf;
7836
7837 err_rings:
7838         pf->next_vsi = i - 1;
7839         kfree(vsi);
7840 unlock_pf:
7841         mutex_unlock(&pf->switch_mutex);
7842         return ret;
7843 }
7844
7845 /**
7846  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
7847  * @type: VSI pointer
7848  * @free_qvectors: a bool to specify if q_vectors need to be freed.
7849  *
7850  * On error: returns error code (negative)
7851  * On success: returns 0
7852  **/
7853 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
7854 {
7855         /* free the ring and vector containers */
7856         if (free_qvectors) {
7857                 kfree(vsi->q_vectors);
7858                 vsi->q_vectors = NULL;
7859         }
7860         kfree(vsi->tx_rings);
7861         vsi->tx_rings = NULL;
7862         vsi->rx_rings = NULL;
7863         vsi->xdp_rings = NULL;
7864 }
7865
7866 /**
7867  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
7868  * and lookup table
7869  * @vsi: Pointer to VSI structure
7870  */
7871 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
7872 {
7873         if (!vsi)
7874                 return;
7875
7876         kfree(vsi->rss_hkey_user);
7877         vsi->rss_hkey_user = NULL;
7878
7879         kfree(vsi->rss_lut_user);
7880         vsi->rss_lut_user = NULL;
7881 }
7882
7883 /**
7884  * i40e_vsi_clear - Deallocate the VSI provided
7885  * @vsi: the VSI being un-configured
7886  **/
7887 static int i40e_vsi_clear(struct i40e_vsi *vsi)
7888 {
7889         struct i40e_pf *pf;
7890
7891         if (!vsi)
7892                 return 0;
7893
7894         if (!vsi->back)
7895                 goto free_vsi;
7896         pf = vsi->back;
7897
7898         mutex_lock(&pf->switch_mutex);
7899         if (!pf->vsi[vsi->idx]) {
7900                 dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](%p,type %d)\n",
7901                         vsi->idx, vsi->idx, vsi, vsi->type);
7902                 goto unlock_vsi;
7903         }
7904
7905         if (pf->vsi[vsi->idx] != vsi) {
7906                 dev_err(&pf->pdev->dev,
7907                         "pf->vsi[%d](%p, type %d) != vsi[%d](%p,type %d): no free!\n",
7908                         pf->vsi[vsi->idx]->idx,
7909                         pf->vsi[vsi->idx],
7910                         pf->vsi[vsi->idx]->type,
7911                         vsi->idx, vsi, vsi->type);
7912                 goto unlock_vsi;
7913         }
7914
7915         /* updates the PF for this cleared vsi */
7916         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
7917         i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
7918
7919         i40e_vsi_free_arrays(vsi, true);
7920         i40e_clear_rss_config_user(vsi);
7921
7922         pf->vsi[vsi->idx] = NULL;
7923         if (vsi->idx < pf->next_vsi)
7924                 pf->next_vsi = vsi->idx;
7925
7926 unlock_vsi:
7927         mutex_unlock(&pf->switch_mutex);
7928 free_vsi:
7929         kfree(vsi);
7930
7931         return 0;
7932 }
7933
7934 /**
7935  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
7936  * @vsi: the VSI being cleaned
7937  **/
7938 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
7939 {
7940         int i;
7941
7942         if (vsi->tx_rings && vsi->tx_rings[0]) {
7943                 for (i = 0; i < vsi->alloc_queue_pairs; i++) {
7944                         kfree_rcu(vsi->tx_rings[i], rcu);
7945                         vsi->tx_rings[i] = NULL;
7946                         vsi->rx_rings[i] = NULL;
7947                         if (vsi->xdp_rings)
7948                                 vsi->xdp_rings[i] = NULL;
7949                 }
7950         }
7951 }
7952
7953 /**
7954  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
7955  * @vsi: the VSI being configured
7956  **/
7957 static int i40e_alloc_rings(struct i40e_vsi *vsi)
7958 {
7959         int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
7960         struct i40e_pf *pf = vsi->back;
7961         struct i40e_ring *ring;
7962
7963         /* Set basic values in the rings to be used later during open() */
7964         for (i = 0; i < vsi->alloc_queue_pairs; i++) {
7965                 /* allocate space for both Tx and Rx in one shot */
7966                 ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
7967                 if (!ring)
7968                         goto err_out;
7969
7970                 ring->queue_index = i;
7971                 ring->reg_idx = vsi->base_queue + i;
7972                 ring->ring_active = false;
7973                 ring->vsi = vsi;
7974                 ring->netdev = vsi->netdev;
7975                 ring->dev = &pf->pdev->dev;
7976                 ring->count = vsi->num_desc;
7977                 ring->size = 0;
7978                 ring->dcb_tc = 0;
7979                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
7980                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
7981                 ring->tx_itr_setting = pf->tx_itr_default;
7982                 vsi->tx_rings[i] = ring++;
7983
7984                 if (!i40e_enabled_xdp_vsi(vsi))
7985                         goto setup_rx;
7986
7987                 ring->queue_index = vsi->alloc_queue_pairs + i;
7988                 ring->reg_idx = vsi->base_queue + ring->queue_index;
7989                 ring->ring_active = false;
7990                 ring->vsi = vsi;
7991                 ring->netdev = NULL;
7992                 ring->dev = &pf->pdev->dev;
7993                 ring->count = vsi->num_desc;
7994                 ring->size = 0;
7995                 ring->dcb_tc = 0;
7996                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
7997                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
7998                 set_ring_xdp(ring);
7999                 ring->tx_itr_setting = pf->tx_itr_default;
8000                 vsi->xdp_rings[i] = ring++;
8001
8002 setup_rx:
8003                 ring->queue_index = i;
8004                 ring->reg_idx = vsi->base_queue + i;
8005                 ring->ring_active = false;
8006                 ring->vsi = vsi;
8007                 ring->netdev = vsi->netdev;
8008                 ring->dev = &pf->pdev->dev;
8009                 ring->count = vsi->num_desc;
8010                 ring->size = 0;
8011                 ring->dcb_tc = 0;
8012                 ring->rx_itr_setting = pf->rx_itr_default;
8013                 vsi->rx_rings[i] = ring;
8014         }
8015
8016         return 0;
8017
8018 err_out:
8019         i40e_vsi_clear_rings(vsi);
8020         return -ENOMEM;
8021 }
8022
8023 /**
8024  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
8025  * @pf: board private structure
8026  * @vectors: the number of MSI-X vectors to request
8027  *
8028  * Returns the number of vectors reserved, or error
8029  **/
8030 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
8031 {
8032         vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
8033                                         I40E_MIN_MSIX, vectors);
8034         if (vectors < 0) {
8035                 dev_info(&pf->pdev->dev,
8036                          "MSI-X vector reservation failed: %d\n", vectors);
8037                 vectors = 0;
8038         }
8039
8040         return vectors;
8041 }
8042
8043 /**
8044  * i40e_init_msix - Setup the MSIX capability
8045  * @pf: board private structure
8046  *
8047  * Work with the OS to set up the MSIX vectors needed.
8048  *
8049  * Returns the number of vectors reserved or negative on failure
8050  **/
8051 static int i40e_init_msix(struct i40e_pf *pf)
8052 {
8053         struct i40e_hw *hw = &pf->hw;
8054         int cpus, extra_vectors;
8055         int vectors_left;
8056         int v_budget, i;
8057         int v_actual;
8058         int iwarp_requested = 0;
8059
8060         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8061                 return -ENODEV;
8062
8063         /* The number of vectors we'll request will be comprised of:
8064          *   - Add 1 for "other" cause for Admin Queue events, etc.
8065          *   - The number of LAN queue pairs
8066          *      - Queues being used for RSS.
8067          *              We don't need as many as max_rss_size vectors.
8068          *              use rss_size instead in the calculation since that
8069          *              is governed by number of cpus in the system.
8070          *      - assumes symmetric Tx/Rx pairing
8071          *   - The number of VMDq pairs
8072          *   - The CPU count within the NUMA node if iWARP is enabled
8073          * Once we count this up, try the request.
8074          *
8075          * If we can't get what we want, we'll simplify to nearly nothing
8076          * and try again.  If that still fails, we punt.
8077          */
8078         vectors_left = hw->func_caps.num_msix_vectors;
8079         v_budget = 0;
8080
8081         /* reserve one vector for miscellaneous handler */
8082         if (vectors_left) {
8083                 v_budget++;
8084                 vectors_left--;
8085         }
8086
8087         /* reserve some vectors for the main PF traffic queues. Initially we
8088          * only reserve at most 50% of the available vectors, in the case that
8089          * the number of online CPUs is large. This ensures that we can enable
8090          * extra features as well. Once we've enabled the other features, we
8091          * will use any remaining vectors to reach as close as we can to the
8092          * number of online CPUs.
8093          */
8094         cpus = num_online_cpus();
8095         pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
8096         vectors_left -= pf->num_lan_msix;
8097
8098         /* reserve one vector for sideband flow director */
8099         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
8100                 if (vectors_left) {
8101                         pf->num_fdsb_msix = 1;
8102                         v_budget++;
8103                         vectors_left--;
8104                 } else {
8105                         pf->num_fdsb_msix = 0;
8106                 }
8107         }
8108
8109         /* can we reserve enough for iWARP? */
8110         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
8111                 iwarp_requested = pf->num_iwarp_msix;
8112
8113                 if (!vectors_left)
8114                         pf->num_iwarp_msix = 0;
8115                 else if (vectors_left < pf->num_iwarp_msix)
8116                         pf->num_iwarp_msix = 1;
8117                 v_budget += pf->num_iwarp_msix;
8118                 vectors_left -= pf->num_iwarp_msix;
8119         }
8120
8121         /* any vectors left over go for VMDq support */
8122         if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
8123                 int vmdq_vecs_wanted = pf->num_vmdq_vsis * pf->num_vmdq_qps;
8124                 int vmdq_vecs = min_t(int, vectors_left, vmdq_vecs_wanted);
8125
8126                 if (!vectors_left) {
8127                         pf->num_vmdq_msix = 0;
8128                         pf->num_vmdq_qps = 0;
8129                 } else {
8130                         /* if we're short on vectors for what's desired, we limit
8131                          * the queues per vmdq.  If this is still more than are
8132                          * available, the user will need to change the number of
8133                          * queues/vectors used by the PF later with the ethtool
8134                          * channels command
8135                          */
8136                         if (vmdq_vecs < vmdq_vecs_wanted)
8137                                 pf->num_vmdq_qps = 1;
8138                         pf->num_vmdq_msix = pf->num_vmdq_qps;
8139
8140                         v_budget += vmdq_vecs;
8141                         vectors_left -= vmdq_vecs;
8142                 }
8143         }
8144
8145         /* On systems with a large number of SMP cores, we previously limited
8146          * the number of vectors for num_lan_msix to be at most 50% of the
8147          * available vectors, to allow for other features. Now, we add back
8148          * the remaining vectors. However, we ensure that the total
8149          * num_lan_msix will not exceed num_online_cpus(). To do this, we
8150          * calculate the number of vectors we can add without going over the
8151          * cap of CPUs. For systems with a small number of CPUs this will be
8152          * zero.
8153          */
8154         extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
8155         pf->num_lan_msix += extra_vectors;
8156         vectors_left -= extra_vectors;
8157
8158         WARN(vectors_left < 0,
8159              "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
8160
8161         v_budget += pf->num_lan_msix;
8162         pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
8163                                    GFP_KERNEL);
8164         if (!pf->msix_entries)
8165                 return -ENOMEM;
8166
8167         for (i = 0; i < v_budget; i++)
8168                 pf->msix_entries[i].entry = i;
8169         v_actual = i40e_reserve_msix_vectors(pf, v_budget);
8170
8171         if (v_actual < I40E_MIN_MSIX) {
8172                 pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
8173                 kfree(pf->msix_entries);
8174                 pf->msix_entries = NULL;
8175                 pci_disable_msix(pf->pdev);
8176                 return -ENODEV;
8177
8178         } else if (v_actual == I40E_MIN_MSIX) {
8179                 /* Adjust for minimal MSIX use */
8180                 pf->num_vmdq_vsis = 0;
8181                 pf->num_vmdq_qps = 0;
8182                 pf->num_lan_qps = 1;
8183                 pf->num_lan_msix = 1;
8184
8185         } else if (!vectors_left) {
8186                 /* If we have limited resources, we will start with no vectors
8187                  * for the special features and then allocate vectors to some
8188                  * of these features based on the policy and at the end disable
8189                  * the features that did not get any vectors.
8190                  */
8191                 int vec;
8192
8193                 dev_info(&pf->pdev->dev,
8194                          "MSI-X vector limit reached, attempting to redistribute vectors\n");
8195                 /* reserve the misc vector */
8196                 vec = v_actual - 1;
8197
8198                 /* Scale vector usage down */
8199                 pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
8200                 pf->num_vmdq_vsis = 1;
8201                 pf->num_vmdq_qps = 1;
8202
8203                 /* partition out the remaining vectors */
8204                 switch (vec) {
8205                 case 2:
8206                         pf->num_lan_msix = 1;
8207                         break;
8208                 case 3:
8209                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
8210                                 pf->num_lan_msix = 1;
8211                                 pf->num_iwarp_msix = 1;
8212                         } else {
8213                                 pf->num_lan_msix = 2;
8214                         }
8215                         break;
8216                 default:
8217                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
8218                                 pf->num_iwarp_msix = min_t(int, (vec / 3),
8219                                                  iwarp_requested);
8220                                 pf->num_vmdq_vsis = min_t(int, (vec / 3),
8221                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
8222                         } else {
8223                                 pf->num_vmdq_vsis = min_t(int, (vec / 2),
8224                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
8225                         }
8226                         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
8227                                 pf->num_fdsb_msix = 1;
8228                                 vec--;
8229                         }
8230                         pf->num_lan_msix = min_t(int,
8231                                (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
8232                                                               pf->num_lan_msix);
8233                         pf->num_lan_qps = pf->num_lan_msix;
8234                         break;
8235                 }
8236         }
8237
8238         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
8239             (pf->num_fdsb_msix == 0)) {
8240                 dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
8241                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8242         }
8243         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
8244             (pf->num_vmdq_msix == 0)) {
8245                 dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
8246                 pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
8247         }
8248
8249         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
8250             (pf->num_iwarp_msix == 0)) {
8251                 dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
8252                 pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
8253         }
8254         i40e_debug(&pf->hw, I40E_DEBUG_INIT,
8255                    "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
8256                    pf->num_lan_msix,
8257                    pf->num_vmdq_msix * pf->num_vmdq_vsis,
8258                    pf->num_fdsb_msix,
8259                    pf->num_iwarp_msix);
8260
8261         return v_actual;
8262 }
8263
8264 /**
8265  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
8266  * @vsi: the VSI being configured
8267  * @v_idx: index of the vector in the vsi struct
8268  * @cpu: cpu to be used on affinity_mask
8269  *
8270  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
8271  **/
8272 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx, int cpu)
8273 {
8274         struct i40e_q_vector *q_vector;
8275
8276         /* allocate q_vector */
8277         q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
8278         if (!q_vector)
8279                 return -ENOMEM;
8280
8281         q_vector->vsi = vsi;
8282         q_vector->v_idx = v_idx;
8283         cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
8284
8285         if (vsi->netdev)
8286                 netif_napi_add(vsi->netdev, &q_vector->napi,
8287                                i40e_napi_poll, NAPI_POLL_WEIGHT);
8288
8289         q_vector->rx.latency_range = I40E_LOW_LATENCY;
8290         q_vector->tx.latency_range = I40E_LOW_LATENCY;
8291
8292         /* tie q_vector and vsi together */
8293         vsi->q_vectors[v_idx] = q_vector;
8294
8295         return 0;
8296 }
8297
8298 /**
8299  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
8300  * @vsi: the VSI being configured
8301  *
8302  * We allocate one q_vector per queue interrupt.  If allocation fails we
8303  * return -ENOMEM.
8304  **/
8305 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
8306 {
8307         struct i40e_pf *pf = vsi->back;
8308         int err, v_idx, num_q_vectors, current_cpu;
8309
8310         /* if not MSIX, give the one vector only to the LAN VSI */
8311         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
8312                 num_q_vectors = vsi->num_q_vectors;
8313         else if (vsi == pf->vsi[pf->lan_vsi])
8314                 num_q_vectors = 1;
8315         else
8316                 return -EINVAL;
8317
8318         current_cpu = cpumask_first(cpu_online_mask);
8319
8320         for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
8321                 err = i40e_vsi_alloc_q_vector(vsi, v_idx, current_cpu);
8322                 if (err)
8323                         goto err_out;
8324                 current_cpu = cpumask_next(current_cpu, cpu_online_mask);
8325                 if (unlikely(current_cpu >= nr_cpu_ids))
8326                         current_cpu = cpumask_first(cpu_online_mask);
8327         }
8328
8329         return 0;
8330
8331 err_out:
8332         while (v_idx--)
8333                 i40e_free_q_vector(vsi, v_idx);
8334
8335         return err;
8336 }
8337
8338 /**
8339  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
8340  * @pf: board private structure to initialize
8341  **/
8342 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
8343 {
8344         int vectors = 0;
8345         ssize_t size;
8346
8347         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
8348                 vectors = i40e_init_msix(pf);
8349                 if (vectors < 0) {
8350                         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED   |
8351                                        I40E_FLAG_IWARP_ENABLED  |
8352                                        I40E_FLAG_RSS_ENABLED    |
8353                                        I40E_FLAG_DCB_CAPABLE    |
8354                                        I40E_FLAG_DCB_ENABLED    |
8355                                        I40E_FLAG_SRIOV_ENABLED  |
8356                                        I40E_FLAG_FD_SB_ENABLED  |
8357                                        I40E_FLAG_FD_ATR_ENABLED |
8358                                        I40E_FLAG_VMDQ_ENABLED);
8359
8360                         /* rework the queue expectations without MSIX */
8361                         i40e_determine_queue_usage(pf);
8362                 }
8363         }
8364
8365         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
8366             (pf->flags & I40E_FLAG_MSI_ENABLED)) {
8367                 dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
8368                 vectors = pci_enable_msi(pf->pdev);
8369                 if (vectors < 0) {
8370                         dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
8371                                  vectors);
8372                         pf->flags &= ~I40E_FLAG_MSI_ENABLED;
8373                 }
8374                 vectors = 1;  /* one MSI or Legacy vector */
8375         }
8376
8377         if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
8378                 dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
8379
8380         /* set up vector assignment tracking */
8381         size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
8382         pf->irq_pile = kzalloc(size, GFP_KERNEL);
8383         if (!pf->irq_pile) {
8384                 dev_err(&pf->pdev->dev, "error allocating irq_pile memory\n");
8385                 return -ENOMEM;
8386         }
8387         pf->irq_pile->num_entries = vectors;
8388         pf->irq_pile->search_hint = 0;
8389
8390         /* track first vector for misc interrupts, ignore return */
8391         (void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
8392
8393         return 0;
8394 }
8395
8396 /**
8397  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
8398  * @pf: board private structure
8399  *
8400  * This sets up the handler for MSIX 0, which is used to manage the
8401  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
8402  * when in MSI or Legacy interrupt mode.
8403  **/
8404 static int i40e_setup_misc_vector(struct i40e_pf *pf)
8405 {
8406         struct i40e_hw *hw = &pf->hw;
8407         int err = 0;
8408
8409         /* Only request the irq if this is the first time through, and
8410          * not when we're rebuilding after a Reset
8411          */
8412         if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
8413                 err = request_irq(pf->msix_entries[0].vector,
8414                                   i40e_intr, 0, pf->int_name, pf);
8415                 if (err) {
8416                         dev_info(&pf->pdev->dev,
8417                                  "request_irq for %s failed: %d\n",
8418                                  pf->int_name, err);
8419                         return -EFAULT;
8420                 }
8421         }
8422
8423         i40e_enable_misc_int_causes(pf);
8424
8425         /* associate no queues to the misc vector */
8426         wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
8427         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K);
8428
8429         i40e_flush(hw);
8430
8431         i40e_irq_dynamic_enable_icr0(pf, true);
8432
8433         return err;
8434 }
8435
8436 /**
8437  * i40e_config_rss_aq - Prepare for RSS using AQ commands
8438  * @vsi: vsi structure
8439  * @seed: RSS hash seed
8440  **/
8441 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
8442                               u8 *lut, u16 lut_size)
8443 {
8444         struct i40e_pf *pf = vsi->back;
8445         struct i40e_hw *hw = &pf->hw;
8446         int ret = 0;
8447
8448         if (seed) {
8449                 struct i40e_aqc_get_set_rss_key_data *seed_dw =
8450                         (struct i40e_aqc_get_set_rss_key_data *)seed;
8451                 ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
8452                 if (ret) {
8453                         dev_info(&pf->pdev->dev,
8454                                  "Cannot set RSS key, err %s aq_err %s\n",
8455                                  i40e_stat_str(hw, ret),
8456                                  i40e_aq_str(hw, hw->aq.asq_last_status));
8457                         return ret;
8458                 }
8459         }
8460         if (lut) {
8461                 bool pf_lut = vsi->type == I40E_VSI_MAIN ? true : false;
8462
8463                 ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
8464                 if (ret) {
8465                         dev_info(&pf->pdev->dev,
8466                                  "Cannot set RSS lut, err %s aq_err %s\n",
8467                                  i40e_stat_str(hw, ret),
8468                                  i40e_aq_str(hw, hw->aq.asq_last_status));
8469                         return ret;
8470                 }
8471         }
8472         return ret;
8473 }
8474
8475 /**
8476  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
8477  * @vsi: Pointer to vsi structure
8478  * @seed: Buffter to store the hash keys
8479  * @lut: Buffer to store the lookup table entries
8480  * @lut_size: Size of buffer to store the lookup table entries
8481  *
8482  * Return 0 on success, negative on failure
8483  */
8484 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
8485                            u8 *lut, u16 lut_size)
8486 {
8487         struct i40e_pf *pf = vsi->back;
8488         struct i40e_hw *hw = &pf->hw;
8489         int ret = 0;
8490
8491         if (seed) {
8492                 ret = i40e_aq_get_rss_key(hw, vsi->id,
8493                         (struct i40e_aqc_get_set_rss_key_data *)seed);
8494                 if (ret) {
8495                         dev_info(&pf->pdev->dev,
8496                                  "Cannot get RSS key, err %s aq_err %s\n",
8497                                  i40e_stat_str(&pf->hw, ret),
8498                                  i40e_aq_str(&pf->hw,
8499                                              pf->hw.aq.asq_last_status));
8500                         return ret;
8501                 }
8502         }
8503
8504         if (lut) {
8505                 bool pf_lut = vsi->type == I40E_VSI_MAIN ? true : false;
8506
8507                 ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
8508                 if (ret) {
8509                         dev_info(&pf->pdev->dev,
8510                                  "Cannot get RSS lut, err %s aq_err %s\n",
8511                                  i40e_stat_str(&pf->hw, ret),
8512                                  i40e_aq_str(&pf->hw,
8513                                              pf->hw.aq.asq_last_status));
8514                         return ret;
8515                 }
8516         }
8517
8518         return ret;
8519 }
8520
8521 /**
8522  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
8523  * @vsi: VSI structure
8524  **/
8525 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
8526 {
8527         u8 seed[I40E_HKEY_ARRAY_SIZE];
8528         struct i40e_pf *pf = vsi->back;
8529         u8 *lut;
8530         int ret;
8531
8532         if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
8533                 return 0;
8534
8535         if (!vsi->rss_size)
8536                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
8537                                       vsi->num_queue_pairs);
8538         if (!vsi->rss_size)
8539                 return -EINVAL;
8540
8541         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
8542         if (!lut)
8543                 return -ENOMEM;
8544         /* Use the user configured hash keys and lookup table if there is one,
8545          * otherwise use default
8546          */
8547         if (vsi->rss_lut_user)
8548                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
8549         else
8550                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
8551         if (vsi->rss_hkey_user)
8552                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
8553         else
8554                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
8555         ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
8556         kfree(lut);
8557
8558         return ret;
8559 }
8560
8561 /**
8562  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
8563  * @vsi: Pointer to vsi structure
8564  * @seed: RSS hash seed
8565  * @lut: Lookup table
8566  * @lut_size: Lookup table size
8567  *
8568  * Returns 0 on success, negative on failure
8569  **/
8570 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
8571                                const u8 *lut, u16 lut_size)
8572 {
8573         struct i40e_pf *pf = vsi->back;
8574         struct i40e_hw *hw = &pf->hw;
8575         u16 vf_id = vsi->vf_id;
8576         u8 i;
8577
8578         /* Fill out hash function seed */
8579         if (seed) {
8580                 u32 *seed_dw = (u32 *)seed;
8581
8582                 if (vsi->type == I40E_VSI_MAIN) {
8583                         for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
8584                                 wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
8585                 } else if (vsi->type == I40E_VSI_SRIOV) {
8586                         for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
8587                                 wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
8588                 } else {
8589                         dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
8590                 }
8591         }
8592
8593         if (lut) {
8594                 u32 *lut_dw = (u32 *)lut;
8595
8596                 if (vsi->type == I40E_VSI_MAIN) {
8597                         if (lut_size != I40E_HLUT_ARRAY_SIZE)
8598                                 return -EINVAL;
8599                         for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
8600                                 wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
8601                 } else if (vsi->type == I40E_VSI_SRIOV) {
8602                         if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
8603                                 return -EINVAL;
8604                         for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
8605                                 wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
8606                 } else {
8607                         dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
8608                 }
8609         }
8610         i40e_flush(hw);
8611
8612         return 0;
8613 }
8614
8615 /**
8616  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
8617  * @vsi: Pointer to VSI structure
8618  * @seed: Buffer to store the keys
8619  * @lut: Buffer to store the lookup table entries
8620  * @lut_size: Size of buffer to store the lookup table entries
8621  *
8622  * Returns 0 on success, negative on failure
8623  */
8624 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
8625                             u8 *lut, u16 lut_size)
8626 {
8627         struct i40e_pf *pf = vsi->back;
8628         struct i40e_hw *hw = &pf->hw;
8629         u16 i;
8630
8631         if (seed) {
8632                 u32 *seed_dw = (u32 *)seed;
8633
8634                 for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
8635                         seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
8636         }
8637         if (lut) {
8638                 u32 *lut_dw = (u32 *)lut;
8639
8640                 if (lut_size != I40E_HLUT_ARRAY_SIZE)
8641                         return -EINVAL;
8642                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
8643                         lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
8644         }
8645
8646         return 0;
8647 }
8648
8649 /**
8650  * i40e_config_rss - Configure RSS keys and lut
8651  * @vsi: Pointer to VSI structure
8652  * @seed: RSS hash seed
8653  * @lut: Lookup table
8654  * @lut_size: Lookup table size
8655  *
8656  * Returns 0 on success, negative on failure
8657  */
8658 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
8659 {
8660         struct i40e_pf *pf = vsi->back;
8661
8662         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
8663                 return i40e_config_rss_aq(vsi, seed, lut, lut_size);
8664         else
8665                 return i40e_config_rss_reg(vsi, seed, lut, lut_size);
8666 }
8667
8668 /**
8669  * i40e_get_rss - Get RSS keys and lut
8670  * @vsi: Pointer to VSI structure
8671  * @seed: Buffer to store the keys
8672  * @lut: Buffer to store the lookup table entries
8673  * lut_size: Size of buffer to store the lookup table entries
8674  *
8675  * Returns 0 on success, negative on failure
8676  */
8677 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
8678 {
8679         struct i40e_pf *pf = vsi->back;
8680
8681         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
8682                 return i40e_get_rss_aq(vsi, seed, lut, lut_size);
8683         else
8684                 return i40e_get_rss_reg(vsi, seed, lut, lut_size);
8685 }
8686
8687 /**
8688  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
8689  * @pf: Pointer to board private structure
8690  * @lut: Lookup table
8691  * @rss_table_size: Lookup table size
8692  * @rss_size: Range of queue number for hashing
8693  */
8694 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
8695                        u16 rss_table_size, u16 rss_size)
8696 {
8697         u16 i;
8698
8699         for (i = 0; i < rss_table_size; i++)
8700                 lut[i] = i % rss_size;
8701 }
8702
8703 /**
8704  * i40e_pf_config_rss - Prepare for RSS if used
8705  * @pf: board private structure
8706  **/
8707 static int i40e_pf_config_rss(struct i40e_pf *pf)
8708 {
8709         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
8710         u8 seed[I40E_HKEY_ARRAY_SIZE];
8711         u8 *lut;
8712         struct i40e_hw *hw = &pf->hw;
8713         u32 reg_val;
8714         u64 hena;
8715         int ret;
8716
8717         /* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
8718         hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
8719                 ((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
8720         hena |= i40e_pf_get_default_rss_hena(pf);
8721
8722         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
8723         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
8724
8725         /* Determine the RSS table size based on the hardware capabilities */
8726         reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
8727         reg_val = (pf->rss_table_size == 512) ?
8728                         (reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
8729                         (reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
8730         i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
8731
8732         /* Determine the RSS size of the VSI */
8733         if (!vsi->rss_size) {
8734                 u16 qcount;
8735
8736                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
8737                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
8738         }
8739         if (!vsi->rss_size)
8740                 return -EINVAL;
8741
8742         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
8743         if (!lut)
8744                 return -ENOMEM;
8745
8746         /* Use user configured lut if there is one, otherwise use default */
8747         if (vsi->rss_lut_user)
8748                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
8749         else
8750                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
8751
8752         /* Use user configured hash key if there is one, otherwise
8753          * use default.
8754          */
8755         if (vsi->rss_hkey_user)
8756                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
8757         else
8758                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
8759         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
8760         kfree(lut);
8761
8762         return ret;
8763 }
8764
8765 /**
8766  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
8767  * @pf: board private structure
8768  * @queue_count: the requested queue count for rss.
8769  *
8770  * returns 0 if rss is not enabled, if enabled returns the final rss queue
8771  * count which may be different from the requested queue count.
8772  * Note: expects to be called while under rtnl_lock()
8773  **/
8774 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
8775 {
8776         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
8777         int new_rss_size;
8778
8779         if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
8780                 return 0;
8781
8782         new_rss_size = min_t(int, queue_count, pf->rss_size_max);
8783
8784         if (queue_count != vsi->num_queue_pairs) {
8785                 u16 qcount;
8786
8787                 vsi->req_queue_pairs = queue_count;
8788                 i40e_prep_for_reset(pf, true);
8789
8790                 pf->alloc_rss_size = new_rss_size;
8791
8792                 i40e_reset_and_rebuild(pf, true, true);
8793
8794                 /* Discard the user configured hash keys and lut, if less
8795                  * queues are enabled.
8796                  */
8797                 if (queue_count < vsi->rss_size) {
8798                         i40e_clear_rss_config_user(vsi);
8799                         dev_dbg(&pf->pdev->dev,
8800                                 "discard user configured hash keys and lut\n");
8801                 }
8802
8803                 /* Reset vsi->rss_size, as number of enabled queues changed */
8804                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
8805                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
8806
8807                 i40e_pf_config_rss(pf);
8808         }
8809         dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
8810                  vsi->req_queue_pairs, pf->rss_size_max);
8811         return pf->alloc_rss_size;
8812 }
8813
8814 /**
8815  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
8816  * @pf: board private structure
8817  **/
8818 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
8819 {
8820         i40e_status status;
8821         bool min_valid, max_valid;
8822         u32 max_bw, min_bw;
8823
8824         status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
8825                                            &min_valid, &max_valid);
8826
8827         if (!status) {
8828                 if (min_valid)
8829                         pf->min_bw = min_bw;
8830                 if (max_valid)
8831                         pf->max_bw = max_bw;
8832         }
8833
8834         return status;
8835 }
8836
8837 /**
8838  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
8839  * @pf: board private structure
8840  **/
8841 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
8842 {
8843         struct i40e_aqc_configure_partition_bw_data bw_data;
8844         i40e_status status;
8845
8846         /* Set the valid bit for this PF */
8847         bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
8848         bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
8849         bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
8850
8851         /* Set the new bandwidths */
8852         status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
8853
8854         return status;
8855 }
8856
8857 /**
8858  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
8859  * @pf: board private structure
8860  **/
8861 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
8862 {
8863         /* Commit temporary BW setting to permanent NVM image */
8864         enum i40e_admin_queue_err last_aq_status;
8865         i40e_status ret;
8866         u16 nvm_word;
8867
8868         if (pf->hw.partition_id != 1) {
8869                 dev_info(&pf->pdev->dev,
8870                          "Commit BW only works on partition 1! This is partition %d",
8871                          pf->hw.partition_id);
8872                 ret = I40E_NOT_SUPPORTED;
8873                 goto bw_commit_out;
8874         }
8875
8876         /* Acquire NVM for read access */
8877         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
8878         last_aq_status = pf->hw.aq.asq_last_status;
8879         if (ret) {
8880                 dev_info(&pf->pdev->dev,
8881                          "Cannot acquire NVM for read access, err %s aq_err %s\n",
8882                          i40e_stat_str(&pf->hw, ret),
8883                          i40e_aq_str(&pf->hw, last_aq_status));
8884                 goto bw_commit_out;
8885         }
8886
8887         /* Read word 0x10 of NVM - SW compatibility word 1 */
8888         ret = i40e_aq_read_nvm(&pf->hw,
8889                                I40E_SR_NVM_CONTROL_WORD,
8890                                0x10, sizeof(nvm_word), &nvm_word,
8891                                false, NULL);
8892         /* Save off last admin queue command status before releasing
8893          * the NVM
8894          */
8895         last_aq_status = pf->hw.aq.asq_last_status;
8896         i40e_release_nvm(&pf->hw);
8897         if (ret) {
8898                 dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
8899                          i40e_stat_str(&pf->hw, ret),
8900                          i40e_aq_str(&pf->hw, last_aq_status));
8901                 goto bw_commit_out;
8902         }
8903
8904         /* Wait a bit for NVM release to complete */
8905         msleep(50);
8906
8907         /* Acquire NVM for write access */
8908         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
8909         last_aq_status = pf->hw.aq.asq_last_status;
8910         if (ret) {
8911                 dev_info(&pf->pdev->dev,
8912                          "Cannot acquire NVM for write access, err %s aq_err %s\n",
8913                          i40e_stat_str(&pf->hw, ret),
8914                          i40e_aq_str(&pf->hw, last_aq_status));
8915                 goto bw_commit_out;
8916         }
8917         /* Write it back out unchanged to initiate update NVM,
8918          * which will force a write of the shadow (alt) RAM to
8919          * the NVM - thus storing the bandwidth values permanently.
8920          */
8921         ret = i40e_aq_update_nvm(&pf->hw,
8922                                  I40E_SR_NVM_CONTROL_WORD,
8923                                  0x10, sizeof(nvm_word),
8924                                  &nvm_word, true, NULL);
8925         /* Save off last admin queue command status before releasing
8926          * the NVM
8927          */
8928         last_aq_status = pf->hw.aq.asq_last_status;
8929         i40e_release_nvm(&pf->hw);
8930         if (ret)
8931                 dev_info(&pf->pdev->dev,
8932                          "BW settings NOT SAVED, err %s aq_err %s\n",
8933                          i40e_stat_str(&pf->hw, ret),
8934                          i40e_aq_str(&pf->hw, last_aq_status));
8935 bw_commit_out:
8936
8937         return ret;
8938 }
8939
8940 /**
8941  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
8942  * @pf: board private structure to initialize
8943  *
8944  * i40e_sw_init initializes the Adapter private data structure.
8945  * Fields are initialized based on PCI device information and
8946  * OS network device settings (MTU size).
8947  **/
8948 static int i40e_sw_init(struct i40e_pf *pf)
8949 {
8950         int err = 0;
8951         int size;
8952
8953         /* Set default capability flags */
8954         pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
8955                     I40E_FLAG_MSI_ENABLED     |
8956                     I40E_FLAG_MSIX_ENABLED;
8957
8958         /* Set default ITR */
8959         pf->rx_itr_default = I40E_ITR_DYNAMIC | I40E_ITR_RX_DEF;
8960         pf->tx_itr_default = I40E_ITR_DYNAMIC | I40E_ITR_TX_DEF;
8961
8962         /* Depending on PF configurations, it is possible that the RSS
8963          * maximum might end up larger than the available queues
8964          */
8965         pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
8966         pf->alloc_rss_size = 1;
8967         pf->rss_table_size = pf->hw.func_caps.rss_table_size;
8968         pf->rss_size_max = min_t(int, pf->rss_size_max,
8969                                  pf->hw.func_caps.num_tx_qp);
8970         if (pf->hw.func_caps.rss) {
8971                 pf->flags |= I40E_FLAG_RSS_ENABLED;
8972                 pf->alloc_rss_size = min_t(int, pf->rss_size_max,
8973                                            num_online_cpus());
8974         }
8975
8976         /* MFP mode enabled */
8977         if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
8978                 pf->flags |= I40E_FLAG_MFP_ENABLED;
8979                 dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
8980                 if (i40e_get_partition_bw_setting(pf)) {
8981                         dev_warn(&pf->pdev->dev,
8982                                  "Could not get partition bw settings\n");
8983                 } else {
8984                         dev_info(&pf->pdev->dev,
8985                                  "Partition BW Min = %8.8x, Max = %8.8x\n",
8986                                  pf->min_bw, pf->max_bw);
8987
8988                         /* nudge the Tx scheduler */
8989                         i40e_set_partition_bw_setting(pf);
8990                 }
8991         }
8992
8993         if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
8994             (pf->hw.func_caps.fd_filters_best_effort > 0)) {
8995                 pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
8996                 pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
8997                 if (pf->flags & I40E_FLAG_MFP_ENABLED &&
8998                     pf->hw.num_partitions > 1)
8999                         dev_info(&pf->pdev->dev,
9000                                  "Flow Director Sideband mode Disabled in MFP mode\n");
9001                 else
9002                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9003                 pf->fdir_pf_filter_count =
9004                                  pf->hw.func_caps.fd_filters_guaranteed;
9005                 pf->hw.fdir_shared_filter_count =
9006                                  pf->hw.func_caps.fd_filters_best_effort;
9007         }
9008
9009         if (pf->hw.mac.type == I40E_MAC_X722) {
9010                 pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
9011                                     I40E_HW_128_QP_RSS_CAPABLE |
9012                                     I40E_HW_ATR_EVICT_CAPABLE |
9013                                     I40E_HW_WB_ON_ITR_CAPABLE |
9014                                     I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
9015                                     I40E_HW_NO_PCI_LINK_CHECK |
9016                                     I40E_HW_USE_SET_LLDP_MIB |
9017                                     I40E_HW_GENEVE_OFFLOAD_CAPABLE |
9018                                     I40E_HW_PTP_L4_CAPABLE |
9019                                     I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
9020                                     I40E_HW_OUTER_UDP_CSUM_CAPABLE);
9021
9022 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
9023                 if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
9024                     I40E_FDEVICT_PCTYPE_DEFAULT) {
9025                         dev_warn(&pf->pdev->dev,
9026                                  "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
9027                         pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
9028                 }
9029         } else if ((pf->hw.aq.api_maj_ver > 1) ||
9030                    ((pf->hw.aq.api_maj_ver == 1) &&
9031                     (pf->hw.aq.api_min_ver > 4))) {
9032                 /* Supported in FW API version higher than 1.4 */
9033                 pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
9034         }
9035
9036         /* Enable HW ATR eviction if possible */
9037         if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
9038                 pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
9039
9040         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
9041             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
9042             (pf->hw.aq.fw_maj_ver < 4))) {
9043                 pf->hw_features |= I40E_HW_RESTART_AUTONEG;
9044                 /* No DCB support  for FW < v4.33 */
9045                 pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
9046         }
9047
9048         /* Disable FW LLDP if FW < v4.3 */
9049         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
9050             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
9051             (pf->hw.aq.fw_maj_ver < 4)))
9052                 pf->hw_features |= I40E_HW_STOP_FW_LLDP;
9053
9054         /* Use the FW Set LLDP MIB API if FW > v4.40 */
9055         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
9056             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
9057             (pf->hw.aq.fw_maj_ver >= 5)))
9058                 pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
9059
9060         if (pf->hw.func_caps.vmdq) {
9061                 pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
9062                 pf->flags |= I40E_FLAG_VMDQ_ENABLED;
9063                 pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
9064         }
9065
9066         if (pf->hw.func_caps.iwarp) {
9067                 pf->flags |= I40E_FLAG_IWARP_ENABLED;
9068                 /* IWARP needs one extra vector for CQP just like MISC.*/
9069                 pf->num_iwarp_msix = (int)num_online_cpus() + 1;
9070         }
9071
9072 #ifdef CONFIG_PCI_IOV
9073         if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
9074                 pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
9075                 pf->flags |= I40E_FLAG_SRIOV_ENABLED;
9076                 pf->num_req_vfs = min_t(int,
9077                                         pf->hw.func_caps.num_vfs,
9078                                         I40E_MAX_VF_COUNT);
9079         }
9080 #endif /* CONFIG_PCI_IOV */
9081         pf->eeprom_version = 0xDEAD;
9082         pf->lan_veb = I40E_NO_VEB;
9083         pf->lan_vsi = I40E_NO_VSI;
9084
9085         /* By default FW has this off for performance reasons */
9086         pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
9087
9088         /* set up queue assignment tracking */
9089         size = sizeof(struct i40e_lump_tracking)
9090                 + (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
9091         pf->qp_pile = kzalloc(size, GFP_KERNEL);
9092         if (!pf->qp_pile) {
9093                 err = -ENOMEM;
9094                 goto sw_init_done;
9095         }
9096         pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
9097         pf->qp_pile->search_hint = 0;
9098
9099         pf->tx_timeout_recovery_level = 1;
9100
9101         mutex_init(&pf->switch_mutex);
9102
9103 sw_init_done:
9104         return err;
9105 }
9106
9107 /**
9108  * i40e_set_ntuple - set the ntuple feature flag and take action
9109  * @pf: board private structure to initialize
9110  * @features: the feature set that the stack is suggesting
9111  *
9112  * returns a bool to indicate if reset needs to happen
9113  **/
9114 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
9115 {
9116         bool need_reset = false;
9117
9118         /* Check if Flow Director n-tuple support was enabled or disabled.  If
9119          * the state changed, we need to reset.
9120          */
9121         if (features & NETIF_F_NTUPLE) {
9122                 /* Enable filters and mark for reset */
9123                 if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
9124                         need_reset = true;
9125                 /* enable FD_SB only if there is MSI-X vector */
9126                 if (pf->num_fdsb_msix > 0)
9127                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9128         } else {
9129                 /* turn off filters, mark for reset and clear SW filter list */
9130                 if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
9131                         need_reset = true;
9132                         i40e_fdir_filter_exit(pf);
9133                 }
9134                 pf->flags &= ~(I40E_FLAG_FD_SB_ENABLED |
9135                                I40E_FLAG_FD_SB_AUTO_DISABLED);
9136                 /* reset fd counters */
9137                 pf->fd_add_err = 0;
9138                 pf->fd_atr_cnt = 0;
9139                 /* if ATR was auto disabled it can be re-enabled. */
9140                 if (pf->flags & I40E_FLAG_FD_ATR_AUTO_DISABLED) {
9141                         pf->flags &= ~I40E_FLAG_FD_ATR_AUTO_DISABLED;
9142                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9143                             (I40E_DEBUG_FD & pf->hw.debug_mask))
9144                                 dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
9145                 }
9146         }
9147         return need_reset;
9148 }
9149
9150 /**
9151  * i40e_clear_rss_lut - clear the rx hash lookup table
9152  * @vsi: the VSI being configured
9153  **/
9154 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
9155 {
9156         struct i40e_pf *pf = vsi->back;
9157         struct i40e_hw *hw = &pf->hw;
9158         u16 vf_id = vsi->vf_id;
9159         u8 i;
9160
9161         if (vsi->type == I40E_VSI_MAIN) {
9162                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
9163                         wr32(hw, I40E_PFQF_HLUT(i), 0);
9164         } else if (vsi->type == I40E_VSI_SRIOV) {
9165                 for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
9166                         i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
9167         } else {
9168                 dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
9169         }
9170 }
9171
9172 /**
9173  * i40e_set_features - set the netdev feature flags
9174  * @netdev: ptr to the netdev being adjusted
9175  * @features: the feature set that the stack is suggesting
9176  * Note: expects to be called while under rtnl_lock()
9177  **/
9178 static int i40e_set_features(struct net_device *netdev,
9179                              netdev_features_t features)
9180 {
9181         struct i40e_netdev_priv *np = netdev_priv(netdev);
9182         struct i40e_vsi *vsi = np->vsi;
9183         struct i40e_pf *pf = vsi->back;
9184         bool need_reset;
9185
9186         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
9187                 i40e_pf_config_rss(pf);
9188         else if (!(features & NETIF_F_RXHASH) &&
9189                  netdev->features & NETIF_F_RXHASH)
9190                 i40e_clear_rss_lut(vsi);
9191
9192         if (features & NETIF_F_HW_VLAN_CTAG_RX)
9193                 i40e_vlan_stripping_enable(vsi);
9194         else
9195                 i40e_vlan_stripping_disable(vsi);
9196
9197         need_reset = i40e_set_ntuple(pf, features);
9198
9199         if (need_reset)
9200                 i40e_do_reset(pf, BIT_ULL(__I40E_PF_RESET_REQUESTED), true);
9201
9202         return 0;
9203 }
9204
9205 /**
9206  * i40e_get_udp_port_idx - Lookup a possibly offloaded for Rx UDP port
9207  * @pf: board private structure
9208  * @port: The UDP port to look up
9209  *
9210  * Returns the index number or I40E_MAX_PF_UDP_OFFLOAD_PORTS if port not found
9211  **/
9212 static u8 i40e_get_udp_port_idx(struct i40e_pf *pf, u16 port)
9213 {
9214         u8 i;
9215
9216         for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
9217                 if (pf->udp_ports[i].port == port)
9218                         return i;
9219         }
9220
9221         return i;
9222 }
9223
9224 /**
9225  * i40e_udp_tunnel_add - Get notifications about UDP tunnel ports that come up
9226  * @netdev: This physical port's netdev
9227  * @ti: Tunnel endpoint information
9228  **/
9229 static void i40e_udp_tunnel_add(struct net_device *netdev,
9230                                 struct udp_tunnel_info *ti)
9231 {
9232         struct i40e_netdev_priv *np = netdev_priv(netdev);
9233         struct i40e_vsi *vsi = np->vsi;
9234         struct i40e_pf *pf = vsi->back;
9235         u16 port = ntohs(ti->port);
9236         u8 next_idx;
9237         u8 idx;
9238
9239         idx = i40e_get_udp_port_idx(pf, port);
9240
9241         /* Check if port already exists */
9242         if (idx < I40E_MAX_PF_UDP_OFFLOAD_PORTS) {
9243                 netdev_info(netdev, "port %d already offloaded\n", port);
9244                 return;
9245         }
9246
9247         /* Now check if there is space to add the new port */
9248         next_idx = i40e_get_udp_port_idx(pf, 0);
9249
9250         if (next_idx == I40E_MAX_PF_UDP_OFFLOAD_PORTS) {
9251                 netdev_info(netdev, "maximum number of offloaded UDP ports reached, not adding port %d\n",
9252                             port);
9253                 return;
9254         }
9255
9256         switch (ti->type) {
9257         case UDP_TUNNEL_TYPE_VXLAN:
9258                 pf->udp_ports[next_idx].type = I40E_AQC_TUNNEL_TYPE_VXLAN;
9259                 break;
9260         case UDP_TUNNEL_TYPE_GENEVE:
9261                 if (!(pf->hw_features & I40E_HW_GENEVE_OFFLOAD_CAPABLE))
9262                         return;
9263                 pf->udp_ports[next_idx].type = I40E_AQC_TUNNEL_TYPE_NGE;
9264                 break;
9265         default:
9266                 return;
9267         }
9268
9269         /* New port: add it and mark its index in the bitmap */
9270         pf->udp_ports[next_idx].port = port;
9271         pf->pending_udp_bitmap |= BIT_ULL(next_idx);
9272         pf->flags |= I40E_FLAG_UDP_FILTER_SYNC;
9273 }
9274
9275 /**
9276  * i40e_udp_tunnel_del - Get notifications about UDP tunnel ports that go away
9277  * @netdev: This physical port's netdev
9278  * @ti: Tunnel endpoint information
9279  **/
9280 static void i40e_udp_tunnel_del(struct net_device *netdev,
9281                                 struct udp_tunnel_info *ti)
9282 {
9283         struct i40e_netdev_priv *np = netdev_priv(netdev);
9284         struct i40e_vsi *vsi = np->vsi;
9285         struct i40e_pf *pf = vsi->back;
9286         u16 port = ntohs(ti->port);
9287         u8 idx;
9288
9289         idx = i40e_get_udp_port_idx(pf, port);
9290
9291         /* Check if port already exists */
9292         if (idx >= I40E_MAX_PF_UDP_OFFLOAD_PORTS)
9293                 goto not_found;
9294
9295         switch (ti->type) {
9296         case UDP_TUNNEL_TYPE_VXLAN:
9297                 if (pf->udp_ports[idx].type != I40E_AQC_TUNNEL_TYPE_VXLAN)
9298                         goto not_found;
9299                 break;
9300         case UDP_TUNNEL_TYPE_GENEVE:
9301                 if (pf->udp_ports[idx].type != I40E_AQC_TUNNEL_TYPE_NGE)
9302                         goto not_found;
9303                 break;
9304         default:
9305                 goto not_found;
9306         }
9307
9308         /* if port exists, set it to 0 (mark for deletion)
9309          * and make it pending
9310          */
9311         pf->udp_ports[idx].port = 0;
9312         pf->pending_udp_bitmap |= BIT_ULL(idx);
9313         pf->flags |= I40E_FLAG_UDP_FILTER_SYNC;
9314
9315         return;
9316 not_found:
9317         netdev_warn(netdev, "UDP port %d was not found, not deleting\n",
9318                     port);
9319 }
9320
9321 static int i40e_get_phys_port_id(struct net_device *netdev,
9322                                  struct netdev_phys_item_id *ppid)
9323 {
9324         struct i40e_netdev_priv *np = netdev_priv(netdev);
9325         struct i40e_pf *pf = np->vsi->back;
9326         struct i40e_hw *hw = &pf->hw;
9327
9328         if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
9329                 return -EOPNOTSUPP;
9330
9331         ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
9332         memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
9333
9334         return 0;
9335 }
9336
9337 /**
9338  * i40e_ndo_fdb_add - add an entry to the hardware database
9339  * @ndm: the input from the stack
9340  * @tb: pointer to array of nladdr (unused)
9341  * @dev: the net device pointer
9342  * @addr: the MAC address entry being added
9343  * @flags: instructions from stack about fdb operation
9344  */
9345 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
9346                             struct net_device *dev,
9347                             const unsigned char *addr, u16 vid,
9348                             u16 flags)
9349 {
9350         struct i40e_netdev_priv *np = netdev_priv(dev);
9351         struct i40e_pf *pf = np->vsi->back;
9352         int err = 0;
9353
9354         if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
9355                 return -EOPNOTSUPP;
9356
9357         if (vid) {
9358                 pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
9359                 return -EINVAL;
9360         }
9361
9362         /* Hardware does not support aging addresses so if a
9363          * ndm_state is given only allow permanent addresses
9364          */
9365         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
9366                 netdev_info(dev, "FDB only supports static addresses\n");
9367                 return -EINVAL;
9368         }
9369
9370         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
9371                 err = dev_uc_add_excl(dev, addr);
9372         else if (is_multicast_ether_addr(addr))
9373                 err = dev_mc_add_excl(dev, addr);
9374         else
9375                 err = -EINVAL;
9376
9377         /* Only return duplicate errors if NLM_F_EXCL is set */
9378         if (err == -EEXIST && !(flags & NLM_F_EXCL))
9379                 err = 0;
9380
9381         return err;
9382 }
9383
9384 /**
9385  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
9386  * @dev: the netdev being configured
9387  * @nlh: RTNL message
9388  *
9389  * Inserts a new hardware bridge if not already created and
9390  * enables the bridging mode requested (VEB or VEPA). If the
9391  * hardware bridge has already been inserted and the request
9392  * is to change the mode then that requires a PF reset to
9393  * allow rebuild of the components with required hardware
9394  * bridge mode enabled.
9395  *
9396  * Note: expects to be called while under rtnl_lock()
9397  **/
9398 static int i40e_ndo_bridge_setlink(struct net_device *dev,
9399                                    struct nlmsghdr *nlh,
9400                                    u16 flags)
9401 {
9402         struct i40e_netdev_priv *np = netdev_priv(dev);
9403         struct i40e_vsi *vsi = np->vsi;
9404         struct i40e_pf *pf = vsi->back;
9405         struct i40e_veb *veb = NULL;
9406         struct nlattr *attr, *br_spec;
9407         int i, rem;
9408
9409         /* Only for PF VSI for now */
9410         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
9411                 return -EOPNOTSUPP;
9412
9413         /* Find the HW bridge for PF VSI */
9414         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
9415                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
9416                         veb = pf->veb[i];
9417         }
9418
9419         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
9420
9421         nla_for_each_nested(attr, br_spec, rem) {
9422                 __u16 mode;
9423
9424                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
9425                         continue;
9426
9427                 mode = nla_get_u16(attr);
9428                 if ((mode != BRIDGE_MODE_VEPA) &&
9429                     (mode != BRIDGE_MODE_VEB))
9430                         return -EINVAL;
9431
9432                 /* Insert a new HW bridge */
9433                 if (!veb) {
9434                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
9435                                              vsi->tc_config.enabled_tc);
9436                         if (veb) {
9437                                 veb->bridge_mode = mode;
9438                                 i40e_config_bridge_mode(veb);
9439                         } else {
9440                                 /* No Bridge HW offload available */
9441                                 return -ENOENT;
9442                         }
9443                         break;
9444                 } else if (mode != veb->bridge_mode) {
9445                         /* Existing HW bridge but different mode needs reset */
9446                         veb->bridge_mode = mode;
9447                         /* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
9448                         if (mode == BRIDGE_MODE_VEB)
9449                                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
9450                         else
9451                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
9452                         i40e_do_reset(pf, BIT_ULL(__I40E_PF_RESET_REQUESTED),
9453                                       true);
9454                         break;
9455                 }
9456         }
9457
9458         return 0;
9459 }
9460
9461 /**
9462  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
9463  * @skb: skb buff
9464  * @pid: process id
9465  * @seq: RTNL message seq #
9466  * @dev: the netdev being configured
9467  * @filter_mask: unused
9468  * @nlflags: netlink flags passed in
9469  *
9470  * Return the mode in which the hardware bridge is operating in
9471  * i.e VEB or VEPA.
9472  **/
9473 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
9474                                    struct net_device *dev,
9475                                    u32 __always_unused filter_mask,
9476                                    int nlflags)
9477 {
9478         struct i40e_netdev_priv *np = netdev_priv(dev);
9479         struct i40e_vsi *vsi = np->vsi;
9480         struct i40e_pf *pf = vsi->back;
9481         struct i40e_veb *veb = NULL;
9482         int i;
9483
9484         /* Only for PF VSI for now */
9485         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
9486                 return -EOPNOTSUPP;
9487
9488         /* Find the HW bridge for the PF VSI */
9489         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
9490                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
9491                         veb = pf->veb[i];
9492         }
9493
9494         if (!veb)
9495                 return 0;
9496
9497         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
9498                                        0, 0, nlflags, filter_mask, NULL);
9499 }
9500
9501 /**
9502  * i40e_features_check - Validate encapsulated packet conforms to limits
9503  * @skb: skb buff
9504  * @dev: This physical port's netdev
9505  * @features: Offload features that the stack believes apply
9506  **/
9507 static netdev_features_t i40e_features_check(struct sk_buff *skb,
9508                                              struct net_device *dev,
9509                                              netdev_features_t features)
9510 {
9511         size_t len;
9512
9513         /* No point in doing any of this if neither checksum nor GSO are
9514          * being requested for this frame.  We can rule out both by just
9515          * checking for CHECKSUM_PARTIAL
9516          */
9517         if (skb->ip_summed != CHECKSUM_PARTIAL)
9518                 return features;
9519
9520         /* We cannot support GSO if the MSS is going to be less than
9521          * 64 bytes.  If it is then we need to drop support for GSO.
9522          */
9523         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
9524                 features &= ~NETIF_F_GSO_MASK;
9525
9526         /* MACLEN can support at most 63 words */
9527         len = skb_network_header(skb) - skb->data;
9528         if (len & ~(63 * 2))
9529                 goto out_err;
9530
9531         /* IPLEN and EIPLEN can support at most 127 dwords */
9532         len = skb_transport_header(skb) - skb_network_header(skb);
9533         if (len & ~(127 * 4))
9534                 goto out_err;
9535
9536         if (skb->encapsulation) {
9537                 /* L4TUNLEN can support 127 words */
9538                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
9539                 if (len & ~(127 * 2))
9540                         goto out_err;
9541
9542                 /* IPLEN can support at most 127 dwords */
9543                 len = skb_inner_transport_header(skb) -
9544                       skb_inner_network_header(skb);
9545                 if (len & ~(127 * 4))
9546                         goto out_err;
9547         }
9548
9549         /* No need to validate L4LEN as TCP is the only protocol with a
9550          * a flexible value and we support all possible values supported
9551          * by TCP, which is at most 15 dwords
9552          */
9553
9554         return features;
9555 out_err:
9556         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
9557 }
9558
9559 /**
9560  * i40e_xdp_setup - add/remove an XDP program
9561  * @vsi: VSI to changed
9562  * @prog: XDP program
9563  **/
9564 static int i40e_xdp_setup(struct i40e_vsi *vsi,
9565                           struct bpf_prog *prog)
9566 {
9567         int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
9568         struct i40e_pf *pf = vsi->back;
9569         struct bpf_prog *old_prog;
9570         bool need_reset;
9571         int i;
9572
9573         /* Don't allow frames that span over multiple buffers */
9574         if (frame_size > vsi->rx_buf_len)
9575                 return -EINVAL;
9576
9577         if (!i40e_enabled_xdp_vsi(vsi) && !prog)
9578                 return 0;
9579
9580         /* When turning XDP on->off/off->on we reset and rebuild the rings. */
9581         need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
9582
9583         if (need_reset)
9584                 i40e_prep_for_reset(pf, true);
9585
9586         old_prog = xchg(&vsi->xdp_prog, prog);
9587
9588         if (need_reset)
9589                 i40e_reset_and_rebuild(pf, true, true);
9590
9591         for (i = 0; i < vsi->num_queue_pairs; i++)
9592                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
9593
9594         if (old_prog)
9595                 bpf_prog_put(old_prog);
9596
9597         return 0;
9598 }
9599
9600 /**
9601  * i40e_xdp - implements ndo_xdp for i40e
9602  * @dev: netdevice
9603  * @xdp: XDP command
9604  **/
9605 static int i40e_xdp(struct net_device *dev,
9606                     struct netdev_xdp *xdp)
9607 {
9608         struct i40e_netdev_priv *np = netdev_priv(dev);
9609         struct i40e_vsi *vsi = np->vsi;
9610
9611         if (vsi->type != I40E_VSI_MAIN)
9612                 return -EINVAL;
9613
9614         switch (xdp->command) {
9615         case XDP_SETUP_PROG:
9616                 return i40e_xdp_setup(vsi, xdp->prog);
9617         case XDP_QUERY_PROG:
9618                 xdp->prog_attached = i40e_enabled_xdp_vsi(vsi);
9619                 xdp->prog_id = vsi->xdp_prog ? vsi->xdp_prog->aux->id : 0;
9620                 return 0;
9621         default:
9622                 return -EINVAL;
9623         }
9624 }
9625
9626 static const struct net_device_ops i40e_netdev_ops = {
9627         .ndo_open               = i40e_open,
9628         .ndo_stop               = i40e_close,
9629         .ndo_start_xmit         = i40e_lan_xmit_frame,
9630         .ndo_get_stats64        = i40e_get_netdev_stats_struct,
9631         .ndo_set_rx_mode        = i40e_set_rx_mode,
9632         .ndo_validate_addr      = eth_validate_addr,
9633         .ndo_set_mac_address    = i40e_set_mac,
9634         .ndo_change_mtu         = i40e_change_mtu,
9635         .ndo_do_ioctl           = i40e_ioctl,
9636         .ndo_tx_timeout         = i40e_tx_timeout,
9637         .ndo_vlan_rx_add_vid    = i40e_vlan_rx_add_vid,
9638         .ndo_vlan_rx_kill_vid   = i40e_vlan_rx_kill_vid,
9639 #ifdef CONFIG_NET_POLL_CONTROLLER
9640         .ndo_poll_controller    = i40e_netpoll,
9641 #endif
9642         .ndo_setup_tc           = __i40e_setup_tc,
9643         .ndo_set_features       = i40e_set_features,
9644         .ndo_set_vf_mac         = i40e_ndo_set_vf_mac,
9645         .ndo_set_vf_vlan        = i40e_ndo_set_vf_port_vlan,
9646         .ndo_set_vf_rate        = i40e_ndo_set_vf_bw,
9647         .ndo_get_vf_config      = i40e_ndo_get_vf_config,
9648         .ndo_set_vf_link_state  = i40e_ndo_set_vf_link_state,
9649         .ndo_set_vf_spoofchk    = i40e_ndo_set_vf_spoofchk,
9650         .ndo_set_vf_trust       = i40e_ndo_set_vf_trust,
9651         .ndo_udp_tunnel_add     = i40e_udp_tunnel_add,
9652         .ndo_udp_tunnel_del     = i40e_udp_tunnel_del,
9653         .ndo_get_phys_port_id   = i40e_get_phys_port_id,
9654         .ndo_fdb_add            = i40e_ndo_fdb_add,
9655         .ndo_features_check     = i40e_features_check,
9656         .ndo_bridge_getlink     = i40e_ndo_bridge_getlink,
9657         .ndo_bridge_setlink     = i40e_ndo_bridge_setlink,
9658         .ndo_xdp                = i40e_xdp,
9659 };
9660
9661 /**
9662  * i40e_config_netdev - Setup the netdev flags
9663  * @vsi: the VSI being configured
9664  *
9665  * Returns 0 on success, negative value on failure
9666  **/
9667 static int i40e_config_netdev(struct i40e_vsi *vsi)
9668 {
9669         struct i40e_pf *pf = vsi->back;
9670         struct i40e_hw *hw = &pf->hw;
9671         struct i40e_netdev_priv *np;
9672         struct net_device *netdev;
9673         u8 broadcast[ETH_ALEN];
9674         u8 mac_addr[ETH_ALEN];
9675         int etherdev_size;
9676         netdev_features_t hw_enc_features;
9677         netdev_features_t hw_features;
9678
9679         etherdev_size = sizeof(struct i40e_netdev_priv);
9680         netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
9681         if (!netdev)
9682                 return -ENOMEM;
9683
9684         vsi->netdev = netdev;
9685         np = netdev_priv(netdev);
9686         np->vsi = vsi;
9687
9688         hw_enc_features = NETIF_F_SG                    |
9689                           NETIF_F_IP_CSUM               |
9690                           NETIF_F_IPV6_CSUM             |
9691                           NETIF_F_HIGHDMA               |
9692                           NETIF_F_SOFT_FEATURES         |
9693                           NETIF_F_TSO                   |
9694                           NETIF_F_TSO_ECN               |
9695                           NETIF_F_TSO6                  |
9696                           NETIF_F_GSO_GRE               |
9697                           NETIF_F_GSO_GRE_CSUM          |
9698                           NETIF_F_GSO_PARTIAL           |
9699                           NETIF_F_GSO_IPXIP4            |
9700                           NETIF_F_GSO_IPXIP6            |
9701                           NETIF_F_GSO_UDP_TUNNEL        |
9702                           NETIF_F_GSO_UDP_TUNNEL_CSUM   |
9703                           NETIF_F_SCTP_CRC              |
9704                           NETIF_F_RXHASH                |
9705                           NETIF_F_RXCSUM                |
9706                           0;
9707
9708         if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
9709                 netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
9710
9711         netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
9712
9713         netdev->hw_enc_features |= hw_enc_features;
9714
9715         /* record features VLANs can make use of */
9716         netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
9717
9718         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
9719                 netdev->hw_features |= NETIF_F_NTUPLE;
9720         hw_features = hw_enc_features           |
9721                       NETIF_F_HW_VLAN_CTAG_TX   |
9722                       NETIF_F_HW_VLAN_CTAG_RX;
9723
9724         netdev->hw_features |= hw_features;
9725
9726         netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
9727         netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9728
9729         if (vsi->type == I40E_VSI_MAIN) {
9730                 SET_NETDEV_DEV(netdev, &pf->pdev->dev);
9731                 ether_addr_copy(mac_addr, hw->mac.perm_addr);
9732                 /* The following steps are necessary for two reasons. First,
9733                  * some older NVM configurations load a default MAC-VLAN
9734                  * filter that will accept any tagged packet, and we want to
9735                  * replace this with a normal filter. Additionally, it is
9736                  * possible our MAC address was provided by the platform using
9737                  * Open Firmware or similar.
9738                  *
9739                  * Thus, we need to remove the default filter and install one
9740                  * specific to the MAC address.
9741                  */
9742                 i40e_rm_default_mac_filter(vsi, mac_addr);
9743                 spin_lock_bh(&vsi->mac_filter_hash_lock);
9744                 i40e_add_mac_filter(vsi, mac_addr);
9745                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
9746         } else {
9747                 /* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
9748                  * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
9749                  * the end, which is 4 bytes long, so force truncation of the
9750                  * original name by IFNAMSIZ - 4
9751                  */
9752                 snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
9753                          IFNAMSIZ - 4,
9754                          pf->vsi[pf->lan_vsi]->netdev->name);
9755                 random_ether_addr(mac_addr);
9756
9757                 spin_lock_bh(&vsi->mac_filter_hash_lock);
9758                 i40e_add_mac_filter(vsi, mac_addr);
9759                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
9760         }
9761
9762         /* Add the broadcast filter so that we initially will receive
9763          * broadcast packets. Note that when a new VLAN is first added the
9764          * driver will convert all filters marked I40E_VLAN_ANY into VLAN
9765          * specific filters as part of transitioning into "vlan" operation.
9766          * When more VLANs are added, the driver will copy each existing MAC
9767          * filter and add it for the new VLAN.
9768          *
9769          * Broadcast filters are handled specially by
9770          * i40e_sync_filters_subtask, as the driver must to set the broadcast
9771          * promiscuous bit instead of adding this directly as a MAC/VLAN
9772          * filter. The subtask will update the correct broadcast promiscuous
9773          * bits as VLANs become active or inactive.
9774          */
9775         eth_broadcast_addr(broadcast);
9776         spin_lock_bh(&vsi->mac_filter_hash_lock);
9777         i40e_add_mac_filter(vsi, broadcast);
9778         spin_unlock_bh(&vsi->mac_filter_hash_lock);
9779
9780         ether_addr_copy(netdev->dev_addr, mac_addr);
9781         ether_addr_copy(netdev->perm_addr, mac_addr);
9782
9783         /* i40iw_net_event() reads 16 bytes from neigh->primary_key */
9784         netdev->neigh_priv_len = sizeof(u32) * 4;
9785
9786         netdev->priv_flags |= IFF_UNICAST_FLT;
9787         netdev->priv_flags |= IFF_SUPP_NOFCS;
9788         /* Setup netdev TC information */
9789         i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
9790
9791         netdev->netdev_ops = &i40e_netdev_ops;
9792         netdev->watchdog_timeo = 5 * HZ;
9793         i40e_set_ethtool_ops(netdev);
9794
9795         /* MTU range: 68 - 9706 */
9796         netdev->min_mtu = ETH_MIN_MTU;
9797         netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
9798
9799         return 0;
9800 }
9801
9802 /**
9803  * i40e_vsi_delete - Delete a VSI from the switch
9804  * @vsi: the VSI being removed
9805  *
9806  * Returns 0 on success, negative value on failure
9807  **/
9808 static void i40e_vsi_delete(struct i40e_vsi *vsi)
9809 {
9810         /* remove default VSI is not allowed */
9811         if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
9812                 return;
9813
9814         i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
9815 }
9816
9817 /**
9818  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
9819  * @vsi: the VSI being queried
9820  *
9821  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
9822  **/
9823 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
9824 {
9825         struct i40e_veb *veb;
9826         struct i40e_pf *pf = vsi->back;
9827
9828         /* Uplink is not a bridge so default to VEB */
9829         if (vsi->veb_idx == I40E_NO_VEB)
9830                 return 1;
9831
9832         veb = pf->veb[vsi->veb_idx];
9833         if (!veb) {
9834                 dev_info(&pf->pdev->dev,
9835                          "There is no veb associated with the bridge\n");
9836                 return -ENOENT;
9837         }
9838
9839         /* Uplink is a bridge in VEPA mode */
9840         if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
9841                 return 0;
9842         } else {
9843                 /* Uplink is a bridge in VEB mode */
9844                 return 1;
9845         }
9846
9847         /* VEPA is now default bridge, so return 0 */
9848         return 0;
9849 }
9850
9851 /**
9852  * i40e_add_vsi - Add a VSI to the switch
9853  * @vsi: the VSI being configured
9854  *
9855  * This initializes a VSI context depending on the VSI type to be added and
9856  * passes it down to the add_vsi aq command.
9857  **/
9858 static int i40e_add_vsi(struct i40e_vsi *vsi)
9859 {
9860         int ret = -ENODEV;
9861         struct i40e_pf *pf = vsi->back;
9862         struct i40e_hw *hw = &pf->hw;
9863         struct i40e_vsi_context ctxt;
9864         struct i40e_mac_filter *f;
9865         struct hlist_node *h;
9866         int bkt;
9867
9868         u8 enabled_tc = 0x1; /* TC0 enabled */
9869         int f_count = 0;
9870
9871         memset(&ctxt, 0, sizeof(ctxt));
9872         switch (vsi->type) {
9873         case I40E_VSI_MAIN:
9874                 /* The PF's main VSI is already setup as part of the
9875                  * device initialization, so we'll not bother with
9876                  * the add_vsi call, but we will retrieve the current
9877                  * VSI context.
9878                  */
9879                 ctxt.seid = pf->main_vsi_seid;
9880                 ctxt.pf_num = pf->hw.pf_id;
9881                 ctxt.vf_num = 0;
9882                 ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
9883                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9884                 if (ret) {
9885                         dev_info(&pf->pdev->dev,
9886                                  "couldn't get PF vsi config, err %s aq_err %s\n",
9887                                  i40e_stat_str(&pf->hw, ret),
9888                                  i40e_aq_str(&pf->hw,
9889                                              pf->hw.aq.asq_last_status));
9890                         return -ENOENT;
9891                 }
9892                 vsi->info = ctxt.info;
9893                 vsi->info.valid_sections = 0;
9894
9895                 vsi->seid = ctxt.seid;
9896                 vsi->id = ctxt.vsi_number;
9897
9898                 enabled_tc = i40e_pf_get_tc_map(pf);
9899
9900                 /* MFP mode setup queue map and update VSI */
9901                 if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
9902                     !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
9903                         memset(&ctxt, 0, sizeof(ctxt));
9904                         ctxt.seid = pf->main_vsi_seid;
9905                         ctxt.pf_num = pf->hw.pf_id;
9906                         ctxt.vf_num = 0;
9907                         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
9908                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
9909                         if (ret) {
9910                                 dev_info(&pf->pdev->dev,
9911                                          "update vsi failed, err %s aq_err %s\n",
9912                                          i40e_stat_str(&pf->hw, ret),
9913                                          i40e_aq_str(&pf->hw,
9914                                                     pf->hw.aq.asq_last_status));
9915                                 ret = -ENOENT;
9916                                 goto err;
9917                         }
9918                         /* update the local VSI info queue map */
9919                         i40e_vsi_update_queue_map(vsi, &ctxt);
9920                         vsi->info.valid_sections = 0;
9921                 } else {
9922                         /* Default/Main VSI is only enabled for TC0
9923                          * reconfigure it to enable all TCs that are
9924                          * available on the port in SFP mode.
9925                          * For MFP case the iSCSI PF would use this
9926                          * flow to enable LAN+iSCSI TC.
9927                          */
9928                         ret = i40e_vsi_config_tc(vsi, enabled_tc);
9929                         if (ret) {
9930                                 /* Single TC condition is not fatal,
9931                                  * message and continue
9932                                  */
9933                                 dev_info(&pf->pdev->dev,
9934                                          "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
9935                                          enabled_tc,
9936                                          i40e_stat_str(&pf->hw, ret),
9937                                          i40e_aq_str(&pf->hw,
9938                                                     pf->hw.aq.asq_last_status));
9939                         }
9940                 }
9941                 break;
9942
9943         case I40E_VSI_FDIR:
9944                 ctxt.pf_num = hw->pf_id;
9945                 ctxt.vf_num = 0;
9946                 ctxt.uplink_seid = vsi->uplink_seid;
9947                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
9948                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9949                 if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
9950                     (i40e_is_vsi_uplink_mode_veb(vsi))) {
9951                         ctxt.info.valid_sections |=
9952                              cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9953                         ctxt.info.switch_id =
9954                            cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9955                 }
9956                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
9957                 break;
9958
9959         case I40E_VSI_VMDQ2:
9960                 ctxt.pf_num = hw->pf_id;
9961                 ctxt.vf_num = 0;
9962                 ctxt.uplink_seid = vsi->uplink_seid;
9963                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
9964                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
9965
9966                 /* This VSI is connected to VEB so the switch_id
9967                  * should be set to zero by default.
9968                  */
9969                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
9970                         ctxt.info.valid_sections |=
9971                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9972                         ctxt.info.switch_id =
9973                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9974                 }
9975
9976                 /* Setup the VSI tx/rx queue map for TC0 only for now */
9977                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
9978                 break;
9979
9980         case I40E_VSI_SRIOV:
9981                 ctxt.pf_num = hw->pf_id;
9982                 ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
9983                 ctxt.uplink_seid = vsi->uplink_seid;
9984                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
9985                 ctxt.flags = I40E_AQ_VSI_TYPE_VF;
9986
9987                 /* This VSI is connected to VEB so the switch_id
9988                  * should be set to zero by default.
9989                  */
9990                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
9991                         ctxt.info.valid_sections |=
9992                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9993                         ctxt.info.switch_id =
9994                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9995                 }
9996
9997                 if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
9998                         ctxt.info.valid_sections |=
9999                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
10000                         ctxt.info.queueing_opt_flags |=
10001                                 (I40E_AQ_VSI_QUE_OPT_TCP_ENA |
10002                                  I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
10003                 }
10004
10005                 ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
10006                 ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
10007                 if (pf->vf[vsi->vf_id].spoofchk) {
10008                         ctxt.info.valid_sections |=
10009                                 cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
10010                         ctxt.info.sec_flags |=
10011                                 (I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
10012                                  I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
10013                 }
10014                 /* Setup the VSI tx/rx queue map for TC0 only for now */
10015                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
10016                 break;
10017
10018         case I40E_VSI_IWARP:
10019                 /* send down message to iWARP */
10020                 break;
10021
10022         default:
10023                 return -ENODEV;
10024         }
10025
10026         if (vsi->type != I40E_VSI_MAIN) {
10027                 ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
10028                 if (ret) {
10029                         dev_info(&vsi->back->pdev->dev,
10030                                  "add vsi failed, err %s aq_err %s\n",
10031                                  i40e_stat_str(&pf->hw, ret),
10032                                  i40e_aq_str(&pf->hw,
10033                                              pf->hw.aq.asq_last_status));
10034                         ret = -ENOENT;
10035                         goto err;
10036                 }
10037                 vsi->info = ctxt.info;
10038                 vsi->info.valid_sections = 0;
10039                 vsi->seid = ctxt.seid;
10040                 vsi->id = ctxt.vsi_number;
10041         }
10042
10043         vsi->active_filters = 0;
10044         clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
10045         spin_lock_bh(&vsi->mac_filter_hash_lock);
10046         /* If macvlan filters already exist, force them to get loaded */
10047         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
10048                 f->state = I40E_FILTER_NEW;
10049                 f_count++;
10050         }
10051         spin_unlock_bh(&vsi->mac_filter_hash_lock);
10052
10053         if (f_count) {
10054                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
10055                 pf->flags |= I40E_FLAG_FILTER_SYNC;
10056         }
10057
10058         /* Update VSI BW information */
10059         ret = i40e_vsi_get_bw_info(vsi);
10060         if (ret) {
10061                 dev_info(&pf->pdev->dev,
10062                          "couldn't get vsi bw info, err %s aq_err %s\n",
10063                          i40e_stat_str(&pf->hw, ret),
10064                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10065                 /* VSI is already added so not tearing that up */
10066                 ret = 0;
10067         }
10068
10069 err:
10070         return ret;
10071 }
10072
10073 /**
10074  * i40e_vsi_release - Delete a VSI and free its resources
10075  * @vsi: the VSI being removed
10076  *
10077  * Returns 0 on success or < 0 on error
10078  **/
10079 int i40e_vsi_release(struct i40e_vsi *vsi)
10080 {
10081         struct i40e_mac_filter *f;
10082         struct hlist_node *h;
10083         struct i40e_veb *veb = NULL;
10084         struct i40e_pf *pf;
10085         u16 uplink_seid;
10086         int i, n, bkt;
10087
10088         pf = vsi->back;
10089
10090         /* release of a VEB-owner or last VSI is not allowed */
10091         if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
10092                 dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
10093                          vsi->seid, vsi->uplink_seid);
10094                 return -ENODEV;
10095         }
10096         if (vsi == pf->vsi[pf->lan_vsi] &&
10097             !test_bit(__I40E_DOWN, pf->state)) {
10098                 dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
10099                 return -ENODEV;
10100         }
10101
10102         uplink_seid = vsi->uplink_seid;
10103         if (vsi->type != I40E_VSI_SRIOV) {
10104                 if (vsi->netdev_registered) {
10105                         vsi->netdev_registered = false;
10106                         if (vsi->netdev) {
10107                                 /* results in a call to i40e_close() */
10108                                 unregister_netdev(vsi->netdev);
10109                         }
10110                 } else {
10111                         i40e_vsi_close(vsi);
10112                 }
10113                 i40e_vsi_disable_irq(vsi);
10114         }
10115
10116         spin_lock_bh(&vsi->mac_filter_hash_lock);
10117
10118         /* clear the sync flag on all filters */
10119         if (vsi->netdev) {
10120                 __dev_uc_unsync(vsi->netdev, NULL);
10121                 __dev_mc_unsync(vsi->netdev, NULL);
10122         }
10123
10124         /* make sure any remaining filters are marked for deletion */
10125         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
10126                 __i40e_del_filter(vsi, f);
10127
10128         spin_unlock_bh(&vsi->mac_filter_hash_lock);
10129
10130         i40e_sync_vsi_filters(vsi);
10131
10132         i40e_vsi_delete(vsi);
10133         i40e_vsi_free_q_vectors(vsi);
10134         if (vsi->netdev) {
10135                 free_netdev(vsi->netdev);
10136                 vsi->netdev = NULL;
10137         }
10138         i40e_vsi_clear_rings(vsi);
10139         i40e_vsi_clear(vsi);
10140
10141         /* If this was the last thing on the VEB, except for the
10142          * controlling VSI, remove the VEB, which puts the controlling
10143          * VSI onto the next level down in the switch.
10144          *
10145          * Well, okay, there's one more exception here: don't remove
10146          * the orphan VEBs yet.  We'll wait for an explicit remove request
10147          * from up the network stack.
10148          */
10149         for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
10150                 if (pf->vsi[i] &&
10151                     pf->vsi[i]->uplink_seid == uplink_seid &&
10152                     (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
10153                         n++;      /* count the VSIs */
10154                 }
10155         }
10156         for (i = 0; i < I40E_MAX_VEB; i++) {
10157                 if (!pf->veb[i])
10158                         continue;
10159                 if (pf->veb[i]->uplink_seid == uplink_seid)
10160                         n++;     /* count the VEBs */
10161                 if (pf->veb[i]->seid == uplink_seid)
10162                         veb = pf->veb[i];
10163         }
10164         if (n == 0 && veb && veb->uplink_seid != 0)
10165                 i40e_veb_release(veb);
10166
10167         return 0;
10168 }
10169
10170 /**
10171  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
10172  * @vsi: ptr to the VSI
10173  *
10174  * This should only be called after i40e_vsi_mem_alloc() which allocates the
10175  * corresponding SW VSI structure and initializes num_queue_pairs for the
10176  * newly allocated VSI.
10177  *
10178  * Returns 0 on success or negative on failure
10179  **/
10180 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
10181 {
10182         int ret = -ENOENT;
10183         struct i40e_pf *pf = vsi->back;
10184
10185         if (vsi->q_vectors[0]) {
10186                 dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
10187                          vsi->seid);
10188                 return -EEXIST;
10189         }
10190
10191         if (vsi->base_vector) {
10192                 dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
10193                          vsi->seid, vsi->base_vector);
10194                 return -EEXIST;
10195         }
10196
10197         ret = i40e_vsi_alloc_q_vectors(vsi);
10198         if (ret) {
10199                 dev_info(&pf->pdev->dev,
10200                          "failed to allocate %d q_vector for VSI %d, ret=%d\n",
10201                          vsi->num_q_vectors, vsi->seid, ret);
10202                 vsi->num_q_vectors = 0;
10203                 goto vector_setup_out;
10204         }
10205
10206         /* In Legacy mode, we do not have to get any other vector since we
10207          * piggyback on the misc/ICR0 for queue interrupts.
10208         */
10209         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
10210                 return ret;
10211         if (vsi->num_q_vectors)
10212                 vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
10213                                                  vsi->num_q_vectors, vsi->idx);
10214         if (vsi->base_vector < 0) {
10215                 dev_info(&pf->pdev->dev,
10216                          "failed to get tracking for %d vectors for VSI %d, err=%d\n",
10217                          vsi->num_q_vectors, vsi->seid, vsi->base_vector);
10218                 i40e_vsi_free_q_vectors(vsi);
10219                 ret = -ENOENT;
10220                 goto vector_setup_out;
10221         }
10222
10223 vector_setup_out:
10224         return ret;
10225 }
10226
10227 /**
10228  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
10229  * @vsi: pointer to the vsi.
10230  *
10231  * This re-allocates a vsi's queue resources.
10232  *
10233  * Returns pointer to the successfully allocated and configured VSI sw struct
10234  * on success, otherwise returns NULL on failure.
10235  **/
10236 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
10237 {
10238         u16 alloc_queue_pairs;
10239         struct i40e_pf *pf;
10240         u8 enabled_tc;
10241         int ret;
10242
10243         if (!vsi)
10244                 return NULL;
10245
10246         pf = vsi->back;
10247
10248         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
10249         i40e_vsi_clear_rings(vsi);
10250
10251         i40e_vsi_free_arrays(vsi, false);
10252         i40e_set_num_rings_in_vsi(vsi);
10253         ret = i40e_vsi_alloc_arrays(vsi, false);
10254         if (ret)
10255                 goto err_vsi;
10256
10257         alloc_queue_pairs = vsi->alloc_queue_pairs *
10258                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
10259
10260         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
10261         if (ret < 0) {
10262                 dev_info(&pf->pdev->dev,
10263                          "failed to get tracking for %d queues for VSI %d err %d\n",
10264                          alloc_queue_pairs, vsi->seid, ret);
10265                 goto err_vsi;
10266         }
10267         vsi->base_queue = ret;
10268
10269         /* Update the FW view of the VSI. Force a reset of TC and queue
10270          * layout configurations.
10271          */
10272         enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
10273         pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
10274         pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
10275         i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
10276         if (vsi->type == I40E_VSI_MAIN)
10277                 i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
10278
10279         /* assign it some queues */
10280         ret = i40e_alloc_rings(vsi);
10281         if (ret)
10282                 goto err_rings;
10283
10284         /* map all of the rings to the q_vectors */
10285         i40e_vsi_map_rings_to_vectors(vsi);
10286         return vsi;
10287
10288 err_rings:
10289         i40e_vsi_free_q_vectors(vsi);
10290         if (vsi->netdev_registered) {
10291                 vsi->netdev_registered = false;
10292                 unregister_netdev(vsi->netdev);
10293                 free_netdev(vsi->netdev);
10294                 vsi->netdev = NULL;
10295         }
10296         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
10297 err_vsi:
10298         i40e_vsi_clear(vsi);
10299         return NULL;
10300 }
10301
10302 /**
10303  * i40e_vsi_setup - Set up a VSI by a given type
10304  * @pf: board private structure
10305  * @type: VSI type
10306  * @uplink_seid: the switch element to link to
10307  * @param1: usage depends upon VSI type. For VF types, indicates VF id
10308  *
10309  * This allocates the sw VSI structure and its queue resources, then add a VSI
10310  * to the identified VEB.
10311  *
10312  * Returns pointer to the successfully allocated and configure VSI sw struct on
10313  * success, otherwise returns NULL on failure.
10314  **/
10315 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
10316                                 u16 uplink_seid, u32 param1)
10317 {
10318         struct i40e_vsi *vsi = NULL;
10319         struct i40e_veb *veb = NULL;
10320         u16 alloc_queue_pairs;
10321         int ret, i;
10322         int v_idx;
10323
10324         /* The requested uplink_seid must be either
10325          *     - the PF's port seid
10326          *              no VEB is needed because this is the PF
10327          *              or this is a Flow Director special case VSI
10328          *     - seid of an existing VEB
10329          *     - seid of a VSI that owns an existing VEB
10330          *     - seid of a VSI that doesn't own a VEB
10331          *              a new VEB is created and the VSI becomes the owner
10332          *     - seid of the PF VSI, which is what creates the first VEB
10333          *              this is a special case of the previous
10334          *
10335          * Find which uplink_seid we were given and create a new VEB if needed
10336          */
10337         for (i = 0; i < I40E_MAX_VEB; i++) {
10338                 if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
10339                         veb = pf->veb[i];
10340                         break;
10341                 }
10342         }
10343
10344         if (!veb && uplink_seid != pf->mac_seid) {
10345
10346                 for (i = 0; i < pf->num_alloc_vsi; i++) {
10347                         if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
10348                                 vsi = pf->vsi[i];
10349                                 break;
10350                         }
10351                 }
10352                 if (!vsi) {
10353                         dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
10354                                  uplink_seid);
10355                         return NULL;
10356                 }
10357
10358                 if (vsi->uplink_seid == pf->mac_seid)
10359                         veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
10360                                              vsi->tc_config.enabled_tc);
10361                 else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
10362                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
10363                                              vsi->tc_config.enabled_tc);
10364                 if (veb) {
10365                         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
10366                                 dev_info(&vsi->back->pdev->dev,
10367                                          "New VSI creation error, uplink seid of LAN VSI expected.\n");
10368                                 return NULL;
10369                         }
10370                         /* We come up by default in VEPA mode if SRIOV is not
10371                          * already enabled, in which case we can't force VEPA
10372                          * mode.
10373                          */
10374                         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
10375                                 veb->bridge_mode = BRIDGE_MODE_VEPA;
10376                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
10377                         }
10378                         i40e_config_bridge_mode(veb);
10379                 }
10380                 for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
10381                         if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
10382                                 veb = pf->veb[i];
10383                 }
10384                 if (!veb) {
10385                         dev_info(&pf->pdev->dev, "couldn't add VEB\n");
10386                         return NULL;
10387                 }
10388
10389                 vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
10390                 uplink_seid = veb->seid;
10391         }
10392
10393         /* get vsi sw struct */
10394         v_idx = i40e_vsi_mem_alloc(pf, type);
10395         if (v_idx < 0)
10396                 goto err_alloc;
10397         vsi = pf->vsi[v_idx];
10398         if (!vsi)
10399                 goto err_alloc;
10400         vsi->type = type;
10401         vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
10402
10403         if (type == I40E_VSI_MAIN)
10404                 pf->lan_vsi = v_idx;
10405         else if (type == I40E_VSI_SRIOV)
10406                 vsi->vf_id = param1;
10407         /* assign it some queues */
10408         alloc_queue_pairs = vsi->alloc_queue_pairs *
10409                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
10410
10411         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
10412         if (ret < 0) {
10413                 dev_info(&pf->pdev->dev,
10414                          "failed to get tracking for %d queues for VSI %d err=%d\n",
10415                          alloc_queue_pairs, vsi->seid, ret);
10416                 goto err_vsi;
10417         }
10418         vsi->base_queue = ret;
10419
10420         /* get a VSI from the hardware */
10421         vsi->uplink_seid = uplink_seid;
10422         ret = i40e_add_vsi(vsi);
10423         if (ret)
10424                 goto err_vsi;
10425
10426         switch (vsi->type) {
10427         /* setup the netdev if needed */
10428         case I40E_VSI_MAIN:
10429         case I40E_VSI_VMDQ2:
10430                 ret = i40e_config_netdev(vsi);
10431                 if (ret)
10432                         goto err_netdev;
10433                 ret = register_netdev(vsi->netdev);
10434                 if (ret)
10435                         goto err_netdev;
10436                 vsi->netdev_registered = true;
10437                 netif_carrier_off(vsi->netdev);
10438 #ifdef CONFIG_I40E_DCB
10439                 /* Setup DCB netlink interface */
10440                 i40e_dcbnl_setup(vsi);
10441 #endif /* CONFIG_I40E_DCB */
10442                 /* fall through */
10443
10444         case I40E_VSI_FDIR:
10445                 /* set up vectors and rings if needed */
10446                 ret = i40e_vsi_setup_vectors(vsi);
10447                 if (ret)
10448                         goto err_msix;
10449
10450                 ret = i40e_alloc_rings(vsi);
10451                 if (ret)
10452                         goto err_rings;
10453
10454                 /* map all of the rings to the q_vectors */
10455                 i40e_vsi_map_rings_to_vectors(vsi);
10456
10457                 i40e_vsi_reset_stats(vsi);
10458                 break;
10459
10460         default:
10461                 /* no netdev or rings for the other VSI types */
10462                 break;
10463         }
10464
10465         if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
10466             (vsi->type == I40E_VSI_VMDQ2)) {
10467                 ret = i40e_vsi_config_rss(vsi);
10468         }
10469         return vsi;
10470
10471 err_rings:
10472         i40e_vsi_free_q_vectors(vsi);
10473 err_msix:
10474         if (vsi->netdev_registered) {
10475                 vsi->netdev_registered = false;
10476                 unregister_netdev(vsi->netdev);
10477                 free_netdev(vsi->netdev);
10478                 vsi->netdev = NULL;
10479         }
10480 err_netdev:
10481         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
10482 err_vsi:
10483         i40e_vsi_clear(vsi);
10484 err_alloc:
10485         return NULL;
10486 }
10487
10488 /**
10489  * i40e_veb_get_bw_info - Query VEB BW information
10490  * @veb: the veb to query
10491  *
10492  * Query the Tx scheduler BW configuration data for given VEB
10493  **/
10494 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
10495 {
10496         struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
10497         struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
10498         struct i40e_pf *pf = veb->pf;
10499         struct i40e_hw *hw = &pf->hw;
10500         u32 tc_bw_max;
10501         int ret = 0;
10502         int i;
10503
10504         ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
10505                                                   &bw_data, NULL);
10506         if (ret) {
10507                 dev_info(&pf->pdev->dev,
10508                          "query veb bw config failed, err %s aq_err %s\n",
10509                          i40e_stat_str(&pf->hw, ret),
10510                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
10511                 goto out;
10512         }
10513
10514         ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
10515                                                    &ets_data, NULL);
10516         if (ret) {
10517                 dev_info(&pf->pdev->dev,
10518                          "query veb bw ets config failed, err %s aq_err %s\n",
10519                          i40e_stat_str(&pf->hw, ret),
10520                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
10521                 goto out;
10522         }
10523
10524         veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
10525         veb->bw_max_quanta = ets_data.tc_bw_max;
10526         veb->is_abs_credits = bw_data.absolute_credits_enable;
10527         veb->enabled_tc = ets_data.tc_valid_bits;
10528         tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
10529                     (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
10530         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
10531                 veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
10532                 veb->bw_tc_limit_credits[i] =
10533                                         le16_to_cpu(bw_data.tc_bw_limits[i]);
10534                 veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
10535         }
10536
10537 out:
10538         return ret;
10539 }
10540
10541 /**
10542  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
10543  * @pf: board private structure
10544  *
10545  * On error: returns error code (negative)
10546  * On success: returns vsi index in PF (positive)
10547  **/
10548 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
10549 {
10550         int ret = -ENOENT;
10551         struct i40e_veb *veb;
10552         int i;
10553
10554         /* Need to protect the allocation of switch elements at the PF level */
10555         mutex_lock(&pf->switch_mutex);
10556
10557         /* VEB list may be fragmented if VEB creation/destruction has
10558          * been happening.  We can afford to do a quick scan to look
10559          * for any free slots in the list.
10560          *
10561          * find next empty veb slot, looping back around if necessary
10562          */
10563         i = 0;
10564         while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
10565                 i++;
10566         if (i >= I40E_MAX_VEB) {
10567                 ret = -ENOMEM;
10568                 goto err_alloc_veb;  /* out of VEB slots! */
10569         }
10570
10571         veb = kzalloc(sizeof(*veb), GFP_KERNEL);
10572         if (!veb) {
10573                 ret = -ENOMEM;
10574                 goto err_alloc_veb;
10575         }
10576         veb->pf = pf;
10577         veb->idx = i;
10578         veb->enabled_tc = 1;
10579
10580         pf->veb[i] = veb;
10581         ret = i;
10582 err_alloc_veb:
10583         mutex_unlock(&pf->switch_mutex);
10584         return ret;
10585 }
10586
10587 /**
10588  * i40e_switch_branch_release - Delete a branch of the switch tree
10589  * @branch: where to start deleting
10590  *
10591  * This uses recursion to find the tips of the branch to be
10592  * removed, deleting until we get back to and can delete this VEB.
10593  **/
10594 static void i40e_switch_branch_release(struct i40e_veb *branch)
10595 {
10596         struct i40e_pf *pf = branch->pf;
10597         u16 branch_seid = branch->seid;
10598         u16 veb_idx = branch->idx;
10599         int i;
10600
10601         /* release any VEBs on this VEB - RECURSION */
10602         for (i = 0; i < I40E_MAX_VEB; i++) {
10603                 if (!pf->veb[i])
10604                         continue;
10605                 if (pf->veb[i]->uplink_seid == branch->seid)
10606                         i40e_switch_branch_release(pf->veb[i]);
10607         }
10608
10609         /* Release the VSIs on this VEB, but not the owner VSI.
10610          *
10611          * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
10612          *       the VEB itself, so don't use (*branch) after this loop.
10613          */
10614         for (i = 0; i < pf->num_alloc_vsi; i++) {
10615                 if (!pf->vsi[i])
10616                         continue;
10617                 if (pf->vsi[i]->uplink_seid == branch_seid &&
10618                    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
10619                         i40e_vsi_release(pf->vsi[i]);
10620                 }
10621         }
10622
10623         /* There's one corner case where the VEB might not have been
10624          * removed, so double check it here and remove it if needed.
10625          * This case happens if the veb was created from the debugfs
10626          * commands and no VSIs were added to it.
10627          */
10628         if (pf->veb[veb_idx])
10629                 i40e_veb_release(pf->veb[veb_idx]);
10630 }
10631
10632 /**
10633  * i40e_veb_clear - remove veb struct
10634  * @veb: the veb to remove
10635  **/
10636 static void i40e_veb_clear(struct i40e_veb *veb)
10637 {
10638         if (!veb)
10639                 return;
10640
10641         if (veb->pf) {
10642                 struct i40e_pf *pf = veb->pf;
10643
10644                 mutex_lock(&pf->switch_mutex);
10645                 if (pf->veb[veb->idx] == veb)
10646                         pf->veb[veb->idx] = NULL;
10647                 mutex_unlock(&pf->switch_mutex);
10648         }
10649
10650         kfree(veb);
10651 }
10652
10653 /**
10654  * i40e_veb_release - Delete a VEB and free its resources
10655  * @veb: the VEB being removed
10656  **/
10657 void i40e_veb_release(struct i40e_veb *veb)
10658 {
10659         struct i40e_vsi *vsi = NULL;
10660         struct i40e_pf *pf;
10661         int i, n = 0;
10662
10663         pf = veb->pf;
10664
10665         /* find the remaining VSI and check for extras */
10666         for (i = 0; i < pf->num_alloc_vsi; i++) {
10667                 if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
10668                         n++;
10669                         vsi = pf->vsi[i];
10670                 }
10671         }
10672         if (n != 1) {
10673                 dev_info(&pf->pdev->dev,
10674                          "can't remove VEB %d with %d VSIs left\n",
10675                          veb->seid, n);
10676                 return;
10677         }
10678
10679         /* move the remaining VSI to uplink veb */
10680         vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
10681         if (veb->uplink_seid) {
10682                 vsi->uplink_seid = veb->uplink_seid;
10683                 if (veb->uplink_seid == pf->mac_seid)
10684                         vsi->veb_idx = I40E_NO_VEB;
10685                 else
10686                         vsi->veb_idx = veb->veb_idx;
10687         } else {
10688                 /* floating VEB */
10689                 vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10690                 vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
10691         }
10692
10693         i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
10694         i40e_veb_clear(veb);
10695 }
10696
10697 /**
10698  * i40e_add_veb - create the VEB in the switch
10699  * @veb: the VEB to be instantiated
10700  * @vsi: the controlling VSI
10701  **/
10702 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
10703 {
10704         struct i40e_pf *pf = veb->pf;
10705         bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
10706         int ret;
10707
10708         ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
10709                               veb->enabled_tc, false,
10710                               &veb->seid, enable_stats, NULL);
10711
10712         /* get a VEB from the hardware */
10713         if (ret) {
10714                 dev_info(&pf->pdev->dev,
10715                          "couldn't add VEB, err %s aq_err %s\n",
10716                          i40e_stat_str(&pf->hw, ret),
10717                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10718                 return -EPERM;
10719         }
10720
10721         /* get statistics counter */
10722         ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
10723                                          &veb->stats_idx, NULL, NULL, NULL);
10724         if (ret) {
10725                 dev_info(&pf->pdev->dev,
10726                          "couldn't get VEB statistics idx, err %s aq_err %s\n",
10727                          i40e_stat_str(&pf->hw, ret),
10728                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10729                 return -EPERM;
10730         }
10731         ret = i40e_veb_get_bw_info(veb);
10732         if (ret) {
10733                 dev_info(&pf->pdev->dev,
10734                          "couldn't get VEB bw info, err %s aq_err %s\n",
10735                          i40e_stat_str(&pf->hw, ret),
10736                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10737                 i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
10738                 return -ENOENT;
10739         }
10740
10741         vsi->uplink_seid = veb->seid;
10742         vsi->veb_idx = veb->idx;
10743         vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
10744
10745         return 0;
10746 }
10747
10748 /**
10749  * i40e_veb_setup - Set up a VEB
10750  * @pf: board private structure
10751  * @flags: VEB setup flags
10752  * @uplink_seid: the switch element to link to
10753  * @vsi_seid: the initial VSI seid
10754  * @enabled_tc: Enabled TC bit-map
10755  *
10756  * This allocates the sw VEB structure and links it into the switch
10757  * It is possible and legal for this to be a duplicate of an already
10758  * existing VEB.  It is also possible for both uplink and vsi seids
10759  * to be zero, in order to create a floating VEB.
10760  *
10761  * Returns pointer to the successfully allocated VEB sw struct on
10762  * success, otherwise returns NULL on failure.
10763  **/
10764 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
10765                                 u16 uplink_seid, u16 vsi_seid,
10766                                 u8 enabled_tc)
10767 {
10768         struct i40e_veb *veb, *uplink_veb = NULL;
10769         int vsi_idx, veb_idx;
10770         int ret;
10771
10772         /* if one seid is 0, the other must be 0 to create a floating relay */
10773         if ((uplink_seid == 0 || vsi_seid == 0) &&
10774             (uplink_seid + vsi_seid != 0)) {
10775                 dev_info(&pf->pdev->dev,
10776                          "one, not both seid's are 0: uplink=%d vsi=%d\n",
10777                          uplink_seid, vsi_seid);
10778                 return NULL;
10779         }
10780
10781         /* make sure there is such a vsi and uplink */
10782         for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
10783                 if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
10784                         break;
10785         if (vsi_idx >= pf->num_alloc_vsi && vsi_seid != 0) {
10786                 dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
10787                          vsi_seid);
10788                 return NULL;
10789         }
10790
10791         if (uplink_seid && uplink_seid != pf->mac_seid) {
10792                 for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10793                         if (pf->veb[veb_idx] &&
10794                             pf->veb[veb_idx]->seid == uplink_seid) {
10795                                 uplink_veb = pf->veb[veb_idx];
10796                                 break;
10797                         }
10798                 }
10799                 if (!uplink_veb) {
10800                         dev_info(&pf->pdev->dev,
10801                                  "uplink seid %d not found\n", uplink_seid);
10802                         return NULL;
10803                 }
10804         }
10805
10806         /* get veb sw struct */
10807         veb_idx = i40e_veb_mem_alloc(pf);
10808         if (veb_idx < 0)
10809                 goto err_alloc;
10810         veb = pf->veb[veb_idx];
10811         veb->flags = flags;
10812         veb->uplink_seid = uplink_seid;
10813         veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
10814         veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
10815
10816         /* create the VEB in the switch */
10817         ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
10818         if (ret)
10819                 goto err_veb;
10820         if (vsi_idx == pf->lan_vsi)
10821                 pf->lan_veb = veb->idx;
10822
10823         return veb;
10824
10825 err_veb:
10826         i40e_veb_clear(veb);
10827 err_alloc:
10828         return NULL;
10829 }
10830
10831 /**
10832  * i40e_setup_pf_switch_element - set PF vars based on switch type
10833  * @pf: board private structure
10834  * @ele: element we are building info from
10835  * @num_reported: total number of elements
10836  * @printconfig: should we print the contents
10837  *
10838  * helper function to assist in extracting a few useful SEID values.
10839  **/
10840 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
10841                                 struct i40e_aqc_switch_config_element_resp *ele,
10842                                 u16 num_reported, bool printconfig)
10843 {
10844         u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
10845         u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
10846         u8 element_type = ele->element_type;
10847         u16 seid = le16_to_cpu(ele->seid);
10848
10849         if (printconfig)
10850                 dev_info(&pf->pdev->dev,
10851                          "type=%d seid=%d uplink=%d downlink=%d\n",
10852                          element_type, seid, uplink_seid, downlink_seid);
10853
10854         switch (element_type) {
10855         case I40E_SWITCH_ELEMENT_TYPE_MAC:
10856                 pf->mac_seid = seid;
10857                 break;
10858         case I40E_SWITCH_ELEMENT_TYPE_VEB:
10859                 /* Main VEB? */
10860                 if (uplink_seid != pf->mac_seid)
10861                         break;
10862                 if (pf->lan_veb == I40E_NO_VEB) {
10863                         int v;
10864
10865                         /* find existing or else empty VEB */
10866                         for (v = 0; v < I40E_MAX_VEB; v++) {
10867                                 if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
10868                                         pf->lan_veb = v;
10869                                         break;
10870                                 }
10871                         }
10872                         if (pf->lan_veb == I40E_NO_VEB) {
10873                                 v = i40e_veb_mem_alloc(pf);
10874                                 if (v < 0)
10875                                         break;
10876                                 pf->lan_veb = v;
10877                         }
10878                 }
10879
10880                 pf->veb[pf->lan_veb]->seid = seid;
10881                 pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
10882                 pf->veb[pf->lan_veb]->pf = pf;
10883                 pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
10884                 break;
10885         case I40E_SWITCH_ELEMENT_TYPE_VSI:
10886                 if (num_reported != 1)
10887                         break;
10888                 /* This is immediately after a reset so we can assume this is
10889                  * the PF's VSI
10890                  */
10891                 pf->mac_seid = uplink_seid;
10892                 pf->pf_seid = downlink_seid;
10893                 pf->main_vsi_seid = seid;
10894                 if (printconfig)
10895                         dev_info(&pf->pdev->dev,
10896                                  "pf_seid=%d main_vsi_seid=%d\n",
10897                                  pf->pf_seid, pf->main_vsi_seid);
10898                 break;
10899         case I40E_SWITCH_ELEMENT_TYPE_PF:
10900         case I40E_SWITCH_ELEMENT_TYPE_VF:
10901         case I40E_SWITCH_ELEMENT_TYPE_EMP:
10902         case I40E_SWITCH_ELEMENT_TYPE_BMC:
10903         case I40E_SWITCH_ELEMENT_TYPE_PE:
10904         case I40E_SWITCH_ELEMENT_TYPE_PA:
10905                 /* ignore these for now */
10906                 break;
10907         default:
10908                 dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
10909                          element_type, seid);
10910                 break;
10911         }
10912 }
10913
10914 /**
10915  * i40e_fetch_switch_configuration - Get switch config from firmware
10916  * @pf: board private structure
10917  * @printconfig: should we print the contents
10918  *
10919  * Get the current switch configuration from the device and
10920  * extract a few useful SEID values.
10921  **/
10922 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
10923 {
10924         struct i40e_aqc_get_switch_config_resp *sw_config;
10925         u16 next_seid = 0;
10926         int ret = 0;
10927         u8 *aq_buf;
10928         int i;
10929
10930         aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
10931         if (!aq_buf)
10932                 return -ENOMEM;
10933
10934         sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
10935         do {
10936                 u16 num_reported, num_total;
10937
10938                 ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
10939                                                 I40E_AQ_LARGE_BUF,
10940                                                 &next_seid, NULL);
10941                 if (ret) {
10942                         dev_info(&pf->pdev->dev,
10943                                  "get switch config failed err %s aq_err %s\n",
10944                                  i40e_stat_str(&pf->hw, ret),
10945                                  i40e_aq_str(&pf->hw,
10946                                              pf->hw.aq.asq_last_status));
10947                         kfree(aq_buf);
10948                         return -ENOENT;
10949                 }
10950
10951                 num_reported = le16_to_cpu(sw_config->header.num_reported);
10952                 num_total = le16_to_cpu(sw_config->header.num_total);
10953
10954                 if (printconfig)
10955                         dev_info(&pf->pdev->dev,
10956                                  "header: %d reported %d total\n",
10957                                  num_reported, num_total);
10958
10959                 for (i = 0; i < num_reported; i++) {
10960                         struct i40e_aqc_switch_config_element_resp *ele =
10961                                 &sw_config->element[i];
10962
10963                         i40e_setup_pf_switch_element(pf, ele, num_reported,
10964                                                      printconfig);
10965                 }
10966         } while (next_seid != 0);
10967
10968         kfree(aq_buf);
10969         return ret;
10970 }
10971
10972 /**
10973  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
10974  * @pf: board private structure
10975  * @reinit: if the Main VSI needs to re-initialized.
10976  *
10977  * Returns 0 on success, negative value on failure
10978  **/
10979 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit)
10980 {
10981         u16 flags = 0;
10982         int ret;
10983
10984         /* find out what's out there already */
10985         ret = i40e_fetch_switch_configuration(pf, false);
10986         if (ret) {
10987                 dev_info(&pf->pdev->dev,
10988                          "couldn't fetch switch config, err %s aq_err %s\n",
10989                          i40e_stat_str(&pf->hw, ret),
10990                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10991                 return ret;
10992         }
10993         i40e_pf_reset_stats(pf);
10994
10995         /* set the switch config bit for the whole device to
10996          * support limited promisc or true promisc
10997          * when user requests promisc. The default is limited
10998          * promisc.
10999         */
11000
11001         if ((pf->hw.pf_id == 0) &&
11002             !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT))
11003                 flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
11004
11005         if (pf->hw.pf_id == 0) {
11006                 u16 valid_flags;
11007
11008                 valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
11009                 ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags,
11010                                                 NULL);
11011                 if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
11012                         dev_info(&pf->pdev->dev,
11013                                  "couldn't set switch config bits, err %s aq_err %s\n",
11014                                  i40e_stat_str(&pf->hw, ret),
11015                                  i40e_aq_str(&pf->hw,
11016                                              pf->hw.aq.asq_last_status));
11017                         /* not a fatal problem, just keep going */
11018                 }
11019         }
11020
11021         /* first time setup */
11022         if (pf->lan_vsi == I40E_NO_VSI || reinit) {
11023                 struct i40e_vsi *vsi = NULL;
11024                 u16 uplink_seid;
11025
11026                 /* Set up the PF VSI associated with the PF's main VSI
11027                  * that is already in the HW switch
11028                  */
11029                 if (pf->lan_veb != I40E_NO_VEB && pf->veb[pf->lan_veb])
11030                         uplink_seid = pf->veb[pf->lan_veb]->seid;
11031                 else
11032                         uplink_seid = pf->mac_seid;
11033                 if (pf->lan_vsi == I40E_NO_VSI)
11034                         vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
11035                 else if (reinit)
11036                         vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
11037                 if (!vsi) {
11038                         dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
11039                         i40e_fdir_teardown(pf);
11040                         return -EAGAIN;
11041                 }
11042         } else {
11043                 /* force a reset of TC and queue layout configurations */
11044                 u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
11045
11046                 pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
11047                 pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
11048                 i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
11049         }
11050         i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
11051
11052         i40e_fdir_sb_setup(pf);
11053
11054         /* Setup static PF queue filter control settings */
11055         ret = i40e_setup_pf_filter_control(pf);
11056         if (ret) {
11057                 dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
11058                          ret);
11059                 /* Failure here should not stop continuing other steps */
11060         }
11061
11062         /* enable RSS in the HW, even for only one queue, as the stack can use
11063          * the hash
11064          */
11065         if ((pf->flags & I40E_FLAG_RSS_ENABLED))
11066                 i40e_pf_config_rss(pf);
11067
11068         /* fill in link information and enable LSE reporting */
11069         i40e_link_event(pf);
11070
11071         /* Initialize user-specific link properties */
11072         pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
11073                                   I40E_AQ_AN_COMPLETED) ? true : false);
11074
11075         i40e_ptp_init(pf);
11076
11077         /* repopulate tunnel port filters */
11078         i40e_sync_udp_filters(pf);
11079
11080         return ret;
11081 }
11082
11083 /**
11084  * i40e_determine_queue_usage - Work out queue distribution
11085  * @pf: board private structure
11086  **/
11087 static void i40e_determine_queue_usage(struct i40e_pf *pf)
11088 {
11089         int queues_left;
11090
11091         pf->num_lan_qps = 0;
11092
11093         /* Find the max queues to be put into basic use.  We'll always be
11094          * using TC0, whether or not DCB is running, and TC0 will get the
11095          * big RSS set.
11096          */
11097         queues_left = pf->hw.func_caps.num_tx_qp;
11098
11099         if ((queues_left == 1) ||
11100             !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
11101                 /* one qp for PF, no queues for anything else */
11102                 queues_left = 0;
11103                 pf->alloc_rss_size = pf->num_lan_qps = 1;
11104
11105                 /* make sure all the fancies are disabled */
11106                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
11107                                I40E_FLAG_IWARP_ENABLED  |
11108                                I40E_FLAG_FD_SB_ENABLED  |
11109                                I40E_FLAG_FD_ATR_ENABLED |
11110                                I40E_FLAG_DCB_CAPABLE    |
11111                                I40E_FLAG_DCB_ENABLED    |
11112                                I40E_FLAG_SRIOV_ENABLED  |
11113                                I40E_FLAG_VMDQ_ENABLED);
11114         } else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
11115                                   I40E_FLAG_FD_SB_ENABLED |
11116                                   I40E_FLAG_FD_ATR_ENABLED |
11117                                   I40E_FLAG_DCB_CAPABLE))) {
11118                 /* one qp for PF */
11119                 pf->alloc_rss_size = pf->num_lan_qps = 1;
11120                 queues_left -= pf->num_lan_qps;
11121
11122                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
11123                                I40E_FLAG_IWARP_ENABLED  |
11124                                I40E_FLAG_FD_SB_ENABLED  |
11125                                I40E_FLAG_FD_ATR_ENABLED |
11126                                I40E_FLAG_DCB_ENABLED    |
11127                                I40E_FLAG_VMDQ_ENABLED);
11128         } else {
11129                 /* Not enough queues for all TCs */
11130                 if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
11131                     (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
11132                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
11133                                         I40E_FLAG_DCB_ENABLED);
11134                         dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
11135                 }
11136                 pf->num_lan_qps = max_t(int, pf->rss_size_max,
11137                                         num_online_cpus());
11138                 pf->num_lan_qps = min_t(int, pf->num_lan_qps,
11139                                         pf->hw.func_caps.num_tx_qp);
11140
11141                 queues_left -= pf->num_lan_qps;
11142         }
11143
11144         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11145                 if (queues_left > 1) {
11146                         queues_left -= 1; /* save 1 queue for FD */
11147                 } else {
11148                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11149                         dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
11150                 }
11151         }
11152
11153         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
11154             pf->num_vf_qps && pf->num_req_vfs && queues_left) {
11155                 pf->num_req_vfs = min_t(int, pf->num_req_vfs,
11156                                         (queues_left / pf->num_vf_qps));
11157                 queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
11158         }
11159
11160         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11161             pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
11162                 pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
11163                                           (queues_left / pf->num_vmdq_qps));
11164                 queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
11165         }
11166
11167         pf->queues_left = queues_left;
11168         dev_dbg(&pf->pdev->dev,
11169                 "qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
11170                 pf->hw.func_caps.num_tx_qp,
11171                 !!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
11172                 pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
11173                 pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
11174                 queues_left);
11175 }
11176
11177 /**
11178  * i40e_setup_pf_filter_control - Setup PF static filter control
11179  * @pf: PF to be setup
11180  *
11181  * i40e_setup_pf_filter_control sets up a PF's initial filter control
11182  * settings. If PE/FCoE are enabled then it will also set the per PF
11183  * based filter sizes required for them. It also enables Flow director,
11184  * ethertype and macvlan type filter settings for the pf.
11185  *
11186  * Returns 0 on success, negative on failure
11187  **/
11188 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
11189 {
11190         struct i40e_filter_control_settings *settings = &pf->filter_settings;
11191
11192         settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
11193
11194         /* Flow Director is enabled */
11195         if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
11196                 settings->enable_fdir = true;
11197
11198         /* Ethtype and MACVLAN filters enabled for PF */
11199         settings->enable_ethtype = true;
11200         settings->enable_macvlan = true;
11201
11202         if (i40e_set_filter_control(&pf->hw, settings))
11203                 return -ENOENT;
11204
11205         return 0;
11206 }
11207
11208 #define INFO_STRING_LEN 255
11209 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
11210 static void i40e_print_features(struct i40e_pf *pf)
11211 {
11212         struct i40e_hw *hw = &pf->hw;
11213         char *buf;
11214         int i;
11215
11216         buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
11217         if (!buf)
11218                 return;
11219
11220         i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
11221 #ifdef CONFIG_PCI_IOV
11222         i += snprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
11223 #endif
11224         i += snprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
11225                       pf->hw.func_caps.num_vsis,
11226                       pf->vsi[pf->lan_vsi]->num_queue_pairs);
11227         if (pf->flags & I40E_FLAG_RSS_ENABLED)
11228                 i += snprintf(&buf[i], REMAIN(i), " RSS");
11229         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
11230                 i += snprintf(&buf[i], REMAIN(i), " FD_ATR");
11231         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11232                 i += snprintf(&buf[i], REMAIN(i), " FD_SB");
11233                 i += snprintf(&buf[i], REMAIN(i), " NTUPLE");
11234         }
11235         if (pf->flags & I40E_FLAG_DCB_CAPABLE)
11236                 i += snprintf(&buf[i], REMAIN(i), " DCB");
11237         i += snprintf(&buf[i], REMAIN(i), " VxLAN");
11238         i += snprintf(&buf[i], REMAIN(i), " Geneve");
11239         if (pf->flags & I40E_FLAG_PTP)
11240                 i += snprintf(&buf[i], REMAIN(i), " PTP");
11241         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
11242                 i += snprintf(&buf[i], REMAIN(i), " VEB");
11243         else
11244                 i += snprintf(&buf[i], REMAIN(i), " VEPA");
11245
11246         dev_info(&pf->pdev->dev, "%s\n", buf);
11247         kfree(buf);
11248         WARN_ON(i > INFO_STRING_LEN);
11249 }
11250
11251 /**
11252  * i40e_get_platform_mac_addr - get platform-specific MAC address
11253  * @pdev: PCI device information struct
11254  * @pf: board private structure
11255  *
11256  * Look up the MAC address for the device. First we'll try
11257  * eth_platform_get_mac_address, which will check Open Firmware, or arch
11258  * specific fallback. Otherwise, we'll default to the stored value in
11259  * firmware.
11260  **/
11261 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
11262 {
11263         if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
11264                 i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
11265 }
11266
11267 /**
11268  * i40e_probe - Device initialization routine
11269  * @pdev: PCI device information struct
11270  * @ent: entry in i40e_pci_tbl
11271  *
11272  * i40e_probe initializes a PF identified by a pci_dev structure.
11273  * The OS initialization, configuring of the PF private structure,
11274  * and a hardware reset occur.
11275  *
11276  * Returns 0 on success, negative on failure
11277  **/
11278 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
11279 {
11280         struct i40e_aq_get_phy_abilities_resp abilities;
11281         struct i40e_pf *pf;
11282         struct i40e_hw *hw;
11283         static u16 pfs_found;
11284         u16 wol_nvm_bits;
11285         u16 link_status;
11286         int err;
11287         u32 val;
11288         u32 i;
11289         u8 set_fc_aq_fail;
11290
11291         err = pci_enable_device_mem(pdev);
11292         if (err)
11293                 return err;
11294
11295         /* set up for high or low dma */
11296         err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
11297         if (err) {
11298                 err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
11299                 if (err) {
11300                         dev_err(&pdev->dev,
11301                                 "DMA configuration failed: 0x%x\n", err);
11302                         goto err_dma;
11303                 }
11304         }
11305
11306         /* set up pci connections */
11307         err = pci_request_mem_regions(pdev, i40e_driver_name);
11308         if (err) {
11309                 dev_info(&pdev->dev,
11310                          "pci_request_selected_regions failed %d\n", err);
11311                 goto err_pci_reg;
11312         }
11313
11314         pci_enable_pcie_error_reporting(pdev);
11315         pci_set_master(pdev);
11316
11317         /* Now that we have a PCI connection, we need to do the
11318          * low level device setup.  This is primarily setting up
11319          * the Admin Queue structures and then querying for the
11320          * device's current profile information.
11321          */
11322         pf = kzalloc(sizeof(*pf), GFP_KERNEL);
11323         if (!pf) {
11324                 err = -ENOMEM;
11325                 goto err_pf_alloc;
11326         }
11327         pf->next_vsi = 0;
11328         pf->pdev = pdev;
11329         set_bit(__I40E_DOWN, pf->state);
11330
11331         hw = &pf->hw;
11332         hw->back = pf;
11333
11334         pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
11335                                 I40E_MAX_CSR_SPACE);
11336
11337         hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
11338         if (!hw->hw_addr) {
11339                 err = -EIO;
11340                 dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
11341                          (unsigned int)pci_resource_start(pdev, 0),
11342                          pf->ioremap_len, err);
11343                 goto err_ioremap;
11344         }
11345         hw->vendor_id = pdev->vendor;
11346         hw->device_id = pdev->device;
11347         pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
11348         hw->subsystem_vendor_id = pdev->subsystem_vendor;
11349         hw->subsystem_device_id = pdev->subsystem_device;
11350         hw->bus.device = PCI_SLOT(pdev->devfn);
11351         hw->bus.func = PCI_FUNC(pdev->devfn);
11352         hw->bus.bus_id = pdev->bus->number;
11353         pf->instance = pfs_found;
11354
11355         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
11356         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
11357
11358         /* set up the locks for the AQ, do this only once in probe
11359          * and destroy them only once in remove
11360          */
11361         mutex_init(&hw->aq.asq_mutex);
11362         mutex_init(&hw->aq.arq_mutex);
11363
11364         pf->msg_enable = netif_msg_init(debug,
11365                                         NETIF_MSG_DRV |
11366                                         NETIF_MSG_PROBE |
11367                                         NETIF_MSG_LINK);
11368         if (debug < -1)
11369                 pf->hw.debug_mask = debug;
11370
11371         /* do a special CORER for clearing PXE mode once at init */
11372         if (hw->revision_id == 0 &&
11373             (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
11374                 wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
11375                 i40e_flush(hw);
11376                 msleep(200);
11377                 pf->corer_count++;
11378
11379                 i40e_clear_pxe_mode(hw);
11380         }
11381
11382         /* Reset here to make sure all is clean and to define PF 'n' */
11383         i40e_clear_hw(hw);
11384         err = i40e_pf_reset(hw);
11385         if (err) {
11386                 dev_info(&pdev->dev, "Initial pf_reset failed: %d\n", err);
11387                 goto err_pf_reset;
11388         }
11389         pf->pfr_count++;
11390
11391         hw->aq.num_arq_entries = I40E_AQ_LEN;
11392         hw->aq.num_asq_entries = I40E_AQ_LEN;
11393         hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
11394         hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
11395         pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
11396
11397         snprintf(pf->int_name, sizeof(pf->int_name) - 1,
11398                  "%s-%s:misc",
11399                  dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
11400
11401         err = i40e_init_shared_code(hw);
11402         if (err) {
11403                 dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
11404                          err);
11405                 goto err_pf_reset;
11406         }
11407
11408         /* set up a default setting for link flow control */
11409         pf->hw.fc.requested_mode = I40E_FC_NONE;
11410
11411         err = i40e_init_adminq(hw);
11412         if (err) {
11413                 if (err == I40E_ERR_FIRMWARE_API_VERSION)
11414                         dev_info(&pdev->dev,
11415                                  "The driver for the device stopped because the NVM image is newer than expected. You must install the most recent version of the network driver.\n");
11416                 else
11417                         dev_info(&pdev->dev,
11418                                  "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
11419
11420                 goto err_pf_reset;
11421         }
11422         i40e_get_oem_version(hw);
11423
11424         /* provide nvm, fw, api versions */
11425         dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s\n",
11426                  hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
11427                  hw->aq.api_maj_ver, hw->aq.api_min_ver,
11428                  i40e_nvm_version_str(hw));
11429
11430         if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
11431             hw->aq.api_min_ver > I40E_FW_API_VERSION_MINOR)
11432                 dev_info(&pdev->dev,
11433                          "The driver for the device detected a newer version of the NVM image than expected. Please install the most recent version of the network driver.\n");
11434         else if (hw->aq.api_maj_ver < I40E_FW_API_VERSION_MAJOR ||
11435                  hw->aq.api_min_ver < (I40E_FW_API_VERSION_MINOR - 1))
11436                 dev_info(&pdev->dev,
11437                          "The driver for the device detected an older version of the NVM image than expected. Please update the NVM image.\n");
11438
11439         i40e_verify_eeprom(pf);
11440
11441         /* Rev 0 hardware was never productized */
11442         if (hw->revision_id < 1)
11443                 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");
11444
11445         i40e_clear_pxe_mode(hw);
11446         err = i40e_get_capabilities(pf);
11447         if (err)
11448                 goto err_adminq_setup;
11449
11450         err = i40e_sw_init(pf);
11451         if (err) {
11452                 dev_info(&pdev->dev, "sw_init failed: %d\n", err);
11453                 goto err_sw_init;
11454         }
11455
11456         err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
11457                                 hw->func_caps.num_rx_qp, 0, 0);
11458         if (err) {
11459                 dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
11460                 goto err_init_lan_hmc;
11461         }
11462
11463         err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
11464         if (err) {
11465                 dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
11466                 err = -ENOENT;
11467                 goto err_configure_lan_hmc;
11468         }
11469
11470         /* Disable LLDP for NICs that have firmware versions lower than v4.3.
11471          * Ignore error return codes because if it was already disabled via
11472          * hardware settings this will fail
11473          */
11474         if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
11475                 dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
11476                 i40e_aq_stop_lldp(hw, true, NULL);
11477         }
11478
11479         /* allow a platform config to override the HW addr */
11480         i40e_get_platform_mac_addr(pdev, pf);
11481
11482         if (!is_valid_ether_addr(hw->mac.addr)) {
11483                 dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
11484                 err = -EIO;
11485                 goto err_mac_addr;
11486         }
11487         dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
11488         ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
11489         i40e_get_port_mac_addr(hw, hw->mac.port_addr);
11490         if (is_valid_ether_addr(hw->mac.port_addr))
11491                 pf->hw_features |= I40E_HW_PORT_ID_VALID;
11492
11493         pci_set_drvdata(pdev, pf);
11494         pci_save_state(pdev);
11495 #ifdef CONFIG_I40E_DCB
11496         err = i40e_init_pf_dcb(pf);
11497         if (err) {
11498                 dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
11499                 pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
11500                 /* Continue without DCB enabled */
11501         }
11502 #endif /* CONFIG_I40E_DCB */
11503
11504         /* set up periodic task facility */
11505         setup_timer(&pf->service_timer, i40e_service_timer, (unsigned long)pf);
11506         pf->service_timer_period = HZ;
11507
11508         INIT_WORK(&pf->service_task, i40e_service_task);
11509         clear_bit(__I40E_SERVICE_SCHED, pf->state);
11510
11511         /* NVM bit on means WoL disabled for the port */
11512         i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
11513         if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
11514                 pf->wol_en = false;
11515         else
11516                 pf->wol_en = true;
11517         device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
11518
11519         /* set up the main switch operations */
11520         i40e_determine_queue_usage(pf);
11521         err = i40e_init_interrupt_scheme(pf);
11522         if (err)
11523                 goto err_switch_setup;
11524
11525         /* The number of VSIs reported by the FW is the minimum guaranteed
11526          * to us; HW supports far more and we share the remaining pool with
11527          * the other PFs. We allocate space for more than the guarantee with
11528          * the understanding that we might not get them all later.
11529          */
11530         if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
11531                 pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
11532         else
11533                 pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
11534
11535         /* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
11536         pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
11537                           GFP_KERNEL);
11538         if (!pf->vsi) {
11539                 err = -ENOMEM;
11540                 goto err_switch_setup;
11541         }
11542
11543 #ifdef CONFIG_PCI_IOV
11544         /* prep for VF support */
11545         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
11546             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11547             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
11548                 if (pci_num_vf(pdev))
11549                         pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
11550         }
11551 #endif
11552         err = i40e_setup_pf_switch(pf, false);
11553         if (err) {
11554                 dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
11555                 goto err_vsis;
11556         }
11557
11558         /* Make sure flow control is set according to current settings */
11559         err = i40e_set_fc(hw, &set_fc_aq_fail, true);
11560         if (set_fc_aq_fail & I40E_SET_FC_AQ_FAIL_GET)
11561                 dev_dbg(&pf->pdev->dev,
11562                         "Set fc with err %s aq_err %s on get_phy_cap\n",
11563                         i40e_stat_str(hw, err),
11564                         i40e_aq_str(hw, hw->aq.asq_last_status));
11565         if (set_fc_aq_fail & I40E_SET_FC_AQ_FAIL_SET)
11566                 dev_dbg(&pf->pdev->dev,
11567                         "Set fc with err %s aq_err %s on set_phy_config\n",
11568                         i40e_stat_str(hw, err),
11569                         i40e_aq_str(hw, hw->aq.asq_last_status));
11570         if (set_fc_aq_fail & I40E_SET_FC_AQ_FAIL_UPDATE)
11571                 dev_dbg(&pf->pdev->dev,
11572                         "Set fc with err %s aq_err %s on get_link_info\n",
11573                         i40e_stat_str(hw, err),
11574                         i40e_aq_str(hw, hw->aq.asq_last_status));
11575
11576         /* if FDIR VSI was set up, start it now */
11577         for (i = 0; i < pf->num_alloc_vsi; i++) {
11578                 if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
11579                         i40e_vsi_open(pf->vsi[i]);
11580                         break;
11581                 }
11582         }
11583
11584         /* The driver only wants link up/down and module qualification
11585          * reports from firmware.  Note the negative logic.
11586          */
11587         err = i40e_aq_set_phy_int_mask(&pf->hw,
11588                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
11589                                          I40E_AQ_EVENT_MEDIA_NA |
11590                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
11591         if (err)
11592                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
11593                          i40e_stat_str(&pf->hw, err),
11594                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11595
11596         /* Reconfigure hardware for allowing smaller MSS in the case
11597          * of TSO, so that we avoid the MDD being fired and causing
11598          * a reset in the case of small MSS+TSO.
11599          */
11600         val = rd32(hw, I40E_REG_MSS);
11601         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11602                 val &= ~I40E_REG_MSS_MIN_MASK;
11603                 val |= I40E_64BYTE_MSS;
11604                 wr32(hw, I40E_REG_MSS, val);
11605         }
11606
11607         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
11608                 msleep(75);
11609                 err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11610                 if (err)
11611                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
11612                                  i40e_stat_str(&pf->hw, err),
11613                                  i40e_aq_str(&pf->hw,
11614                                              pf->hw.aq.asq_last_status));
11615         }
11616         /* The main driver is (mostly) up and happy. We need to set this state
11617          * before setting up the misc vector or we get a race and the vector
11618          * ends up disabled forever.
11619          */
11620         clear_bit(__I40E_DOWN, pf->state);
11621
11622         /* In case of MSIX we are going to setup the misc vector right here
11623          * to handle admin queue events etc. In case of legacy and MSI
11624          * the misc functionality and queue processing is combined in
11625          * the same vector and that gets setup at open.
11626          */
11627         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11628                 err = i40e_setup_misc_vector(pf);
11629                 if (err) {
11630                         dev_info(&pdev->dev,
11631                                  "setup of misc vector failed: %d\n", err);
11632                         goto err_vsis;
11633                 }
11634         }
11635
11636 #ifdef CONFIG_PCI_IOV
11637         /* prep for VF support */
11638         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
11639             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11640             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
11641                 /* disable link interrupts for VFs */
11642                 val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
11643                 val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
11644                 wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
11645                 i40e_flush(hw);
11646
11647                 if (pci_num_vf(pdev)) {
11648                         dev_info(&pdev->dev,
11649                                  "Active VFs found, allocating resources.\n");
11650                         err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
11651                         if (err)
11652                                 dev_info(&pdev->dev,
11653                                          "Error %d allocating resources for existing VFs\n",
11654                                          err);
11655                 }
11656         }
11657 #endif /* CONFIG_PCI_IOV */
11658
11659         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11660                 pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
11661                                                       pf->num_iwarp_msix,
11662                                                       I40E_IWARP_IRQ_PILE_ID);
11663                 if (pf->iwarp_base_vector < 0) {
11664                         dev_info(&pdev->dev,
11665                                  "failed to get tracking for %d vectors for IWARP err=%d\n",
11666                                  pf->num_iwarp_msix, pf->iwarp_base_vector);
11667                         pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11668                 }
11669         }
11670
11671         i40e_dbg_pf_init(pf);
11672
11673         /* tell the firmware that we're starting */
11674         i40e_send_version(pf);
11675
11676         /* since everything's happy, start the service_task timer */
11677         mod_timer(&pf->service_timer,
11678                   round_jiffies(jiffies + pf->service_timer_period));
11679
11680         /* add this PF to client device list and launch a client service task */
11681         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11682                 err = i40e_lan_add_device(pf);
11683                 if (err)
11684                         dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
11685                                  err);
11686         }
11687
11688 #define PCI_SPEED_SIZE 8
11689 #define PCI_WIDTH_SIZE 8
11690         /* Devices on the IOSF bus do not have this information
11691          * and will report PCI Gen 1 x 1 by default so don't bother
11692          * checking them.
11693          */
11694         if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
11695                 char speed[PCI_SPEED_SIZE] = "Unknown";
11696                 char width[PCI_WIDTH_SIZE] = "Unknown";
11697
11698                 /* Get the negotiated link width and speed from PCI config
11699                  * space
11700                  */
11701                 pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
11702                                           &link_status);
11703
11704                 i40e_set_pci_config_data(hw, link_status);
11705
11706                 switch (hw->bus.speed) {
11707                 case i40e_bus_speed_8000:
11708                         strncpy(speed, "8.0", PCI_SPEED_SIZE); break;
11709                 case i40e_bus_speed_5000:
11710                         strncpy(speed, "5.0", PCI_SPEED_SIZE); break;
11711                 case i40e_bus_speed_2500:
11712                         strncpy(speed, "2.5", PCI_SPEED_SIZE); break;
11713                 default:
11714                         break;
11715                 }
11716                 switch (hw->bus.width) {
11717                 case i40e_bus_width_pcie_x8:
11718                         strncpy(width, "8", PCI_WIDTH_SIZE); break;
11719                 case i40e_bus_width_pcie_x4:
11720                         strncpy(width, "4", PCI_WIDTH_SIZE); break;
11721                 case i40e_bus_width_pcie_x2:
11722                         strncpy(width, "2", PCI_WIDTH_SIZE); break;
11723                 case i40e_bus_width_pcie_x1:
11724                         strncpy(width, "1", PCI_WIDTH_SIZE); break;
11725                 default:
11726                         break;
11727                 }
11728
11729                 dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
11730                          speed, width);
11731
11732                 if (hw->bus.width < i40e_bus_width_pcie_x8 ||
11733                     hw->bus.speed < i40e_bus_speed_8000) {
11734                         dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
11735                         dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
11736                 }
11737         }
11738
11739         /* get the requested speeds from the fw */
11740         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
11741         if (err)
11742                 dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
11743                         i40e_stat_str(&pf->hw, err),
11744                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11745         pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
11746
11747         /* get the supported phy types from the fw */
11748         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
11749         if (err)
11750                 dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
11751                         i40e_stat_str(&pf->hw, err),
11752                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11753
11754         /* Add a filter to drop all Flow control frames from any VSI from being
11755          * transmitted. By doing so we stop a malicious VF from sending out
11756          * PAUSE or PFC frames and potentially controlling traffic for other
11757          * PF/VF VSIs.
11758          * The FW can still send Flow control frames if enabled.
11759          */
11760         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11761                                                        pf->main_vsi_seid);
11762
11763         if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
11764                 (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
11765                 pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
11766         if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
11767                 pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
11768         /* print a string summarizing features */
11769         i40e_print_features(pf);
11770
11771         return 0;
11772
11773         /* Unwind what we've done if something failed in the setup */
11774 err_vsis:
11775         set_bit(__I40E_DOWN, pf->state);
11776         i40e_clear_interrupt_scheme(pf);
11777         kfree(pf->vsi);
11778 err_switch_setup:
11779         i40e_reset_interrupt_capability(pf);
11780         del_timer_sync(&pf->service_timer);
11781 err_mac_addr:
11782 err_configure_lan_hmc:
11783         (void)i40e_shutdown_lan_hmc(hw);
11784 err_init_lan_hmc:
11785         kfree(pf->qp_pile);
11786 err_sw_init:
11787 err_adminq_setup:
11788 err_pf_reset:
11789         iounmap(hw->hw_addr);
11790 err_ioremap:
11791         kfree(pf);
11792 err_pf_alloc:
11793         pci_disable_pcie_error_reporting(pdev);
11794         pci_release_mem_regions(pdev);
11795 err_pci_reg:
11796 err_dma:
11797         pci_disable_device(pdev);
11798         return err;
11799 }
11800
11801 /**
11802  * i40e_remove - Device removal routine
11803  * @pdev: PCI device information struct
11804  *
11805  * i40e_remove is called by the PCI subsystem to alert the driver
11806  * that is should release a PCI device.  This could be caused by a
11807  * Hot-Plug event, or because the driver is going to be removed from
11808  * memory.
11809  **/
11810 static void i40e_remove(struct pci_dev *pdev)
11811 {
11812         struct i40e_pf *pf = pci_get_drvdata(pdev);
11813         struct i40e_hw *hw = &pf->hw;
11814         i40e_status ret_code;
11815         int i;
11816
11817         i40e_dbg_pf_exit(pf);
11818
11819         i40e_ptp_stop(pf);
11820
11821         /* Disable RSS in hw */
11822         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
11823         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
11824
11825         /* no more scheduling of any task */
11826         set_bit(__I40E_SUSPENDED, pf->state);
11827         set_bit(__I40E_DOWN, pf->state);
11828         if (pf->service_timer.data)
11829                 del_timer_sync(&pf->service_timer);
11830         if (pf->service_task.func)
11831                 cancel_work_sync(&pf->service_task);
11832
11833         /* Client close must be called explicitly here because the timer
11834          * has been stopped.
11835          */
11836         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
11837
11838         if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
11839                 i40e_free_vfs(pf);
11840                 pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
11841         }
11842
11843         i40e_fdir_teardown(pf);
11844
11845         /* If there is a switch structure or any orphans, remove them.
11846          * This will leave only the PF's VSI remaining.
11847          */
11848         for (i = 0; i < I40E_MAX_VEB; i++) {
11849                 if (!pf->veb[i])
11850                         continue;
11851
11852                 if (pf->veb[i]->uplink_seid == pf->mac_seid ||
11853                     pf->veb[i]->uplink_seid == 0)
11854                         i40e_switch_branch_release(pf->veb[i]);
11855         }
11856
11857         /* Now we can shutdown the PF's VSI, just before we kill
11858          * adminq and hmc.
11859          */
11860         if (pf->vsi[pf->lan_vsi])
11861                 i40e_vsi_release(pf->vsi[pf->lan_vsi]);
11862
11863         /* remove attached clients */
11864         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11865                 ret_code = i40e_lan_del_device(pf);
11866                 if (ret_code)
11867                         dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
11868                                  ret_code);
11869         }
11870
11871         /* shutdown and destroy the HMC */
11872         if (hw->hmc.hmc_obj) {
11873                 ret_code = i40e_shutdown_lan_hmc(hw);
11874                 if (ret_code)
11875                         dev_warn(&pdev->dev,
11876                                  "Failed to destroy the HMC resources: %d\n",
11877                                  ret_code);
11878         }
11879
11880         /* shutdown the adminq */
11881         i40e_shutdown_adminq(hw);
11882
11883         /* destroy the locks only once, here */
11884         mutex_destroy(&hw->aq.arq_mutex);
11885         mutex_destroy(&hw->aq.asq_mutex);
11886
11887         /* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
11888         i40e_clear_interrupt_scheme(pf);
11889         for (i = 0; i < pf->num_alloc_vsi; i++) {
11890                 if (pf->vsi[i]) {
11891                         i40e_vsi_clear_rings(pf->vsi[i]);
11892                         i40e_vsi_clear(pf->vsi[i]);
11893                         pf->vsi[i] = NULL;
11894                 }
11895         }
11896
11897         for (i = 0; i < I40E_MAX_VEB; i++) {
11898                 kfree(pf->veb[i]);
11899                 pf->veb[i] = NULL;
11900         }
11901
11902         kfree(pf->qp_pile);
11903         kfree(pf->vsi);
11904
11905         iounmap(hw->hw_addr);
11906         kfree(pf);
11907         pci_release_mem_regions(pdev);
11908
11909         pci_disable_pcie_error_reporting(pdev);
11910         pci_disable_device(pdev);
11911 }
11912
11913 /**
11914  * i40e_pci_error_detected - warning that something funky happened in PCI land
11915  * @pdev: PCI device information struct
11916  *
11917  * Called to warn that something happened and the error handling steps
11918  * are in progress.  Allows the driver to quiesce things, be ready for
11919  * remediation.
11920  **/
11921 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
11922                                                 enum pci_channel_state error)
11923 {
11924         struct i40e_pf *pf = pci_get_drvdata(pdev);
11925
11926         dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
11927
11928         if (!pf) {
11929                 dev_info(&pdev->dev,
11930                          "Cannot recover - error happened during device probe\n");
11931                 return PCI_ERS_RESULT_DISCONNECT;
11932         }
11933
11934         /* shutdown all operations */
11935         if (!test_bit(__I40E_SUSPENDED, pf->state))
11936                 i40e_prep_for_reset(pf, false);
11937
11938         /* Request a slot reset */
11939         return PCI_ERS_RESULT_NEED_RESET;
11940 }
11941
11942 /**
11943  * i40e_pci_error_slot_reset - a PCI slot reset just happened
11944  * @pdev: PCI device information struct
11945  *
11946  * Called to find if the driver can work with the device now that
11947  * the pci slot has been reset.  If a basic connection seems good
11948  * (registers are readable and have sane content) then return a
11949  * happy little PCI_ERS_RESULT_xxx.
11950  **/
11951 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
11952 {
11953         struct i40e_pf *pf = pci_get_drvdata(pdev);
11954         pci_ers_result_t result;
11955         int err;
11956         u32 reg;
11957
11958         dev_dbg(&pdev->dev, "%s\n", __func__);
11959         if (pci_enable_device_mem(pdev)) {
11960                 dev_info(&pdev->dev,
11961                          "Cannot re-enable PCI device after reset.\n");
11962                 result = PCI_ERS_RESULT_DISCONNECT;
11963         } else {
11964                 pci_set_master(pdev);
11965                 pci_restore_state(pdev);
11966                 pci_save_state(pdev);
11967                 pci_wake_from_d3(pdev, false);
11968
11969                 reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
11970                 if (reg == 0)
11971                         result = PCI_ERS_RESULT_RECOVERED;
11972                 else
11973                         result = PCI_ERS_RESULT_DISCONNECT;
11974         }
11975
11976         err = pci_cleanup_aer_uncorrect_error_status(pdev);
11977         if (err) {
11978                 dev_info(&pdev->dev,
11979                          "pci_cleanup_aer_uncorrect_error_status failed 0x%0x\n",
11980                          err);
11981                 /* non-fatal, continue */
11982         }
11983
11984         return result;
11985 }
11986
11987 /**
11988  * i40e_pci_error_resume - restart operations after PCI error recovery
11989  * @pdev: PCI device information struct
11990  *
11991  * Called to allow the driver to bring things back up after PCI error
11992  * and/or reset recovery has finished.
11993  **/
11994 static void i40e_pci_error_resume(struct pci_dev *pdev)
11995 {
11996         struct i40e_pf *pf = pci_get_drvdata(pdev);
11997
11998         dev_dbg(&pdev->dev, "%s\n", __func__);
11999         if (test_bit(__I40E_SUSPENDED, pf->state))
12000                 return;
12001
12002         i40e_handle_reset_warning(pf, false);
12003 }
12004
12005 /**
12006  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
12007  * using the mac_address_write admin q function
12008  * @pf: pointer to i40e_pf struct
12009  **/
12010 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
12011 {
12012         struct i40e_hw *hw = &pf->hw;
12013         i40e_status ret;
12014         u8 mac_addr[6];
12015         u16 flags = 0;
12016
12017         /* Get current MAC address in case it's an LAA */
12018         if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
12019                 ether_addr_copy(mac_addr,
12020                                 pf->vsi[pf->lan_vsi]->netdev->dev_addr);
12021         } else {
12022                 dev_err(&pf->pdev->dev,
12023                         "Failed to retrieve MAC address; using default\n");
12024                 ether_addr_copy(mac_addr, hw->mac.addr);
12025         }
12026
12027         /* The FW expects the mac address write cmd to first be called with
12028          * one of these flags before calling it again with the multicast
12029          * enable flags.
12030          */
12031         flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
12032
12033         if (hw->func_caps.flex10_enable && hw->partition_id != 1)
12034                 flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
12035
12036         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
12037         if (ret) {
12038                 dev_err(&pf->pdev->dev,
12039                         "Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
12040                 return;
12041         }
12042
12043         flags = I40E_AQC_MC_MAG_EN
12044                         | I40E_AQC_WOL_PRESERVE_ON_PFR
12045                         | I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
12046         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
12047         if (ret)
12048                 dev_err(&pf->pdev->dev,
12049                         "Failed to enable Multicast Magic Packet wake up\n");
12050 }
12051
12052 /**
12053  * i40e_shutdown - PCI callback for shutting down
12054  * @pdev: PCI device information struct
12055  **/
12056 static void i40e_shutdown(struct pci_dev *pdev)
12057 {
12058         struct i40e_pf *pf = pci_get_drvdata(pdev);
12059         struct i40e_hw *hw = &pf->hw;
12060
12061         set_bit(__I40E_SUSPENDED, pf->state);
12062         set_bit(__I40E_DOWN, pf->state);
12063         rtnl_lock();
12064         i40e_prep_for_reset(pf, true);
12065         rtnl_unlock();
12066
12067         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
12068         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
12069
12070         del_timer_sync(&pf->service_timer);
12071         cancel_work_sync(&pf->service_task);
12072         i40e_fdir_teardown(pf);
12073
12074         /* Client close must be called explicitly here because the timer
12075          * has been stopped.
12076          */
12077         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
12078
12079         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
12080                 i40e_enable_mc_magic_wake(pf);
12081
12082         i40e_prep_for_reset(pf, false);
12083
12084         wr32(hw, I40E_PFPM_APM,
12085              (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
12086         wr32(hw, I40E_PFPM_WUFC,
12087              (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
12088
12089         i40e_clear_interrupt_scheme(pf);
12090
12091         if (system_state == SYSTEM_POWER_OFF) {
12092                 pci_wake_from_d3(pdev, pf->wol_en);
12093                 pci_set_power_state(pdev, PCI_D3hot);
12094         }
12095 }
12096
12097 #ifdef CONFIG_PM
12098 /**
12099  * i40e_suspend - PCI callback for moving to D3
12100  * @pdev: PCI device information struct
12101  **/
12102 static int i40e_suspend(struct pci_dev *pdev, pm_message_t state)
12103 {
12104         struct i40e_pf *pf = pci_get_drvdata(pdev);
12105         struct i40e_hw *hw = &pf->hw;
12106         int retval = 0;
12107
12108         set_bit(__I40E_SUSPENDED, pf->state);
12109         set_bit(__I40E_DOWN, pf->state);
12110
12111         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
12112                 i40e_enable_mc_magic_wake(pf);
12113
12114         i40e_prep_for_reset(pf, false);
12115
12116         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
12117         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
12118
12119         i40e_stop_misc_vector(pf);
12120         if (pf->msix_entries) {
12121                 synchronize_irq(pf->msix_entries[0].vector);
12122                 free_irq(pf->msix_entries[0].vector, pf);
12123         }
12124         retval = pci_save_state(pdev);
12125         if (retval)
12126                 return retval;
12127
12128         pci_wake_from_d3(pdev, pf->wol_en);
12129         pci_set_power_state(pdev, PCI_D3hot);
12130
12131         return retval;
12132 }
12133
12134 /**
12135  * i40e_resume - PCI callback for waking up from D3
12136  * @pdev: PCI device information struct
12137  **/
12138 static int i40e_resume(struct pci_dev *pdev)
12139 {
12140         struct i40e_pf *pf = pci_get_drvdata(pdev);
12141         u32 err;
12142
12143         pci_set_power_state(pdev, PCI_D0);
12144         pci_restore_state(pdev);
12145         /* pci_restore_state() clears dev->state_saves, so
12146          * call pci_save_state() again to restore it.
12147          */
12148         pci_save_state(pdev);
12149
12150         err = pci_enable_device_mem(pdev);
12151         if (err) {
12152                 dev_err(&pdev->dev, "Cannot enable PCI device from suspend\n");
12153                 return err;
12154         }
12155         pci_set_master(pdev);
12156
12157         /* no wakeup events while running */
12158         pci_wake_from_d3(pdev, false);
12159
12160         /* handling the reset will rebuild the device state */
12161         if (test_and_clear_bit(__I40E_SUSPENDED, pf->state)) {
12162                 clear_bit(__I40E_DOWN, pf->state);
12163                 if (pf->msix_entries) {
12164                         err = request_irq(pf->msix_entries[0].vector,
12165                                           i40e_intr, 0, pf->int_name, pf);
12166                         if (err) {
12167                                 dev_err(&pf->pdev->dev,
12168                                         "request_irq for %s failed: %d\n",
12169                                         pf->int_name, err);
12170                         }
12171                 }
12172                 i40e_reset_and_rebuild(pf, false, false);
12173         }
12174
12175         return 0;
12176 }
12177
12178 #endif
12179 static const struct pci_error_handlers i40e_err_handler = {
12180         .error_detected = i40e_pci_error_detected,
12181         .slot_reset = i40e_pci_error_slot_reset,
12182         .resume = i40e_pci_error_resume,
12183 };
12184
12185 static struct pci_driver i40e_driver = {
12186         .name     = i40e_driver_name,
12187         .id_table = i40e_pci_tbl,
12188         .probe    = i40e_probe,
12189         .remove   = i40e_remove,
12190 #ifdef CONFIG_PM
12191         .suspend  = i40e_suspend,
12192         .resume   = i40e_resume,
12193 #endif
12194         .shutdown = i40e_shutdown,
12195         .err_handler = &i40e_err_handler,
12196         .sriov_configure = i40e_pci_sriov_configure,
12197 };
12198
12199 /**
12200  * i40e_init_module - Driver registration routine
12201  *
12202  * i40e_init_module is the first routine called when the driver is
12203  * loaded. All it does is register with the PCI subsystem.
12204  **/
12205 static int __init i40e_init_module(void)
12206 {
12207         pr_info("%s: %s - version %s\n", i40e_driver_name,
12208                 i40e_driver_string, i40e_driver_version_str);
12209         pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
12210
12211         /* There is no need to throttle the number of active tasks because
12212          * each device limits its own task using a state bit for scheduling
12213          * the service task, and the device tasks do not interfere with each
12214          * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
12215          * since we need to be able to guarantee forward progress even under
12216          * memory pressure.
12217          */
12218         i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
12219         if (!i40e_wq) {
12220                 pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
12221                 return -ENOMEM;
12222         }
12223
12224         i40e_dbg_init();
12225         return pci_register_driver(&i40e_driver);
12226 }
12227 module_init(i40e_init_module);
12228
12229 /**
12230  * i40e_exit_module - Driver exit cleanup routine
12231  *
12232  * i40e_exit_module is called just before the driver is removed
12233  * from memory.
12234  **/
12235 static void __exit i40e_exit_module(void)
12236 {
12237         pci_unregister_driver(&i40e_driver);
12238         destroy_workqueue(i40e_wq);
12239         i40e_dbg_exit();
12240 }
12241 module_exit(i40e_exit_module);