GNU Linux-libre 4.14.259-gnu1
[releases.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                     !test_bit(__I40E_VSI_RELEASING, pf->vsi[v]->state)) {
2420                         int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2421
2422                         if (ret) {
2423                                 /* come back and try again later */
2424                                 pf->flags |= I40E_FLAG_FILTER_SYNC;
2425                                 break;
2426                         }
2427                 }
2428         }
2429 }
2430
2431 /**
2432  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2433  * @vsi: the vsi
2434  **/
2435 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2436 {
2437         if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2438                 return I40E_RXBUFFER_2048;
2439         else
2440                 return I40E_RXBUFFER_3072;
2441 }
2442
2443 /**
2444  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2445  * @netdev: network interface device structure
2446  * @new_mtu: new value for maximum frame size
2447  *
2448  * Returns 0 on success, negative on failure
2449  **/
2450 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2451 {
2452         struct i40e_netdev_priv *np = netdev_priv(netdev);
2453         struct i40e_vsi *vsi = np->vsi;
2454         struct i40e_pf *pf = vsi->back;
2455
2456         if (i40e_enabled_xdp_vsi(vsi)) {
2457                 int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2458
2459                 if (frame_size > i40e_max_xdp_frame_size(vsi))
2460                         return -EINVAL;
2461         }
2462
2463         netdev_info(netdev, "changing MTU from %d to %d\n",
2464                     netdev->mtu, new_mtu);
2465         netdev->mtu = new_mtu;
2466         if (netif_running(netdev))
2467                 i40e_vsi_reinit_locked(vsi);
2468         pf->flags |= (I40E_FLAG_SERVICE_CLIENT_REQUESTED |
2469                       I40E_FLAG_CLIENT_L2_CHANGE);
2470         return 0;
2471 }
2472
2473 /**
2474  * i40e_ioctl - Access the hwtstamp interface
2475  * @netdev: network interface device structure
2476  * @ifr: interface request data
2477  * @cmd: ioctl command
2478  **/
2479 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2480 {
2481         struct i40e_netdev_priv *np = netdev_priv(netdev);
2482         struct i40e_pf *pf = np->vsi->back;
2483
2484         switch (cmd) {
2485         case SIOCGHWTSTAMP:
2486                 return i40e_ptp_get_ts_config(pf, ifr);
2487         case SIOCSHWTSTAMP:
2488                 return i40e_ptp_set_ts_config(pf, ifr);
2489         default:
2490                 return -EOPNOTSUPP;
2491         }
2492 }
2493
2494 /**
2495  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2496  * @vsi: the vsi being adjusted
2497  **/
2498 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2499 {
2500         struct i40e_vsi_context ctxt;
2501         i40e_status ret;
2502
2503         /* Don't modify stripping options if a port VLAN is active */
2504         if (vsi->info.pvid)
2505                 return;
2506
2507         if ((vsi->info.valid_sections &
2508              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2509             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2510                 return;  /* already enabled */
2511
2512         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2513         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2514                                     I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2515
2516         ctxt.seid = vsi->seid;
2517         ctxt.info = vsi->info;
2518         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2519         if (ret) {
2520                 dev_info(&vsi->back->pdev->dev,
2521                          "update vlan stripping failed, err %s aq_err %s\n",
2522                          i40e_stat_str(&vsi->back->hw, ret),
2523                          i40e_aq_str(&vsi->back->hw,
2524                                      vsi->back->hw.aq.asq_last_status));
2525         }
2526 }
2527
2528 /**
2529  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2530  * @vsi: the vsi being adjusted
2531  **/
2532 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2533 {
2534         struct i40e_vsi_context ctxt;
2535         i40e_status ret;
2536
2537         /* Don't modify stripping options if a port VLAN is active */
2538         if (vsi->info.pvid)
2539                 return;
2540
2541         if ((vsi->info.valid_sections &
2542              cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2543             ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
2544              I40E_AQ_VSI_PVLAN_EMOD_MASK))
2545                 return;  /* already disabled */
2546
2547         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2548         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2549                                     I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2550
2551         ctxt.seid = vsi->seid;
2552         ctxt.info = vsi->info;
2553         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2554         if (ret) {
2555                 dev_info(&vsi->back->pdev->dev,
2556                          "update vlan stripping failed, err %s aq_err %s\n",
2557                          i40e_stat_str(&vsi->back->hw, ret),
2558                          i40e_aq_str(&vsi->back->hw,
2559                                      vsi->back->hw.aq.asq_last_status));
2560         }
2561 }
2562
2563 /**
2564  * i40e_vlan_rx_register - Setup or shutdown vlan offload
2565  * @netdev: network interface to be adjusted
2566  * @features: netdev features to test if VLAN offload is enabled or not
2567  **/
2568 static void i40e_vlan_rx_register(struct net_device *netdev, u32 features)
2569 {
2570         struct i40e_netdev_priv *np = netdev_priv(netdev);
2571         struct i40e_vsi *vsi = np->vsi;
2572
2573         if (features & NETIF_F_HW_VLAN_CTAG_RX)
2574                 i40e_vlan_stripping_enable(vsi);
2575         else
2576                 i40e_vlan_stripping_disable(vsi);
2577 }
2578
2579 /**
2580  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
2581  * @vsi: the vsi being configured
2582  * @vid: vlan id to be added (0 = untagged only , -1 = any)
2583  *
2584  * This is a helper function for adding a new MAC/VLAN filter with the
2585  * specified VLAN for each existing MAC address already in the hash table.
2586  * This function does *not* perform any accounting to update filters based on
2587  * VLAN mode.
2588  *
2589  * NOTE: this function expects to be called while under the
2590  * mac_filter_hash_lock
2591  **/
2592 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2593 {
2594         struct i40e_mac_filter *f, *add_f;
2595         struct hlist_node *h;
2596         int bkt;
2597
2598         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2599                 if (f->state == I40E_FILTER_REMOVE)
2600                         continue;
2601                 add_f = i40e_add_filter(vsi, f->macaddr, vid);
2602                 if (!add_f) {
2603                         dev_info(&vsi->back->pdev->dev,
2604                                  "Could not add vlan filter %d for %pM\n",
2605                                  vid, f->macaddr);
2606                         return -ENOMEM;
2607                 }
2608         }
2609
2610         return 0;
2611 }
2612
2613 /**
2614  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
2615  * @vsi: the VSI being configured
2616  * @vid: VLAN id to be added
2617  **/
2618 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
2619 {
2620         int err;
2621
2622         if (vsi->info.pvid)
2623                 return -EINVAL;
2624
2625         /* The network stack will attempt to add VID=0, with the intention to
2626          * receive priority tagged packets with a VLAN of 0. Our HW receives
2627          * these packets by default when configured to receive untagged
2628          * packets, so we don't need to add a filter for this case.
2629          * Additionally, HW interprets adding a VID=0 filter as meaning to
2630          * receive *only* tagged traffic and stops receiving untagged traffic.
2631          * Thus, we do not want to actually add a filter for VID=0
2632          */
2633         if (!vid)
2634                 return 0;
2635
2636         /* Locked once because all functions invoked below iterates list*/
2637         spin_lock_bh(&vsi->mac_filter_hash_lock);
2638         err = i40e_add_vlan_all_mac(vsi, vid);
2639         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2640         if (err)
2641                 return err;
2642
2643         /* schedule our worker thread which will take care of
2644          * applying the new filter changes
2645          */
2646         i40e_service_event_schedule(vsi->back);
2647         return 0;
2648 }
2649
2650 /**
2651  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
2652  * @vsi: the vsi being configured
2653  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
2654  *
2655  * This function should be used to remove all VLAN filters which match the
2656  * given VID. It does not schedule the service event and does not take the
2657  * mac_filter_hash_lock so it may be combined with other operations under
2658  * a single invocation of the mac_filter_hash_lock.
2659  *
2660  * NOTE: this function expects to be called while under the
2661  * mac_filter_hash_lock
2662  */
2663 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2664 {
2665         struct i40e_mac_filter *f;
2666         struct hlist_node *h;
2667         int bkt;
2668
2669         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2670                 if (f->vlan == vid)
2671                         __i40e_del_filter(vsi, f);
2672         }
2673 }
2674
2675 /**
2676  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
2677  * @vsi: the VSI being configured
2678  * @vid: VLAN id to be removed
2679  **/
2680 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
2681 {
2682         if (!vid || vsi->info.pvid)
2683                 return;
2684
2685         spin_lock_bh(&vsi->mac_filter_hash_lock);
2686         i40e_rm_vlan_all_mac(vsi, vid);
2687         spin_unlock_bh(&vsi->mac_filter_hash_lock);
2688
2689         /* schedule our worker thread which will take care of
2690          * applying the new filter changes
2691          */
2692         i40e_service_event_schedule(vsi->back);
2693 }
2694
2695 /**
2696  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
2697  * @netdev: network interface to be adjusted
2698  * @vid: vlan id to be added
2699  *
2700  * net_device_ops implementation for adding vlan ids
2701  **/
2702 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
2703                                 __always_unused __be16 proto, u16 vid)
2704 {
2705         struct i40e_netdev_priv *np = netdev_priv(netdev);
2706         struct i40e_vsi *vsi = np->vsi;
2707         int ret = 0;
2708
2709         if (vid >= VLAN_N_VID)
2710                 return -EINVAL;
2711
2712         ret = i40e_vsi_add_vlan(vsi, vid);
2713         if (!ret)
2714                 set_bit(vid, vsi->active_vlans);
2715
2716         return ret;
2717 }
2718
2719 /**
2720  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
2721  * @netdev: network interface to be adjusted
2722  * @vid: vlan id to be removed
2723  *
2724  * net_device_ops implementation for removing vlan ids
2725  **/
2726 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
2727                                  __always_unused __be16 proto, u16 vid)
2728 {
2729         struct i40e_netdev_priv *np = netdev_priv(netdev);
2730         struct i40e_vsi *vsi = np->vsi;
2731
2732         /* return code is ignored as there is nothing a user
2733          * can do about failure to remove and a log message was
2734          * already printed from the other function
2735          */
2736         i40e_vsi_kill_vlan(vsi, vid);
2737
2738         clear_bit(vid, vsi->active_vlans);
2739
2740         return 0;
2741 }
2742
2743 /**
2744  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
2745  * @vsi: the vsi being brought back up
2746  **/
2747 static void i40e_restore_vlan(struct i40e_vsi *vsi)
2748 {
2749         u16 vid;
2750
2751         if (!vsi->netdev)
2752                 return;
2753
2754         i40e_vlan_rx_register(vsi->netdev, vsi->netdev->features);
2755
2756         for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
2757                 i40e_vlan_rx_add_vid(vsi->netdev, htons(ETH_P_8021Q),
2758                                      vid);
2759 }
2760
2761 /**
2762  * i40e_vsi_add_pvid - Add pvid for the VSI
2763  * @vsi: the vsi being adjusted
2764  * @vid: the vlan id to set as a PVID
2765  **/
2766 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
2767 {
2768         struct i40e_vsi_context ctxt;
2769         i40e_status ret;
2770
2771         vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2772         vsi->info.pvid = cpu_to_le16(vid);
2773         vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
2774                                     I40E_AQ_VSI_PVLAN_INSERT_PVID |
2775                                     I40E_AQ_VSI_PVLAN_EMOD_STR;
2776
2777         ctxt.seid = vsi->seid;
2778         ctxt.info = vsi->info;
2779         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2780         if (ret) {
2781                 dev_info(&vsi->back->pdev->dev,
2782                          "add pvid failed, err %s aq_err %s\n",
2783                          i40e_stat_str(&vsi->back->hw, ret),
2784                          i40e_aq_str(&vsi->back->hw,
2785                                      vsi->back->hw.aq.asq_last_status));
2786                 return -ENOENT;
2787         }
2788
2789         return 0;
2790 }
2791
2792 /**
2793  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
2794  * @vsi: the vsi being adjusted
2795  *
2796  * Just use the vlan_rx_register() service to put it back to normal
2797  **/
2798 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
2799 {
2800         i40e_vlan_stripping_disable(vsi);
2801
2802         vsi->info.pvid = 0;
2803 }
2804
2805 /**
2806  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
2807  * @vsi: ptr to the VSI
2808  *
2809  * If this function returns with an error, then it's possible one or
2810  * more of the rings is populated (while the rest are not).  It is the
2811  * callers duty to clean those orphaned rings.
2812  *
2813  * Return 0 on success, negative on failure
2814  **/
2815 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
2816 {
2817         int i, err = 0;
2818
2819         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
2820                 err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
2821
2822         if (!i40e_enabled_xdp_vsi(vsi))
2823                 return err;
2824
2825         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
2826                 err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
2827
2828         return err;
2829 }
2830
2831 /**
2832  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
2833  * @vsi: ptr to the VSI
2834  *
2835  * Free VSI's transmit software resources
2836  **/
2837 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
2838 {
2839         int i;
2840
2841         if (vsi->tx_rings) {
2842                 for (i = 0; i < vsi->num_queue_pairs; i++)
2843                         if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
2844                                 i40e_free_tx_resources(vsi->tx_rings[i]);
2845         }
2846
2847         if (vsi->xdp_rings) {
2848                 for (i = 0; i < vsi->num_queue_pairs; i++)
2849                         if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
2850                                 i40e_free_tx_resources(vsi->xdp_rings[i]);
2851         }
2852 }
2853
2854 /**
2855  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
2856  * @vsi: ptr to the VSI
2857  *
2858  * If this function returns with an error, then it's possible one or
2859  * more of the rings is populated (while the rest are not).  It is the
2860  * callers duty to clean those orphaned rings.
2861  *
2862  * Return 0 on success, negative on failure
2863  **/
2864 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
2865 {
2866         int i, err = 0;
2867
2868         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
2869                 err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
2870         return err;
2871 }
2872
2873 /**
2874  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
2875  * @vsi: ptr to the VSI
2876  *
2877  * Free all receive software resources
2878  **/
2879 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
2880 {
2881         int i;
2882
2883         if (!vsi->rx_rings)
2884                 return;
2885
2886         for (i = 0; i < vsi->num_queue_pairs; i++)
2887                 if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
2888                         i40e_free_rx_resources(vsi->rx_rings[i]);
2889 }
2890
2891 /**
2892  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
2893  * @ring: The Tx ring to configure
2894  *
2895  * This enables/disables XPS for a given Tx descriptor ring
2896  * based on the TCs enabled for the VSI that ring belongs to.
2897  **/
2898 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
2899 {
2900         struct i40e_vsi *vsi = ring->vsi;
2901         int cpu;
2902
2903         if (!ring->q_vector || !ring->netdev)
2904                 return;
2905
2906         if ((vsi->tc_config.numtc <= 1) &&
2907             !test_and_set_bit(__I40E_TX_XPS_INIT_DONE, &ring->state)) {
2908                 cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
2909                 netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
2910                                     ring->queue_index);
2911         }
2912
2913         /* schedule our worker thread which will take care of
2914          * applying the new filter changes
2915          */
2916         i40e_service_event_schedule(vsi->back);
2917 }
2918
2919 /**
2920  * i40e_configure_tx_ring - Configure a transmit ring context and rest
2921  * @ring: The Tx ring to configure
2922  *
2923  * Configure the Tx descriptor ring in the HMC context.
2924  **/
2925 static int i40e_configure_tx_ring(struct i40e_ring *ring)
2926 {
2927         struct i40e_vsi *vsi = ring->vsi;
2928         u16 pf_q = vsi->base_queue + ring->queue_index;
2929         struct i40e_hw *hw = &vsi->back->hw;
2930         struct i40e_hmc_obj_txq tx_ctx;
2931         i40e_status err = 0;
2932         u32 qtx_ctl = 0;
2933
2934         /* some ATR related tx ring init */
2935         if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
2936                 ring->atr_sample_rate = vsi->back->atr_sample_rate;
2937                 ring->atr_count = 0;
2938         } else {
2939                 ring->atr_sample_rate = 0;
2940         }
2941
2942         /* configure XPS */
2943         i40e_config_xps_tx_ring(ring);
2944
2945         /* clear the context structure first */
2946         memset(&tx_ctx, 0, sizeof(tx_ctx));
2947
2948         tx_ctx.new_context = 1;
2949         tx_ctx.base = (ring->dma / 128);
2950         tx_ctx.qlen = ring->count;
2951         tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
2952                                                I40E_FLAG_FD_ATR_ENABLED));
2953         tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
2954         /* FDIR VSI tx ring can still use RS bit and writebacks */
2955         if (vsi->type != I40E_VSI_FDIR)
2956                 tx_ctx.head_wb_ena = 1;
2957         tx_ctx.head_wb_addr = ring->dma +
2958                               (ring->count * sizeof(struct i40e_tx_desc));
2959
2960         /* As part of VSI creation/update, FW allocates certain
2961          * Tx arbitration queue sets for each TC enabled for
2962          * the VSI. The FW returns the handles to these queue
2963          * sets as part of the response buffer to Add VSI,
2964          * Update VSI, etc. AQ commands. It is expected that
2965          * these queue set handles be associated with the Tx
2966          * queues by the driver as part of the TX queue context
2967          * initialization. This has to be done regardless of
2968          * DCB as by default everything is mapped to TC0.
2969          */
2970         tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
2971         tx_ctx.rdylist_act = 0;
2972
2973         /* clear the context in the HMC */
2974         err = i40e_clear_lan_tx_queue_context(hw, pf_q);
2975         if (err) {
2976                 dev_info(&vsi->back->pdev->dev,
2977                          "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
2978                          ring->queue_index, pf_q, err);
2979                 return -ENOMEM;
2980         }
2981
2982         /* set the context in the HMC */
2983         err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
2984         if (err) {
2985                 dev_info(&vsi->back->pdev->dev,
2986                          "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
2987                          ring->queue_index, pf_q, err);
2988                 return -ENOMEM;
2989         }
2990
2991         /* Now associate this queue with this PCI function */
2992         if (vsi->type == I40E_VSI_VMDQ2) {
2993                 qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
2994                 qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
2995                            I40E_QTX_CTL_VFVM_INDX_MASK;
2996         } else {
2997                 qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
2998         }
2999
3000         qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3001                     I40E_QTX_CTL_PF_INDX_MASK);
3002         wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3003         i40e_flush(hw);
3004
3005         /* cache tail off for easier writes later */
3006         ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3007
3008         return 0;
3009 }
3010
3011 /**
3012  * i40e_configure_rx_ring - Configure a receive ring context
3013  * @ring: The Rx ring to configure
3014  *
3015  * Configure the Rx descriptor ring in the HMC context.
3016  **/
3017 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3018 {
3019         struct i40e_vsi *vsi = ring->vsi;
3020         u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3021         u16 pf_q = vsi->base_queue + ring->queue_index;
3022         struct i40e_hw *hw = &vsi->back->hw;
3023         struct i40e_hmc_obj_rxq rx_ctx;
3024         i40e_status err = 0;
3025
3026         ring->state = 0;
3027
3028         /* clear the context structure first */
3029         memset(&rx_ctx, 0, sizeof(rx_ctx));
3030
3031         ring->rx_buf_len = vsi->rx_buf_len;
3032
3033         rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3034                                     BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3035
3036         rx_ctx.base = (ring->dma / 128);
3037         rx_ctx.qlen = ring->count;
3038
3039         /* use 32 byte descriptors */
3040         rx_ctx.dsize = 1;
3041
3042         /* descriptor type is always zero
3043          * rx_ctx.dtype = 0;
3044          */
3045         rx_ctx.hsplit_0 = 0;
3046
3047         rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3048         if (hw->revision_id == 0)
3049                 rx_ctx.lrxqthresh = 0;
3050         else
3051                 rx_ctx.lrxqthresh = 2;
3052         rx_ctx.crcstrip = 1;
3053         rx_ctx.l2tsel = 1;
3054         /* this controls whether VLAN is stripped from inner headers */
3055         rx_ctx.showiv = 0;
3056         /* set the prefena field to 1 because the manual says to */
3057         rx_ctx.prefena = 1;
3058
3059         /* clear the context in the HMC */
3060         err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3061         if (err) {
3062                 dev_info(&vsi->back->pdev->dev,
3063                          "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3064                          ring->queue_index, pf_q, err);
3065                 return -ENOMEM;
3066         }
3067
3068         /* set the context in the HMC */
3069         err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3070         if (err) {
3071                 dev_info(&vsi->back->pdev->dev,
3072                          "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3073                          ring->queue_index, pf_q, err);
3074                 return -ENOMEM;
3075         }
3076
3077         /* configure Rx buffer alignment */
3078         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3079                 clear_ring_build_skb_enabled(ring);
3080         else
3081                 set_ring_build_skb_enabled(ring);
3082
3083         /* cache tail for quicker writes, and clear the reg before use */
3084         ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3085         writel(0, ring->tail);
3086
3087         i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3088
3089         return 0;
3090 }
3091
3092 /**
3093  * i40e_vsi_configure_tx - Configure the VSI for Tx
3094  * @vsi: VSI structure describing this set of rings and resources
3095  *
3096  * Configure the Tx VSI for operation.
3097  **/
3098 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3099 {
3100         int err = 0;
3101         u16 i;
3102
3103         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3104                 err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3105
3106         if (!i40e_enabled_xdp_vsi(vsi))
3107                 return err;
3108
3109         for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3110                 err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3111
3112         return err;
3113 }
3114
3115 /**
3116  * i40e_vsi_configure_rx - Configure the VSI for Rx
3117  * @vsi: the VSI being configured
3118  *
3119  * Configure the Rx VSI for operation.
3120  **/
3121 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3122 {
3123         int err = 0;
3124         u16 i;
3125
3126         if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3127                 vsi->max_frame = I40E_MAX_RXBUFFER;
3128                 vsi->rx_buf_len = I40E_RXBUFFER_2048;
3129 #if (PAGE_SIZE < 8192)
3130         } else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3131                    (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3132                 vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3133                 vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3134 #endif
3135         } else {
3136                 vsi->max_frame = I40E_MAX_RXBUFFER;
3137                 vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3138                                                        I40E_RXBUFFER_2048;
3139         }
3140
3141         /* set up individual rings */
3142         for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3143                 err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3144
3145         return err;
3146 }
3147
3148 /**
3149  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3150  * @vsi: ptr to the VSI
3151  **/
3152 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3153 {
3154         struct i40e_ring *tx_ring, *rx_ring;
3155         u16 qoffset, qcount;
3156         int i, n;
3157
3158         if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3159                 /* Reset the TC information */
3160                 for (i = 0; i < vsi->num_queue_pairs; i++) {
3161                         rx_ring = vsi->rx_rings[i];
3162                         tx_ring = vsi->tx_rings[i];
3163                         rx_ring->dcb_tc = 0;
3164                         tx_ring->dcb_tc = 0;
3165                 }
3166         }
3167
3168         for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3169                 if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3170                         continue;
3171
3172                 qoffset = vsi->tc_config.tc_info[n].qoffset;
3173                 qcount = vsi->tc_config.tc_info[n].qcount;
3174                 for (i = qoffset; i < (qoffset + qcount); i++) {
3175                         rx_ring = vsi->rx_rings[i];
3176                         tx_ring = vsi->tx_rings[i];
3177                         rx_ring->dcb_tc = n;
3178                         tx_ring->dcb_tc = n;
3179                 }
3180         }
3181 }
3182
3183 /**
3184  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3185  * @vsi: ptr to the VSI
3186  **/
3187 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3188 {
3189         if (vsi->netdev)
3190                 i40e_set_rx_mode(vsi->netdev);
3191 }
3192
3193 /**
3194  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3195  * @vsi: Pointer to the targeted VSI
3196  *
3197  * This function replays the hlist on the hw where all the SB Flow Director
3198  * filters were saved.
3199  **/
3200 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3201 {
3202         struct i40e_fdir_filter *filter;
3203         struct i40e_pf *pf = vsi->back;
3204         struct hlist_node *node;
3205
3206         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3207                 return;
3208
3209         /* Reset FDir counters as we're replaying all existing filters */
3210         pf->fd_tcp4_filter_cnt = 0;
3211         pf->fd_udp4_filter_cnt = 0;
3212         pf->fd_sctp4_filter_cnt = 0;
3213         pf->fd_ip4_filter_cnt = 0;
3214
3215         hlist_for_each_entry_safe(filter, node,
3216                                   &pf->fdir_filter_list, fdir_node) {
3217                 i40e_add_del_fdir(vsi, filter, true);
3218         }
3219 }
3220
3221 /**
3222  * i40e_vsi_configure - Set up the VSI for action
3223  * @vsi: the VSI being configured
3224  **/
3225 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3226 {
3227         int err;
3228
3229         i40e_set_vsi_rx_mode(vsi);
3230         i40e_restore_vlan(vsi);
3231         i40e_vsi_config_dcb_rings(vsi);
3232         err = i40e_vsi_configure_tx(vsi);
3233         if (!err)
3234                 err = i40e_vsi_configure_rx(vsi);
3235
3236         return err;
3237 }
3238
3239 /**
3240  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3241  * @vsi: the VSI being configured
3242  **/
3243 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3244 {
3245         bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3246         struct i40e_pf *pf = vsi->back;
3247         struct i40e_hw *hw = &pf->hw;
3248         u16 vector;
3249         int i, q;
3250         u32 qp;
3251
3252         /* The interrupt indexing is offset by 1 in the PFINT_ITRn
3253          * and PFINT_LNKLSTn registers, e.g.:
3254          *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3255          */
3256         qp = vsi->base_queue;
3257         vector = vsi->base_vector;
3258         for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3259                 struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3260
3261                 q_vector->itr_countdown = ITR_COUNTDOWN_START;
3262                 q_vector->rx.itr = ITR_TO_REG(vsi->rx_rings[i]->rx_itr_setting);
3263                 q_vector->rx.latency_range = I40E_LOW_LATENCY;
3264                 wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3265                      q_vector->rx.itr);
3266                 q_vector->tx.itr = ITR_TO_REG(vsi->tx_rings[i]->tx_itr_setting);
3267                 q_vector->tx.latency_range = I40E_LOW_LATENCY;
3268                 wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3269                      q_vector->tx.itr);
3270                 wr32(hw, I40E_PFINT_RATEN(vector - 1),
3271                      i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3272
3273                 /* Linked list for the queuepairs assigned to this vector */
3274                 wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3275                 for (q = 0; q < q_vector->num_ringpairs; q++) {
3276                         u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3277                         u32 val;
3278
3279                         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3280                               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3281                               (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3282                               (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3283                               (I40E_QUEUE_TYPE_TX <<
3284                                I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3285
3286                         wr32(hw, I40E_QINT_RQCTL(qp), val);
3287
3288                         if (has_xdp) {
3289                                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3290                                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3291                                       (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3292                                       (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3293                                       (I40E_QUEUE_TYPE_TX <<
3294                                        I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3295
3296                                 wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3297                         }
3298
3299                         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3300                               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3301                               (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3302                               ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3303                               (I40E_QUEUE_TYPE_RX <<
3304                                I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3305
3306                         /* Terminate the linked list */
3307                         if (q == (q_vector->num_ringpairs - 1))
3308                                 val |= (I40E_QUEUE_END_OF_LIST <<
3309                                         I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3310
3311                         wr32(hw, I40E_QINT_TQCTL(qp), val);
3312                         qp++;
3313                 }
3314         }
3315
3316         i40e_flush(hw);
3317 }
3318
3319 /**
3320  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3321  * @hw: ptr to the hardware info
3322  **/
3323 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3324 {
3325         struct i40e_hw *hw = &pf->hw;
3326         u32 val;
3327
3328         /* clear things first */
3329         wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3330         rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3331
3332         val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3333               I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3334               I40E_PFINT_ICR0_ENA_GRST_MASK          |
3335               I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3336               I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3337               I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3338               I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3339               I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3340
3341         if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3342                 val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3343
3344         if (pf->flags & I40E_FLAG_PTP)
3345                 val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3346
3347         wr32(hw, I40E_PFINT_ICR0_ENA, val);
3348
3349         /* SW_ITR_IDX = 0, but don't change INTENA */
3350         wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3351                                         I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3352
3353         /* OTHER_ITR_IDX = 0 */
3354         wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3355 }
3356
3357 /**
3358  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3359  * @vsi: the VSI being configured
3360  **/
3361 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3362 {
3363         u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3364         struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3365         struct i40e_pf *pf = vsi->back;
3366         struct i40e_hw *hw = &pf->hw;
3367         u32 val;
3368
3369         /* set the ITR configuration */
3370         q_vector->itr_countdown = ITR_COUNTDOWN_START;
3371         q_vector->rx.itr = ITR_TO_REG(vsi->rx_rings[0]->rx_itr_setting);
3372         q_vector->rx.latency_range = I40E_LOW_LATENCY;
3373         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.itr);
3374         q_vector->tx.itr = ITR_TO_REG(vsi->tx_rings[0]->tx_itr_setting);
3375         q_vector->tx.latency_range = I40E_LOW_LATENCY;
3376         wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.itr);
3377
3378         i40e_enable_misc_int_causes(pf);
3379
3380         /* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3381         wr32(hw, I40E_PFINT_LNKLST0, 0);
3382
3383         /* Associate the queue pair to the vector and enable the queue int */
3384         val = I40E_QINT_RQCTL_CAUSE_ENA_MASK                   |
3385               (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3386               (nextqp      << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3387               (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3388
3389         wr32(hw, I40E_QINT_RQCTL(0), val);
3390
3391         if (i40e_enabled_xdp_vsi(vsi)) {
3392                 val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                 |
3393                       (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
3394                       (I40E_QUEUE_TYPE_TX
3395                        << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3396
3397                wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3398         }
3399
3400         val = I40E_QINT_TQCTL_CAUSE_ENA_MASK                  |
3401               (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3402               (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3403
3404         wr32(hw, I40E_QINT_TQCTL(0), val);
3405         i40e_flush(hw);
3406 }
3407
3408 /**
3409  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
3410  * @pf: board private structure
3411  **/
3412 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
3413 {
3414         struct i40e_hw *hw = &pf->hw;
3415
3416         wr32(hw, I40E_PFINT_DYN_CTL0,
3417              I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
3418         i40e_flush(hw);
3419 }
3420
3421 /**
3422  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
3423  * @pf: board private structure
3424  * @clearpba: true when all pending interrupt events should be cleared
3425  **/
3426 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf, bool clearpba)
3427 {
3428         struct i40e_hw *hw = &pf->hw;
3429         u32 val;
3430
3431         val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
3432               (clearpba ? I40E_PFINT_DYN_CTL0_CLEARPBA_MASK : 0) |
3433               (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
3434
3435         wr32(hw, I40E_PFINT_DYN_CTL0, val);
3436         i40e_flush(hw);
3437 }
3438
3439 /**
3440  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
3441  * @irq: interrupt number
3442  * @data: pointer to a q_vector
3443  **/
3444 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
3445 {
3446         struct i40e_q_vector *q_vector = data;
3447
3448         if (!q_vector->tx.ring && !q_vector->rx.ring)
3449                 return IRQ_HANDLED;
3450
3451         napi_schedule_irqoff(&q_vector->napi);
3452
3453         return IRQ_HANDLED;
3454 }
3455
3456 /**
3457  * i40e_irq_affinity_notify - Callback for affinity changes
3458  * @notify: context as to what irq was changed
3459  * @mask: the new affinity mask
3460  *
3461  * This is a callback function used by the irq_set_affinity_notifier function
3462  * so that we may register to receive changes to the irq affinity masks.
3463  **/
3464 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
3465                                      const cpumask_t *mask)
3466 {
3467         struct i40e_q_vector *q_vector =
3468                 container_of(notify, struct i40e_q_vector, affinity_notify);
3469
3470         cpumask_copy(&q_vector->affinity_mask, mask);
3471 }
3472
3473 /**
3474  * i40e_irq_affinity_release - Callback for affinity notifier release
3475  * @ref: internal core kernel usage
3476  *
3477  * This is a callback function used by the irq_set_affinity_notifier function
3478  * to inform the current notification subscriber that they will no longer
3479  * receive notifications.
3480  **/
3481 static void i40e_irq_affinity_release(struct kref *ref) {}
3482
3483 /**
3484  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
3485  * @vsi: the VSI being configured
3486  * @basename: name for the vector
3487  *
3488  * Allocates MSI-X vectors and requests interrupts from the kernel.
3489  **/
3490 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
3491 {
3492         int q_vectors = vsi->num_q_vectors;
3493         struct i40e_pf *pf = vsi->back;
3494         int base = vsi->base_vector;
3495         int rx_int_idx = 0;
3496         int tx_int_idx = 0;
3497         int vector, err;
3498         int irq_num;
3499         int cpu;
3500
3501         for (vector = 0; vector < q_vectors; vector++) {
3502                 struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
3503
3504                 irq_num = pf->msix_entries[base + vector].vector;
3505
3506                 if (q_vector->tx.ring && q_vector->rx.ring) {
3507                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3508                                  "%s-%s-%d", basename, "TxRx", rx_int_idx++);
3509                         tx_int_idx++;
3510                 } else if (q_vector->rx.ring) {
3511                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3512                                  "%s-%s-%d", basename, "rx", rx_int_idx++);
3513                 } else if (q_vector->tx.ring) {
3514                         snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3515                                  "%s-%s-%d", basename, "tx", tx_int_idx++);
3516                 } else {
3517                         /* skip this unused q_vector */
3518                         continue;
3519                 }
3520                 err = request_irq(irq_num,
3521                                   vsi->irq_handler,
3522                                   0,
3523                                   q_vector->name,
3524                                   q_vector);
3525                 if (err) {
3526                         dev_info(&pf->pdev->dev,
3527                                  "MSIX request_irq failed, error: %d\n", err);
3528                         goto free_queue_irqs;
3529                 }
3530
3531                 /* register for affinity change notifications */
3532                 q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
3533                 q_vector->affinity_notify.release = i40e_irq_affinity_release;
3534                 irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
3535                 /* Spread affinity hints out across online CPUs.
3536                  *
3537                  * get_cpu_mask returns a static constant mask with
3538                  * a permanent lifetime so it's ok to pass to
3539                  * irq_set_affinity_hint without making a copy.
3540                  */
3541                 cpu = cpumask_local_spread(q_vector->v_idx, -1);
3542                 irq_set_affinity_hint(irq_num, get_cpu_mask(cpu));
3543         }
3544
3545         vsi->irqs_ready = true;
3546         return 0;
3547
3548 free_queue_irqs:
3549         while (vector) {
3550                 vector--;
3551                 irq_num = pf->msix_entries[base + vector].vector;
3552                 irq_set_affinity_notifier(irq_num, NULL);
3553                 irq_set_affinity_hint(irq_num, NULL);
3554                 free_irq(irq_num, &vsi->q_vectors[vector]);
3555         }
3556         return err;
3557 }
3558
3559 /**
3560  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
3561  * @vsi: the VSI being un-configured
3562  **/
3563 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
3564 {
3565         struct i40e_pf *pf = vsi->back;
3566         struct i40e_hw *hw = &pf->hw;
3567         int base = vsi->base_vector;
3568         int i;
3569
3570         /* disable interrupt causation from each queue */
3571         for (i = 0; i < vsi->num_queue_pairs; i++) {
3572                 u32 val;
3573
3574                 val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
3575                 val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
3576                 wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
3577
3578                 val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
3579                 val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
3580                 wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
3581
3582                 if (!i40e_enabled_xdp_vsi(vsi))
3583                         continue;
3584                 wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
3585         }
3586
3587         /* disable each interrupt */
3588         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3589                 for (i = vsi->base_vector;
3590                      i < (vsi->num_q_vectors + vsi->base_vector); i++)
3591                         wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
3592
3593                 i40e_flush(hw);
3594                 for (i = 0; i < vsi->num_q_vectors; i++)
3595                         synchronize_irq(pf->msix_entries[i + base].vector);
3596         } else {
3597                 /* Legacy and MSI mode - this stops all interrupt handling */
3598                 wr32(hw, I40E_PFINT_ICR0_ENA, 0);
3599                 wr32(hw, I40E_PFINT_DYN_CTL0, 0);
3600                 i40e_flush(hw);
3601                 synchronize_irq(pf->pdev->irq);
3602         }
3603 }
3604
3605 /**
3606  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
3607  * @vsi: the VSI being configured
3608  **/
3609 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
3610 {
3611         struct i40e_pf *pf = vsi->back;
3612         int i;
3613
3614         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3615                 for (i = 0; i < vsi->num_q_vectors; i++)
3616                         i40e_irq_dynamic_enable(vsi, i);
3617         } else {
3618                 i40e_irq_dynamic_enable_icr0(pf, true);
3619         }
3620
3621         i40e_flush(&pf->hw);
3622         return 0;
3623 }
3624
3625 /**
3626  * i40e_stop_misc_vector - Stop the vector that handles non-queue events
3627  * @pf: board private structure
3628  **/
3629 static void i40e_stop_misc_vector(struct i40e_pf *pf)
3630 {
3631         /* Disable ICR 0 */
3632         wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
3633         i40e_flush(&pf->hw);
3634 }
3635
3636 /**
3637  * i40e_intr - MSI/Legacy and non-queue interrupt handler
3638  * @irq: interrupt number
3639  * @data: pointer to a q_vector
3640  *
3641  * This is the handler used for all MSI/Legacy interrupts, and deals
3642  * with both queue and non-queue interrupts.  This is also used in
3643  * MSIX mode to handle the non-queue interrupts.
3644  **/
3645 static irqreturn_t i40e_intr(int irq, void *data)
3646 {
3647         struct i40e_pf *pf = (struct i40e_pf *)data;
3648         struct i40e_hw *hw = &pf->hw;
3649         irqreturn_t ret = IRQ_NONE;
3650         u32 icr0, icr0_remaining;
3651         u32 val, ena_mask;
3652
3653         icr0 = rd32(hw, I40E_PFINT_ICR0);
3654         ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
3655
3656         /* if sharing a legacy IRQ, we might get called w/o an intr pending */
3657         if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
3658                 goto enable_intr;
3659
3660         /* if interrupt but no bits showing, must be SWINT */
3661         if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
3662             (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
3663                 pf->sw_int_count++;
3664
3665         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
3666             (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
3667                 ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3668                 dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
3669                 set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
3670         }
3671
3672         /* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
3673         if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
3674                 struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
3675                 struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3676
3677                 /* We do not have a way to disarm Queue causes while leaving
3678                  * interrupt enabled for all other causes, ideally
3679                  * interrupt should be disabled while we are in NAPI but
3680                  * this is not a performance path and napi_schedule()
3681                  * can deal with rescheduling.
3682                  */
3683                 if (!test_bit(__I40E_DOWN, pf->state))
3684                         napi_schedule_irqoff(&q_vector->napi);
3685         }
3686
3687         if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
3688                 ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3689                 set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
3690                 i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
3691         }
3692
3693         if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
3694                 ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
3695                 set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
3696         }
3697
3698         if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
3699                 ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
3700                 set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
3701         }
3702
3703         if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
3704                 if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
3705                         set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
3706                 ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
3707                 val = rd32(hw, I40E_GLGEN_RSTAT);
3708                 val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
3709                        >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
3710                 if (val == I40E_RESET_CORER) {
3711                         pf->corer_count++;
3712                 } else if (val == I40E_RESET_GLOBR) {
3713                         pf->globr_count++;
3714                 } else if (val == I40E_RESET_EMPR) {
3715                         pf->empr_count++;
3716                         set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
3717                 }
3718         }
3719
3720         if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
3721                 icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
3722                 dev_info(&pf->pdev->dev, "HMC error interrupt\n");
3723                 dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
3724                          rd32(hw, I40E_PFHMC_ERRORINFO),
3725                          rd32(hw, I40E_PFHMC_ERRORDATA));
3726         }
3727
3728         if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
3729                 u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
3730
3731                 if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK) {
3732                         icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3733                         i40e_ptp_tx_hwtstamp(pf);
3734                 }
3735         }
3736
3737         /* If a critical error is pending we have no choice but to reset the
3738          * device.
3739          * Report and mask out any remaining unexpected interrupts.
3740          */
3741         icr0_remaining = icr0 & ena_mask;
3742         if (icr0_remaining) {
3743                 dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
3744                          icr0_remaining);
3745                 if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
3746                     (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
3747                     (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
3748                         dev_info(&pf->pdev->dev, "device will be reset\n");
3749                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
3750                         i40e_service_event_schedule(pf);
3751                 }
3752                 ena_mask &= ~icr0_remaining;
3753         }
3754         ret = IRQ_HANDLED;
3755
3756 enable_intr:
3757         /* re-enable interrupt causes */
3758         wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
3759         if (!test_bit(__I40E_DOWN, pf->state)) {
3760                 i40e_service_event_schedule(pf);
3761                 i40e_irq_dynamic_enable_icr0(pf, false);
3762         }
3763
3764         return ret;
3765 }
3766
3767 /**
3768  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
3769  * @tx_ring:  tx ring to clean
3770  * @budget:   how many cleans we're allowed
3771  *
3772  * Returns true if there's any budget left (e.g. the clean is finished)
3773  **/
3774 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
3775 {
3776         struct i40e_vsi *vsi = tx_ring->vsi;
3777         u16 i = tx_ring->next_to_clean;
3778         struct i40e_tx_buffer *tx_buf;
3779         struct i40e_tx_desc *tx_desc;
3780
3781         tx_buf = &tx_ring->tx_bi[i];
3782         tx_desc = I40E_TX_DESC(tx_ring, i);
3783         i -= tx_ring->count;
3784
3785         do {
3786                 struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
3787
3788                 /* if next_to_watch is not set then there is no work pending */
3789                 if (!eop_desc)
3790                         break;
3791
3792                 /* prevent any other reads prior to eop_desc */
3793                 smp_rmb();
3794
3795                 /* if the descriptor isn't done, no work yet to do */
3796                 if (!(eop_desc->cmd_type_offset_bsz &
3797                       cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
3798                         break;
3799
3800                 /* clear next_to_watch to prevent false hangs */
3801                 tx_buf->next_to_watch = NULL;
3802
3803                 tx_desc->buffer_addr = 0;
3804                 tx_desc->cmd_type_offset_bsz = 0;
3805                 /* move past filter desc */
3806                 tx_buf++;
3807                 tx_desc++;
3808                 i++;
3809                 if (unlikely(!i)) {
3810                         i -= tx_ring->count;
3811                         tx_buf = tx_ring->tx_bi;
3812                         tx_desc = I40E_TX_DESC(tx_ring, 0);
3813                 }
3814                 /* unmap skb header data */
3815                 dma_unmap_single(tx_ring->dev,
3816                                  dma_unmap_addr(tx_buf, dma),
3817                                  dma_unmap_len(tx_buf, len),
3818                                  DMA_TO_DEVICE);
3819                 if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
3820                         kfree(tx_buf->raw_buf);
3821
3822                 tx_buf->raw_buf = NULL;
3823                 tx_buf->tx_flags = 0;
3824                 tx_buf->next_to_watch = NULL;
3825                 dma_unmap_len_set(tx_buf, len, 0);
3826                 tx_desc->buffer_addr = 0;
3827                 tx_desc->cmd_type_offset_bsz = 0;
3828
3829                 /* move us past the eop_desc for start of next FD desc */
3830                 tx_buf++;
3831                 tx_desc++;
3832                 i++;
3833                 if (unlikely(!i)) {
3834                         i -= tx_ring->count;
3835                         tx_buf = tx_ring->tx_bi;
3836                         tx_desc = I40E_TX_DESC(tx_ring, 0);
3837                 }
3838
3839                 /* update budget accounting */
3840                 budget--;
3841         } while (likely(budget));
3842
3843         i += tx_ring->count;
3844         tx_ring->next_to_clean = i;
3845
3846         if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
3847                 i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
3848
3849         return budget > 0;
3850 }
3851
3852 /**
3853  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
3854  * @irq: interrupt number
3855  * @data: pointer to a q_vector
3856  **/
3857 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
3858 {
3859         struct i40e_q_vector *q_vector = data;
3860         struct i40e_vsi *vsi;
3861
3862         if (!q_vector->tx.ring)
3863                 return IRQ_HANDLED;
3864
3865         vsi = q_vector->tx.ring->vsi;
3866         i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
3867
3868         return IRQ_HANDLED;
3869 }
3870
3871 /**
3872  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
3873  * @vsi: the VSI being configured
3874  * @v_idx: vector index
3875  * @qp_idx: queue pair index
3876  **/
3877 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
3878 {
3879         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
3880         struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
3881         struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
3882
3883         tx_ring->q_vector = q_vector;
3884         tx_ring->next = q_vector->tx.ring;
3885         q_vector->tx.ring = tx_ring;
3886         q_vector->tx.count++;
3887
3888         /* Place XDP Tx ring in the same q_vector ring list as regular Tx */
3889         if (i40e_enabled_xdp_vsi(vsi)) {
3890                 struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
3891
3892                 xdp_ring->q_vector = q_vector;
3893                 xdp_ring->next = q_vector->tx.ring;
3894                 q_vector->tx.ring = xdp_ring;
3895                 q_vector->tx.count++;
3896         }
3897
3898         rx_ring->q_vector = q_vector;
3899         rx_ring->next = q_vector->rx.ring;
3900         q_vector->rx.ring = rx_ring;
3901         q_vector->rx.count++;
3902 }
3903
3904 /**
3905  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
3906  * @vsi: the VSI being configured
3907  *
3908  * This function maps descriptor rings to the queue-specific vectors
3909  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
3910  * one vector per queue pair, but on a constrained vector budget, we
3911  * group the queue pairs as "efficiently" as possible.
3912  **/
3913 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
3914 {
3915         int qp_remaining = vsi->num_queue_pairs;
3916         int q_vectors = vsi->num_q_vectors;
3917         int num_ringpairs;
3918         int v_start = 0;
3919         int qp_idx = 0;
3920
3921         /* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
3922          * group them so there are multiple queues per vector.
3923          * It is also important to go through all the vectors available to be
3924          * sure that if we don't use all the vectors, that the remaining vectors
3925          * are cleared. This is especially important when decreasing the
3926          * number of queues in use.
3927          */
3928         for (; v_start < q_vectors; v_start++) {
3929                 struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
3930
3931                 num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
3932
3933                 q_vector->num_ringpairs = num_ringpairs;
3934
3935                 q_vector->rx.count = 0;
3936                 q_vector->tx.count = 0;
3937                 q_vector->rx.ring = NULL;
3938                 q_vector->tx.ring = NULL;
3939
3940                 while (num_ringpairs--) {
3941                         i40e_map_vector_to_qp(vsi, v_start, qp_idx);
3942                         qp_idx++;
3943                         qp_remaining--;
3944                 }
3945         }
3946 }
3947
3948 /**
3949  * i40e_vsi_request_irq - Request IRQ from the OS
3950  * @vsi: the VSI being configured
3951  * @basename: name for the vector
3952  **/
3953 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
3954 {
3955         struct i40e_pf *pf = vsi->back;
3956         int err;
3957
3958         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
3959                 err = i40e_vsi_request_irq_msix(vsi, basename);
3960         else if (pf->flags & I40E_FLAG_MSI_ENABLED)
3961                 err = request_irq(pf->pdev->irq, i40e_intr, 0,
3962                                   pf->int_name, pf);
3963         else
3964                 err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
3965                                   pf->int_name, pf);
3966
3967         if (err)
3968                 dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
3969
3970         return err;
3971 }
3972
3973 #ifdef CONFIG_NET_POLL_CONTROLLER
3974 /**
3975  * i40e_netpoll - A Polling 'interrupt' handler
3976  * @netdev: network interface device structure
3977  *
3978  * This is used by netconsole to send skbs without having to re-enable
3979  * interrupts.  It's not called while the normal interrupt routine is executing.
3980  **/
3981 static void i40e_netpoll(struct net_device *netdev)
3982 {
3983         struct i40e_netdev_priv *np = netdev_priv(netdev);
3984         struct i40e_vsi *vsi = np->vsi;
3985         struct i40e_pf *pf = vsi->back;
3986         int i;
3987
3988         /* if interface is down do nothing */
3989         if (test_bit(__I40E_VSI_DOWN, vsi->state))
3990                 return;
3991
3992         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3993                 for (i = 0; i < vsi->num_q_vectors; i++)
3994                         i40e_msix_clean_rings(0, vsi->q_vectors[i]);
3995         } else {
3996                 i40e_intr(pf->pdev->irq, netdev);
3997         }
3998 }
3999 #endif
4000
4001 #define I40E_QTX_ENA_WAIT_COUNT 50
4002
4003 /**
4004  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4005  * @pf: the PF being configured
4006  * @pf_q: the PF queue
4007  * @enable: enable or disable state of the queue
4008  *
4009  * This routine will wait for the given Tx queue of the PF to reach the
4010  * enabled or disabled state.
4011  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4012  * multiple retries; else will return 0 in case of success.
4013  **/
4014 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4015 {
4016         int i;
4017         u32 tx_reg;
4018
4019         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4020                 tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4021                 if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4022                         break;
4023
4024                 usleep_range(10, 20);
4025         }
4026         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4027                 return -ETIMEDOUT;
4028
4029         return 0;
4030 }
4031
4032 /**
4033  * i40e_control_tx_q - Start or stop a particular Tx queue
4034  * @pf: the PF structure
4035  * @pf_q: the PF queue to configure
4036  * @enable: start or stop the queue
4037  *
4038  * This function enables or disables a single queue. Note that any delay
4039  * required after the operation is expected to be handled by the caller of
4040  * this function.
4041  **/
4042 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4043 {
4044         struct i40e_hw *hw = &pf->hw;
4045         u32 tx_reg;
4046         int i;
4047
4048         /* warn the TX unit of coming changes */
4049         i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4050         if (!enable)
4051                 usleep_range(10, 20);
4052
4053         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4054                 tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4055                 if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4056                     ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4057                         break;
4058                 usleep_range(1000, 2000);
4059         }
4060
4061         /* Skip if the queue is already in the requested state */
4062         if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4063                 return;
4064
4065         /* turn on/off the queue */
4066         if (enable) {
4067                 wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4068                 tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4069         } else {
4070                 tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4071         }
4072
4073         wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4074 }
4075
4076 /**
4077  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4078  * @seid: VSI SEID
4079  * @pf: the PF structure
4080  * @pf_q: the PF queue to configure
4081  * @is_xdp: true if the queue is used for XDP
4082  * @enable: start or stop the queue
4083  **/
4084 static int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4085                                   bool is_xdp, bool enable)
4086 {
4087         int ret;
4088
4089         i40e_control_tx_q(pf, pf_q, enable);
4090
4091         /* wait for the change to finish */
4092         ret = i40e_pf_txq_wait(pf, pf_q, enable);
4093         if (ret) {
4094                 dev_info(&pf->pdev->dev,
4095                          "VSI seid %d %sTx ring %d %sable timeout\n",
4096                          seid, (is_xdp ? "XDP " : ""), pf_q,
4097                          (enable ? "en" : "dis"));
4098         }
4099
4100         return ret;
4101 }
4102
4103 /**
4104  * i40e_vsi_control_tx - Start or stop a VSI's rings
4105  * @vsi: the VSI being configured
4106  * @enable: start or stop the rings
4107  **/
4108 static int i40e_vsi_control_tx(struct i40e_vsi *vsi, bool enable)
4109 {
4110         struct i40e_pf *pf = vsi->back;
4111         int i, pf_q, ret = 0;
4112
4113         pf_q = vsi->base_queue;
4114         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4115                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4116                                              pf_q,
4117                                              false /*is xdp*/, enable);
4118                 if (ret)
4119                         break;
4120
4121                 if (!i40e_enabled_xdp_vsi(vsi))
4122                         continue;
4123
4124                 ret = i40e_control_wait_tx_q(vsi->seid, pf,
4125                                              pf_q + vsi->alloc_queue_pairs,
4126                                              true /*is xdp*/, enable);
4127                 if (ret)
4128                         break;
4129         }
4130
4131         return ret;
4132 }
4133
4134 /**
4135  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4136  * @pf: the PF being configured
4137  * @pf_q: the PF queue
4138  * @enable: enable or disable state of the queue
4139  *
4140  * This routine will wait for the given Rx queue of the PF to reach the
4141  * enabled or disabled state.
4142  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4143  * multiple retries; else will return 0 in case of success.
4144  **/
4145 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4146 {
4147         int i;
4148         u32 rx_reg;
4149
4150         for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4151                 rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4152                 if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4153                         break;
4154
4155                 usleep_range(10, 20);
4156         }
4157         if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4158                 return -ETIMEDOUT;
4159
4160         return 0;
4161 }
4162
4163 /**
4164  * i40e_control_rx_q - Start or stop a particular Rx queue
4165  * @pf: the PF structure
4166  * @pf_q: the PF queue to configure
4167  * @enable: start or stop the queue
4168  *
4169  * This function enables or disables a single queue. Note that any delay
4170  * required after the operation is expected to be handled by the caller of
4171  * this function.
4172  **/
4173 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4174 {
4175         struct i40e_hw *hw = &pf->hw;
4176         u32 rx_reg;
4177         int i;
4178
4179         for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4180                 rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4181                 if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4182                     ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4183                         break;
4184                 usleep_range(1000, 2000);
4185         }
4186
4187         /* Skip if the queue is already in the requested state */
4188         if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4189                 return;
4190
4191         /* turn on/off the queue */
4192         if (enable)
4193                 rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4194         else
4195                 rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4196
4197         wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4198 }
4199
4200 /**
4201  * i40e_vsi_control_rx - Start or stop a VSI's rings
4202  * @vsi: the VSI being configured
4203  * @enable: start or stop the rings
4204  **/
4205 static int i40e_vsi_control_rx(struct i40e_vsi *vsi, bool enable)
4206 {
4207         struct i40e_pf *pf = vsi->back;
4208         int i, pf_q, ret = 0;
4209
4210         pf_q = vsi->base_queue;
4211         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4212                 i40e_control_rx_q(pf, pf_q, enable);
4213
4214                 /* wait for the change to finish */
4215                 ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4216                 if (ret) {
4217                         dev_info(&pf->pdev->dev,
4218                                  "VSI seid %d Rx ring %d %sable timeout\n",
4219                                  vsi->seid, pf_q, (enable ? "en" : "dis"));
4220                         break;
4221                 }
4222         }
4223
4224         /* Due to HW errata, on Rx disable only, the register can indicate done
4225          * before it really is. Needs 50ms to be sure
4226          */
4227         if (!enable)
4228                 mdelay(50);
4229
4230         return ret;
4231 }
4232
4233 /**
4234  * i40e_vsi_start_rings - Start a VSI's rings
4235  * @vsi: the VSI being configured
4236  **/
4237 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4238 {
4239         int ret = 0;
4240
4241         /* do rx first for enable and last for disable */
4242         ret = i40e_vsi_control_rx(vsi, true);
4243         if (ret)
4244                 return ret;
4245         ret = i40e_vsi_control_tx(vsi, true);
4246
4247         return ret;
4248 }
4249
4250 /**
4251  * i40e_vsi_stop_rings - Stop a VSI's rings
4252  * @vsi: the VSI being configured
4253  **/
4254 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4255 {
4256         /* When port TX is suspended, don't wait */
4257         if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4258                 return i40e_vsi_stop_rings_no_wait(vsi);
4259
4260         /* do rx first for enable and last for disable
4261          * Ignore return value, we need to shutdown whatever we can
4262          */
4263         i40e_vsi_control_tx(vsi, false);
4264         i40e_vsi_control_rx(vsi, false);
4265 }
4266
4267 /**
4268  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4269  * @vsi: the VSI being shutdown
4270  *
4271  * This function stops all the rings for a VSI but does not delay to verify
4272  * that rings have been disabled. It is expected that the caller is shutting
4273  * down multiple VSIs at once and will delay together for all the VSIs after
4274  * initiating the shutdown. This is particularly useful for shutting down lots
4275  * of VFs together. Otherwise, a large delay can be incurred while configuring
4276  * each VSI in serial.
4277  **/
4278 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4279 {
4280         struct i40e_pf *pf = vsi->back;
4281         int i, pf_q;
4282
4283         pf_q = vsi->base_queue;
4284         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4285                 i40e_control_tx_q(pf, pf_q, false);
4286                 i40e_control_rx_q(pf, pf_q, false);
4287         }
4288 }
4289
4290 /**
4291  * i40e_vsi_free_irq - Free the irq association with the OS
4292  * @vsi: the VSI being configured
4293  **/
4294 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4295 {
4296         struct i40e_pf *pf = vsi->back;
4297         struct i40e_hw *hw = &pf->hw;
4298         int base = vsi->base_vector;
4299         u32 val, qp;
4300         int i;
4301
4302         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4303                 if (!vsi->q_vectors)
4304                         return;
4305
4306                 if (!vsi->irqs_ready)
4307                         return;
4308
4309                 vsi->irqs_ready = false;
4310                 for (i = 0; i < vsi->num_q_vectors; i++) {
4311                         int irq_num;
4312                         u16 vector;
4313
4314                         vector = i + base;
4315                         irq_num = pf->msix_entries[vector].vector;
4316
4317                         /* free only the irqs that were actually requested */
4318                         if (!vsi->q_vectors[i] ||
4319                             !vsi->q_vectors[i]->num_ringpairs)
4320                                 continue;
4321
4322                         /* clear the affinity notifier in the IRQ descriptor */
4323                         irq_set_affinity_notifier(irq_num, NULL);
4324                         /* remove our suggested affinity mask for this IRQ */
4325                         irq_set_affinity_hint(irq_num, NULL);
4326                         synchronize_irq(irq_num);
4327                         free_irq(irq_num, vsi->q_vectors[i]);
4328
4329                         /* Tear down the interrupt queue link list
4330                          *
4331                          * We know that they come in pairs and always
4332                          * the Rx first, then the Tx.  To clear the
4333                          * link list, stick the EOL value into the
4334                          * next_q field of the registers.
4335                          */
4336                         val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4337                         qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4338                                 >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4339                         val |= I40E_QUEUE_END_OF_LIST
4340                                 << I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4341                         wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4342
4343                         while (qp != I40E_QUEUE_END_OF_LIST) {
4344                                 u32 next;
4345
4346                                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4347
4348                                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4349                                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4350                                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4351                                          I40E_QINT_RQCTL_INTEVENT_MASK);
4352
4353                                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4354                                          I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4355
4356                                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4357
4358                                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4359
4360                                 next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
4361                                         >> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
4362
4363                                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4364                                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4365                                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4366                                          I40E_QINT_TQCTL_INTEVENT_MASK);
4367
4368                                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4369                                          I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4370
4371                                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4372                                 qp = next;
4373                         }
4374                 }
4375         } else {
4376                 free_irq(pf->pdev->irq, pf);
4377
4378                 val = rd32(hw, I40E_PFINT_LNKLST0);
4379                 qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4380                         >> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4381                 val |= I40E_QUEUE_END_OF_LIST
4382                         << I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
4383                 wr32(hw, I40E_PFINT_LNKLST0, val);
4384
4385                 val = rd32(hw, I40E_QINT_RQCTL(qp));
4386                 val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4387                          I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4388                          I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4389                          I40E_QINT_RQCTL_INTEVENT_MASK);
4390
4391                 val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4392                         I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4393
4394                 wr32(hw, I40E_QINT_RQCTL(qp), val);
4395
4396                 val = rd32(hw, I40E_QINT_TQCTL(qp));
4397
4398                 val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4399                          I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4400                          I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4401                          I40E_QINT_TQCTL_INTEVENT_MASK);
4402
4403                 val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4404                         I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4405
4406                 wr32(hw, I40E_QINT_TQCTL(qp), val);
4407         }
4408 }
4409
4410 /**
4411  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
4412  * @vsi: the VSI being configured
4413  * @v_idx: Index of vector to be freed
4414  *
4415  * This function frees the memory allocated to the q_vector.  In addition if
4416  * NAPI is enabled it will delete any references to the NAPI struct prior
4417  * to freeing the q_vector.
4418  **/
4419 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
4420 {
4421         struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4422         struct i40e_ring *ring;
4423
4424         if (!q_vector)
4425                 return;
4426
4427         /* disassociate q_vector from rings */
4428         i40e_for_each_ring(ring, q_vector->tx)
4429                 ring->q_vector = NULL;
4430
4431         i40e_for_each_ring(ring, q_vector->rx)
4432                 ring->q_vector = NULL;
4433
4434         /* only VSI w/ an associated netdev is set up w/ NAPI */
4435         if (vsi->netdev)
4436                 netif_napi_del(&q_vector->napi);
4437
4438         vsi->q_vectors[v_idx] = NULL;
4439
4440         kfree_rcu(q_vector, rcu);
4441 }
4442
4443 /**
4444  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
4445  * @vsi: the VSI being un-configured
4446  *
4447  * This frees the memory allocated to the q_vectors and
4448  * deletes references to the NAPI struct.
4449  **/
4450 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
4451 {
4452         int v_idx;
4453
4454         for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
4455                 i40e_free_q_vector(vsi, v_idx);
4456 }
4457
4458 /**
4459  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
4460  * @pf: board private structure
4461  **/
4462 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
4463 {
4464         /* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
4465         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4466                 pci_disable_msix(pf->pdev);
4467                 kfree(pf->msix_entries);
4468                 pf->msix_entries = NULL;
4469                 kfree(pf->irq_pile);
4470                 pf->irq_pile = NULL;
4471         } else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
4472                 pci_disable_msi(pf->pdev);
4473         }
4474         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
4475 }
4476
4477 /**
4478  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
4479  * @pf: board private structure
4480  *
4481  * We go through and clear interrupt specific resources and reset the structure
4482  * to pre-load conditions
4483  **/
4484 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
4485 {
4486         int i;
4487
4488         i40e_stop_misc_vector(pf);
4489         if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
4490                 synchronize_irq(pf->msix_entries[0].vector);
4491                 free_irq(pf->msix_entries[0].vector, pf);
4492         }
4493
4494         i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
4495                       I40E_IWARP_IRQ_PILE_ID);
4496
4497         i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
4498         for (i = 0; i < pf->num_alloc_vsi; i++)
4499                 if (pf->vsi[i])
4500                         i40e_vsi_free_q_vectors(pf->vsi[i]);
4501         i40e_reset_interrupt_capability(pf);
4502 }
4503
4504 /**
4505  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
4506  * @vsi: the VSI being configured
4507  **/
4508 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
4509 {
4510         int q_idx;
4511
4512         if (!vsi->netdev)
4513                 return;
4514
4515         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4516                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4517
4518                 if (q_vector->rx.ring || q_vector->tx.ring)
4519                         napi_enable(&q_vector->napi);
4520         }
4521 }
4522
4523 /**
4524  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
4525  * @vsi: the VSI being configured
4526  **/
4527 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
4528 {
4529         int q_idx;
4530
4531         if (!vsi->netdev)
4532                 return;
4533
4534         for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4535                 struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4536
4537                 if (q_vector->rx.ring || q_vector->tx.ring)
4538                         napi_disable(&q_vector->napi);
4539         }
4540 }
4541
4542 /**
4543  * i40e_vsi_close - Shut down a VSI
4544  * @vsi: the vsi to be quelled
4545  **/
4546 static void i40e_vsi_close(struct i40e_vsi *vsi)
4547 {
4548         struct i40e_pf *pf = vsi->back;
4549         if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
4550                 i40e_down(vsi);
4551         i40e_vsi_free_irq(vsi);
4552         i40e_vsi_free_tx_resources(vsi);
4553         i40e_vsi_free_rx_resources(vsi);
4554         vsi->current_netdev_flags = 0;
4555         pf->flags |= I40E_FLAG_SERVICE_CLIENT_REQUESTED;
4556         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4557                 pf->flags |=  I40E_FLAG_CLIENT_RESET;
4558 }
4559
4560 /**
4561  * i40e_quiesce_vsi - Pause a given VSI
4562  * @vsi: the VSI being paused
4563  **/
4564 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
4565 {
4566         if (test_bit(__I40E_VSI_DOWN, vsi->state))
4567                 return;
4568
4569         set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
4570         if (vsi->netdev && netif_running(vsi->netdev))
4571                 vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
4572         else
4573                 i40e_vsi_close(vsi);
4574 }
4575
4576 /**
4577  * i40e_unquiesce_vsi - Resume a given VSI
4578  * @vsi: the VSI being resumed
4579  **/
4580 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
4581 {
4582         if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
4583                 return;
4584
4585         if (vsi->netdev && netif_running(vsi->netdev))
4586                 vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
4587         else
4588                 i40e_vsi_open(vsi);   /* this clears the DOWN bit */
4589 }
4590
4591 /**
4592  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
4593  * @pf: the PF
4594  **/
4595 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
4596 {
4597         int v;
4598
4599         for (v = 0; v < pf->num_alloc_vsi; v++) {
4600                 if (pf->vsi[v])
4601                         i40e_quiesce_vsi(pf->vsi[v]);
4602         }
4603 }
4604
4605 /**
4606  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
4607  * @pf: the PF
4608  **/
4609 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
4610 {
4611         int v;
4612
4613         for (v = 0; v < pf->num_alloc_vsi; v++) {
4614                 if (pf->vsi[v])
4615                         i40e_unquiesce_vsi(pf->vsi[v]);
4616         }
4617 }
4618
4619 /**
4620  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
4621  * @vsi: the VSI being configured
4622  *
4623  * Wait until all queues on a given VSI have been disabled.
4624  **/
4625 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
4626 {
4627         struct i40e_pf *pf = vsi->back;
4628         int i, pf_q, ret;
4629
4630         pf_q = vsi->base_queue;
4631         for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4632                 /* Check and wait for the Tx queue */
4633                 ret = i40e_pf_txq_wait(pf, pf_q, false);
4634                 if (ret) {
4635                         dev_info(&pf->pdev->dev,
4636                                  "VSI seid %d Tx ring %d disable timeout\n",
4637                                  vsi->seid, pf_q);
4638                         return ret;
4639                 }
4640
4641                 if (!i40e_enabled_xdp_vsi(vsi))
4642                         goto wait_rx;
4643
4644                 /* Check and wait for the XDP Tx queue */
4645                 ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
4646                                        false);
4647                 if (ret) {
4648                         dev_info(&pf->pdev->dev,
4649                                  "VSI seid %d XDP Tx ring %d disable timeout\n",
4650                                  vsi->seid, pf_q);
4651                         return ret;
4652                 }
4653 wait_rx:
4654                 /* Check and wait for the Rx queue */
4655                 ret = i40e_pf_rxq_wait(pf, pf_q, false);
4656                 if (ret) {
4657                         dev_info(&pf->pdev->dev,
4658                                  "VSI seid %d Rx ring %d disable timeout\n",
4659                                  vsi->seid, pf_q);
4660                         return ret;
4661                 }
4662         }
4663
4664         return 0;
4665 }
4666
4667 #ifdef CONFIG_I40E_DCB
4668 /**
4669  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
4670  * @pf: the PF
4671  *
4672  * This function waits for the queues to be in disabled state for all the
4673  * VSIs that are managed by this PF.
4674  **/
4675 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
4676 {
4677         int v, ret = 0;
4678
4679         for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
4680                 if (pf->vsi[v]) {
4681                         ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
4682                         if (ret)
4683                                 break;
4684                 }
4685         }
4686
4687         return ret;
4688 }
4689
4690 #endif
4691
4692 /**
4693  * i40e_detect_recover_hung_queue - Function to detect and recover hung_queue
4694  * @q_idx: TX queue number
4695  * @vsi: Pointer to VSI struct
4696  *
4697  * This function checks specified queue for given VSI. Detects hung condition.
4698  * We proactively detect hung TX queues by checking if interrupts are disabled
4699  * but there are pending descriptors.  If it appears hung, attempt to recover
4700  * by triggering a SW interrupt.
4701  **/
4702 static void i40e_detect_recover_hung_queue(int q_idx, struct i40e_vsi *vsi)
4703 {
4704         struct i40e_ring *tx_ring = NULL;
4705         struct i40e_pf  *pf;
4706         u32 val, tx_pending;
4707         int i;
4708
4709         pf = vsi->back;
4710
4711         /* now that we have an index, find the tx_ring struct */
4712         for (i = 0; i < vsi->num_queue_pairs; i++) {
4713                 if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
4714                         if (q_idx == vsi->tx_rings[i]->queue_index) {
4715                                 tx_ring = vsi->tx_rings[i];
4716                                 break;
4717                         }
4718                 }
4719         }
4720
4721         if (!tx_ring)
4722                 return;
4723
4724         /* Read interrupt register */
4725         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4726                 val = rd32(&pf->hw,
4727                            I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
4728                                                tx_ring->vsi->base_vector - 1));
4729         else
4730                 val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
4731
4732         tx_pending = i40e_get_tx_pending(tx_ring);
4733
4734         /* Interrupts are disabled and TX pending is non-zero,
4735          * trigger the SW interrupt (don't wait). Worst case
4736          * there will be one extra interrupt which may result
4737          * into not cleaning any queues because queues are cleaned.
4738          */
4739         if (tx_pending && (!(val & I40E_PFINT_DYN_CTLN_INTENA_MASK)))
4740                 i40e_force_wb(vsi, tx_ring->q_vector);
4741 }
4742
4743 /**
4744  * i40e_detect_recover_hung - Function to detect and recover hung_queues
4745  * @pf:  pointer to PF struct
4746  *
4747  * LAN VSI has netdev and netdev has TX queues. This function is to check
4748  * each of those TX queues if they are hung, trigger recovery by issuing
4749  * SW interrupt.
4750  **/
4751 static void i40e_detect_recover_hung(struct i40e_pf *pf)
4752 {
4753         struct net_device *netdev;
4754         struct i40e_vsi *vsi;
4755         unsigned int i;
4756
4757         /* Only for LAN VSI */
4758         vsi = pf->vsi[pf->lan_vsi];
4759
4760         if (!vsi)
4761                 return;
4762
4763         /* Make sure, VSI state is not DOWN/RECOVERY_PENDING */
4764         if (test_bit(__I40E_VSI_DOWN, vsi->back->state) ||
4765             test_bit(__I40E_RESET_RECOVERY_PENDING, vsi->back->state))
4766                 return;
4767
4768         /* Make sure type is MAIN VSI */
4769         if (vsi->type != I40E_VSI_MAIN)
4770                 return;
4771
4772         netdev = vsi->netdev;
4773         if (!netdev)
4774                 return;
4775
4776         /* Bail out if netif_carrier is not OK */
4777         if (!netif_carrier_ok(netdev))
4778                 return;
4779
4780         /* Go thru' TX queues for netdev */
4781         for (i = 0; i < netdev->num_tx_queues; i++) {
4782                 struct netdev_queue *q;
4783
4784                 q = netdev_get_tx_queue(netdev, i);
4785                 if (q)
4786                         i40e_detect_recover_hung_queue(i, vsi);
4787         }
4788 }
4789
4790 /**
4791  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
4792  * @pf: pointer to PF
4793  *
4794  * Get TC map for ISCSI PF type that will include iSCSI TC
4795  * and LAN TC.
4796  **/
4797 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
4798 {
4799         struct i40e_dcb_app_priority_table app;
4800         struct i40e_hw *hw = &pf->hw;
4801         u8 enabled_tc = 1; /* TC0 is always enabled */
4802         u8 tc, i;
4803         /* Get the iSCSI APP TLV */
4804         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
4805
4806         for (i = 0; i < dcbcfg->numapps; i++) {
4807                 app = dcbcfg->app[i];
4808                 if (app.selector == I40E_APP_SEL_TCPIP &&
4809                     app.protocolid == I40E_APP_PROTOID_ISCSI) {
4810                         tc = dcbcfg->etscfg.prioritytable[app.priority];
4811                         enabled_tc |= BIT(tc);
4812                         break;
4813                 }
4814         }
4815
4816         return enabled_tc;
4817 }
4818
4819 /**
4820  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
4821  * @dcbcfg: the corresponding DCBx configuration structure
4822  *
4823  * Return the number of TCs from given DCBx configuration
4824  **/
4825 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
4826 {
4827         int i, tc_unused = 0;
4828         u8 num_tc = 0;
4829         u8 ret = 0;
4830
4831         /* Scan the ETS Config Priority Table to find
4832          * traffic class enabled for a given priority
4833          * and create a bitmask of enabled TCs
4834          */
4835         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
4836                 num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
4837
4838         /* Now scan the bitmask to check for
4839          * contiguous TCs starting with TC0
4840          */
4841         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
4842                 if (num_tc & BIT(i)) {
4843                         if (!tc_unused) {
4844                                 ret++;
4845                         } else {
4846                                 pr_err("Non-contiguous TC - Disabling DCB\n");
4847                                 return 1;
4848                         }
4849                 } else {
4850                         tc_unused = 1;
4851                 }
4852         }
4853
4854         /* There is always at least TC0 */
4855         if (!ret)
4856                 ret = 1;
4857
4858         return ret;
4859 }
4860
4861 /**
4862  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
4863  * @dcbcfg: the corresponding DCBx configuration structure
4864  *
4865  * Query the current DCB configuration and return the number of
4866  * traffic classes enabled from the given DCBX config
4867  **/
4868 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
4869 {
4870         u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
4871         u8 enabled_tc = 1;
4872         u8 i;
4873
4874         for (i = 0; i < num_tc; i++)
4875                 enabled_tc |= BIT(i);
4876
4877         return enabled_tc;
4878 }
4879
4880 /**
4881  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
4882  * @pf: PF being queried
4883  *
4884  * Return number of traffic classes enabled for the given PF
4885  **/
4886 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
4887 {
4888         struct i40e_hw *hw = &pf->hw;
4889         u8 i, enabled_tc = 1;
4890         u8 num_tc = 0;
4891         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
4892
4893         /* If DCB is not enabled then always in single TC */
4894         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
4895                 return 1;
4896
4897         /* SFP mode will be enabled for all TCs on port */
4898         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
4899                 return i40e_dcb_get_num_tc(dcbcfg);
4900
4901         /* MFP mode return count of enabled TCs for this PF */
4902         if (pf->hw.func_caps.iscsi)
4903                 enabled_tc =  i40e_get_iscsi_tc_map(pf);
4904         else
4905                 return 1; /* Only TC0 */
4906
4907         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
4908                 if (enabled_tc & BIT(i))
4909                         num_tc++;
4910         }
4911         return num_tc;
4912 }
4913
4914 /**
4915  * i40e_pf_get_pf_tc_map - Get bitmap for enabled traffic classes
4916  * @pf: PF being queried
4917  *
4918  * Return a bitmap for enabled traffic classes for this PF.
4919  **/
4920 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
4921 {
4922         /* If DCB is not enabled for this PF then just return default TC */
4923         if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
4924                 return I40E_DEFAULT_TRAFFIC_CLASS;
4925
4926         /* SFP mode we want PF to be enabled for all TCs */
4927         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
4928                 return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
4929
4930         /* MFP enabled and iSCSI PF type */
4931         if (pf->hw.func_caps.iscsi)
4932                 return i40e_get_iscsi_tc_map(pf);
4933         else
4934                 return I40E_DEFAULT_TRAFFIC_CLASS;
4935 }
4936
4937 /**
4938  * i40e_vsi_get_bw_info - Query VSI BW Information
4939  * @vsi: the VSI being queried
4940  *
4941  * Returns 0 on success, negative value on failure
4942  **/
4943 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
4944 {
4945         struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
4946         struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
4947         struct i40e_pf *pf = vsi->back;
4948         struct i40e_hw *hw = &pf->hw;
4949         i40e_status ret;
4950         u32 tc_bw_max;
4951         int i;
4952
4953         /* Get the VSI level BW configuration */
4954         ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
4955         if (ret) {
4956                 dev_info(&pf->pdev->dev,
4957                          "couldn't get PF vsi bw config, err %s aq_err %s\n",
4958                          i40e_stat_str(&pf->hw, ret),
4959                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
4960                 return -EINVAL;
4961         }
4962
4963         /* Get the VSI level BW configuration per TC */
4964         ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
4965                                                NULL);
4966         if (ret) {
4967                 dev_info(&pf->pdev->dev,
4968                          "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
4969                          i40e_stat_str(&pf->hw, ret),
4970                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
4971                 return -EINVAL;
4972         }
4973
4974         if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
4975                 dev_info(&pf->pdev->dev,
4976                          "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
4977                          bw_config.tc_valid_bits,
4978                          bw_ets_config.tc_valid_bits);
4979                 /* Still continuing */
4980         }
4981
4982         vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
4983         vsi->bw_max_quanta = bw_config.max_bw;
4984         tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
4985                     (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
4986         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
4987                 vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
4988                 vsi->bw_ets_limit_credits[i] =
4989                                         le16_to_cpu(bw_ets_config.credits[i]);
4990                 /* 3 bits out of 4 for each TC */
4991                 vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
4992         }
4993
4994         return 0;
4995 }
4996
4997 /**
4998  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
4999  * @vsi: the VSI being configured
5000  * @enabled_tc: TC bitmap
5001  * @bw_credits: BW shared credits per TC
5002  *
5003  * Returns 0 on success, negative value on failure
5004  **/
5005 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5006                                        u8 *bw_share)
5007 {
5008         struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5009         i40e_status ret;
5010         int i;
5011
5012         bw_data.tc_valid_bits = enabled_tc;
5013         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5014                 bw_data.tc_bw_credits[i] = bw_share[i];
5015
5016         ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, vsi->seid, &bw_data,
5017                                        NULL);
5018         if (ret) {
5019                 dev_info(&vsi->back->pdev->dev,
5020                          "AQ command Config VSI BW allocation per TC failed = %d\n",
5021                          vsi->back->hw.aq.asq_last_status);
5022                 return -EINVAL;
5023         }
5024
5025         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5026                 vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5027
5028         return 0;
5029 }
5030
5031 /**
5032  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5033  * @vsi: the VSI being configured
5034  * @enabled_tc: TC map to be enabled
5035  *
5036  **/
5037 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5038 {
5039         struct net_device *netdev = vsi->netdev;
5040         struct i40e_pf *pf = vsi->back;
5041         struct i40e_hw *hw = &pf->hw;
5042         u8 netdev_tc = 0;
5043         int i;
5044         struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5045
5046         if (!netdev)
5047                 return;
5048
5049         if (!enabled_tc) {
5050                 netdev_reset_tc(netdev);
5051                 return;
5052         }
5053
5054         /* Set up actual enabled TCs on the VSI */
5055         if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5056                 return;
5057
5058         /* set per TC queues for the VSI */
5059         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5060                 /* Only set TC queues for enabled tcs
5061                  *
5062                  * e.g. For a VSI that has TC0 and TC3 enabled the
5063                  * enabled_tc bitmap would be 0x00001001; the driver
5064                  * will set the numtc for netdev as 2 that will be
5065                  * referenced by the netdev layer as TC 0 and 1.
5066                  */
5067                 if (vsi->tc_config.enabled_tc & BIT(i))
5068                         netdev_set_tc_queue(netdev,
5069                                         vsi->tc_config.tc_info[i].netdev_tc,
5070                                         vsi->tc_config.tc_info[i].qcount,
5071                                         vsi->tc_config.tc_info[i].qoffset);
5072         }
5073
5074         /* Assign UP2TC map for the VSI */
5075         for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5076                 /* Get the actual TC# for the UP */
5077                 u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5078                 /* Get the mapped netdev TC# for the UP */
5079                 netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5080                 netdev_set_prio_tc_map(netdev, i, netdev_tc);
5081         }
5082 }
5083
5084 /**
5085  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5086  * @vsi: the VSI being configured
5087  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5088  **/
5089 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5090                                       struct i40e_vsi_context *ctxt)
5091 {
5092         /* copy just the sections touched not the entire info
5093          * since not all sections are valid as returned by
5094          * update vsi params
5095          */
5096         vsi->info.mapping_flags = ctxt->info.mapping_flags;
5097         memcpy(&vsi->info.queue_mapping,
5098                &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5099         memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5100                sizeof(vsi->info.tc_mapping));
5101 }
5102
5103 /**
5104  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5105  * @vsi: VSI to be configured
5106  * @enabled_tc: TC bitmap
5107  *
5108  * This configures a particular VSI for TCs that are mapped to the
5109  * given TC bitmap. It uses default bandwidth share for TCs across
5110  * VSIs to configure TC for a particular VSI.
5111  *
5112  * NOTE:
5113  * It is expected that the VSI queues have been quisced before calling
5114  * this function.
5115  **/
5116 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5117 {
5118         u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5119         struct i40e_vsi_context ctxt;
5120         int ret = 0;
5121         int i;
5122
5123         /* Check if enabled_tc is same as existing or new TCs */
5124         if (vsi->tc_config.enabled_tc == enabled_tc)
5125                 return ret;
5126
5127         /* Enable ETS TCs with equal BW Share for now across all VSIs */
5128         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5129                 if (enabled_tc & BIT(i))
5130                         bw_share[i] = 1;
5131         }
5132
5133         ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5134         if (ret) {
5135                 dev_info(&vsi->back->pdev->dev,
5136                          "Failed configuring TC map %d for VSI %d\n",
5137                          enabled_tc, vsi->seid);
5138                 goto out;
5139         }
5140
5141         /* Update Queue Pairs Mapping for currently enabled UPs */
5142         ctxt.seid = vsi->seid;
5143         ctxt.pf_num = vsi->back->hw.pf_id;
5144         ctxt.vf_num = 0;
5145         ctxt.uplink_seid = vsi->uplink_seid;
5146         ctxt.info = vsi->info;
5147         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5148
5149         if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5150                 ctxt.info.valid_sections |=
5151                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5152                 ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5153         }
5154
5155         /* Update the VSI after updating the VSI queue-mapping information */
5156         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
5157         if (ret) {
5158                 dev_info(&vsi->back->pdev->dev,
5159                          "Update vsi tc config failed, err %s aq_err %s\n",
5160                          i40e_stat_str(&vsi->back->hw, ret),
5161                          i40e_aq_str(&vsi->back->hw,
5162                                      vsi->back->hw.aq.asq_last_status));
5163                 goto out;
5164         }
5165         /* update the local VSI info with updated queue map */
5166         i40e_vsi_update_queue_map(vsi, &ctxt);
5167         vsi->info.valid_sections = 0;
5168
5169         /* Update current VSI BW information */
5170         ret = i40e_vsi_get_bw_info(vsi);
5171         if (ret) {
5172                 dev_info(&vsi->back->pdev->dev,
5173                          "Failed updating vsi bw info, err %s aq_err %s\n",
5174                          i40e_stat_str(&vsi->back->hw, ret),
5175                          i40e_aq_str(&vsi->back->hw,
5176                                      vsi->back->hw.aq.asq_last_status));
5177                 goto out;
5178         }
5179
5180         /* Update the netdev TC setup */
5181         i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5182 out:
5183         return ret;
5184 }
5185
5186 /**
5187  * i40e_veb_config_tc - Configure TCs for given VEB
5188  * @veb: given VEB
5189  * @enabled_tc: TC bitmap
5190  *
5191  * Configures given TC bitmap for VEB (switching) element
5192  **/
5193 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
5194 {
5195         struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
5196         struct i40e_pf *pf = veb->pf;
5197         int ret = 0;
5198         int i;
5199
5200         /* No TCs or already enabled TCs just return */
5201         if (!enabled_tc || veb->enabled_tc == enabled_tc)
5202                 return ret;
5203
5204         bw_data.tc_valid_bits = enabled_tc;
5205         /* bw_data.absolute_credits is not set (relative) */
5206
5207         /* Enable ETS TCs with equal BW Share for now */
5208         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5209                 if (enabled_tc & BIT(i))
5210                         bw_data.tc_bw_share_credits[i] = 1;
5211         }
5212
5213         ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
5214                                                    &bw_data, NULL);
5215         if (ret) {
5216                 dev_info(&pf->pdev->dev,
5217                          "VEB bw config failed, err %s aq_err %s\n",
5218                          i40e_stat_str(&pf->hw, ret),
5219                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5220                 goto out;
5221         }
5222
5223         /* Update the BW information */
5224         ret = i40e_veb_get_bw_info(veb);
5225         if (ret) {
5226                 dev_info(&pf->pdev->dev,
5227                          "Failed getting veb bw config, err %s aq_err %s\n",
5228                          i40e_stat_str(&pf->hw, ret),
5229                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5230         }
5231
5232 out:
5233         return ret;
5234 }
5235
5236 #ifdef CONFIG_I40E_DCB
5237 /**
5238  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
5239  * @pf: PF struct
5240  *
5241  * Reconfigure VEB/VSIs on a given PF; it is assumed that
5242  * the caller would've quiesce all the VSIs before calling
5243  * this function
5244  **/
5245 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
5246 {
5247         u8 tc_map = 0;
5248         int ret;
5249         u8 v;
5250
5251         /* Enable the TCs available on PF to all VEBs */
5252         tc_map = i40e_pf_get_tc_map(pf);
5253         for (v = 0; v < I40E_MAX_VEB; v++) {
5254                 if (!pf->veb[v])
5255                         continue;
5256                 ret = i40e_veb_config_tc(pf->veb[v], tc_map);
5257                 if (ret) {
5258                         dev_info(&pf->pdev->dev,
5259                                  "Failed configuring TC for VEB seid=%d\n",
5260                                  pf->veb[v]->seid);
5261                         /* Will try to configure as many components */
5262                 }
5263         }
5264
5265         /* Update each VSI */
5266         for (v = 0; v < pf->num_alloc_vsi; v++) {
5267                 if (!pf->vsi[v])
5268                         continue;
5269
5270                 /* - Enable all TCs for the LAN VSI
5271                  * - For all others keep them at TC0 for now
5272                  */
5273                 if (v == pf->lan_vsi)
5274                         tc_map = i40e_pf_get_tc_map(pf);
5275                 else
5276                         tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
5277
5278                 ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
5279                 if (ret) {
5280                         dev_info(&pf->pdev->dev,
5281                                  "Failed configuring TC for VSI seid=%d\n",
5282                                  pf->vsi[v]->seid);
5283                         /* Will try to configure as many components */
5284                 } else {
5285                         /* Re-configure VSI vectors based on updated TC map */
5286                         i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
5287                         if (pf->vsi[v]->netdev)
5288                                 i40e_dcbnl_set_all(pf->vsi[v]);
5289                 }
5290         }
5291 }
5292
5293 /**
5294  * i40e_resume_port_tx - Resume port Tx
5295  * @pf: PF struct
5296  *
5297  * Resume a port's Tx and issue a PF reset in case of failure to
5298  * resume.
5299  **/
5300 static int i40e_resume_port_tx(struct i40e_pf *pf)
5301 {
5302         struct i40e_hw *hw = &pf->hw;
5303         int ret;
5304
5305         ret = i40e_aq_resume_port_tx(hw, NULL);
5306         if (ret) {
5307                 dev_info(&pf->pdev->dev,
5308                          "Resume Port Tx failed, err %s aq_err %s\n",
5309                           i40e_stat_str(&pf->hw, ret),
5310                           i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5311                 /* Schedule PF reset to recover */
5312                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
5313                 i40e_service_event_schedule(pf);
5314         }
5315
5316         return ret;
5317 }
5318
5319 /**
5320  * i40e_init_pf_dcb - Initialize DCB configuration
5321  * @pf: PF being configured
5322  *
5323  * Query the current DCB configuration and cache it
5324  * in the hardware structure
5325  **/
5326 static int i40e_init_pf_dcb(struct i40e_pf *pf)
5327 {
5328         struct i40e_hw *hw = &pf->hw;
5329         int err = 0;
5330
5331         /* Do not enable DCB for SW1 and SW2 images even if the FW is capable */
5332         if (pf->hw_features & I40E_HW_NO_DCB_SUPPORT)
5333                 goto out;
5334
5335         /* Get the initial DCB configuration */
5336         err = i40e_init_dcb(hw);
5337         if (!err) {
5338                 /* Device/Function is not DCBX capable */
5339                 if ((!hw->func_caps.dcb) ||
5340                     (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
5341                         dev_info(&pf->pdev->dev,
5342                                  "DCBX offload is not supported or is disabled for this PF.\n");
5343                 } else {
5344                         /* When status is not DISABLED then DCBX in FW */
5345                         pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
5346                                        DCB_CAP_DCBX_VER_IEEE;
5347
5348                         pf->flags |= I40E_FLAG_DCB_CAPABLE;
5349                         /* Enable DCB tagging only when more than one TC
5350                          * or explicitly disable if only one TC
5351                          */
5352                         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
5353                                 pf->flags |= I40E_FLAG_DCB_ENABLED;
5354                         else
5355                                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
5356                         dev_dbg(&pf->pdev->dev,
5357                                 "DCBX offload is supported for this PF.\n");
5358                 }
5359         } else {
5360                 dev_info(&pf->pdev->dev,
5361                          "Query for DCB configuration failed, err %s aq_err %s\n",
5362                          i40e_stat_str(&pf->hw, err),
5363                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5364         }
5365
5366 out:
5367         return err;
5368 }
5369 #endif /* CONFIG_I40E_DCB */
5370 #define SPEED_SIZE 14
5371 #define FC_SIZE 8
5372 /**
5373  * i40e_print_link_message - print link up or down
5374  * @vsi: the VSI for which link needs a message
5375  */
5376 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
5377 {
5378         enum i40e_aq_link_speed new_speed;
5379         char *speed = "Unknown";
5380         char *fc = "Unknown";
5381         char *fec = "";
5382         char *req_fec = "";
5383         char *an = "";
5384
5385         new_speed = vsi->back->hw.phy.link_info.link_speed;
5386
5387         if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
5388                 return;
5389         vsi->current_isup = isup;
5390         vsi->current_speed = new_speed;
5391         if (!isup) {
5392                 netdev_info(vsi->netdev, "NIC Link is Down\n");
5393                 return;
5394         }
5395
5396         /* Warn user if link speed on NPAR enabled partition is not at
5397          * least 10GB
5398          */
5399         if (vsi->back->hw.func_caps.npar_enable &&
5400             (vsi->back->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
5401              vsi->back->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
5402                 netdev_warn(vsi->netdev,
5403                             "The partition detected link speed that is less than 10Gbps\n");
5404
5405         switch (vsi->back->hw.phy.link_info.link_speed) {
5406         case I40E_LINK_SPEED_40GB:
5407                 speed = "40 G";
5408                 break;
5409         case I40E_LINK_SPEED_20GB:
5410                 speed = "20 G";
5411                 break;
5412         case I40E_LINK_SPEED_25GB:
5413                 speed = "25 G";
5414                 break;
5415         case I40E_LINK_SPEED_10GB:
5416                 speed = "10 G";
5417                 break;
5418         case I40E_LINK_SPEED_1GB:
5419                 speed = "1000 M";
5420                 break;
5421         case I40E_LINK_SPEED_100MB:
5422                 speed = "100 M";
5423                 break;
5424         default:
5425                 break;
5426         }
5427
5428         switch (vsi->back->hw.fc.current_mode) {
5429         case I40E_FC_FULL:
5430                 fc = "RX/TX";
5431                 break;
5432         case I40E_FC_TX_PAUSE:
5433                 fc = "TX";
5434                 break;
5435         case I40E_FC_RX_PAUSE:
5436                 fc = "RX";
5437                 break;
5438         default:
5439                 fc = "None";
5440                 break;
5441         }
5442
5443         if (vsi->back->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
5444                 req_fec = ", Requested FEC: None";
5445                 fec = ", FEC: None";
5446                 an = ", Autoneg: False";
5447
5448                 if (vsi->back->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
5449                         an = ", Autoneg: True";
5450
5451                 if (vsi->back->hw.phy.link_info.fec_info &
5452                     I40E_AQ_CONFIG_FEC_KR_ENA)
5453                         fec = ", FEC: CL74 FC-FEC/BASE-R";
5454                 else if (vsi->back->hw.phy.link_info.fec_info &
5455                          I40E_AQ_CONFIG_FEC_RS_ENA)
5456                         fec = ", FEC: CL108 RS-FEC";
5457
5458                 /* 'CL108 RS-FEC' should be displayed when RS is requested, or
5459                  * both RS and FC are requested
5460                  */
5461                 if (vsi->back->hw.phy.link_info.req_fec_info &
5462                     (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
5463                         if (vsi->back->hw.phy.link_info.req_fec_info &
5464                             I40E_AQ_REQUEST_FEC_RS)
5465                                 req_fec = ", Requested FEC: CL108 RS-FEC";
5466                         else
5467                                 req_fec = ", Requested FEC: CL74 FC-FEC/BASE-R";
5468                 }
5469         }
5470
5471         netdev_info(vsi->netdev, "NIC Link is Up, %sbps Full Duplex%s%s%s, Flow Control: %s\n",
5472                     speed, req_fec, fec, an, fc);
5473 }
5474
5475 /**
5476  * i40e_up_complete - Finish the last steps of bringing up a connection
5477  * @vsi: the VSI being configured
5478  **/
5479 static int i40e_up_complete(struct i40e_vsi *vsi)
5480 {
5481         struct i40e_pf *pf = vsi->back;
5482         int err;
5483
5484         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
5485                 i40e_vsi_configure_msix(vsi);
5486         else
5487                 i40e_configure_msi_and_legacy(vsi);
5488
5489         /* start rings */
5490         err = i40e_vsi_start_rings(vsi);
5491         if (err)
5492                 return err;
5493
5494         clear_bit(__I40E_VSI_DOWN, vsi->state);
5495         i40e_napi_enable_all(vsi);
5496         i40e_vsi_enable_irq(vsi);
5497
5498         if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
5499             (vsi->netdev)) {
5500                 i40e_print_link_message(vsi, true);
5501                 netif_tx_start_all_queues(vsi->netdev);
5502                 netif_carrier_on(vsi->netdev);
5503         } else if (vsi->netdev) {
5504                 i40e_print_link_message(vsi, false);
5505                 /* need to check for qualified module here*/
5506                 if ((pf->hw.phy.link_info.link_info &
5507                         I40E_AQ_MEDIA_AVAILABLE) &&
5508                     (!(pf->hw.phy.link_info.an_info &
5509                         I40E_AQ_QUALIFIED_MODULE)))
5510                         netdev_err(vsi->netdev,
5511                                    "the driver failed to link because an unqualified module was detected.");
5512         }
5513
5514         /* replay FDIR SB filters */
5515         if (vsi->type == I40E_VSI_FDIR) {
5516                 /* reset fd counters */
5517                 pf->fd_add_err = 0;
5518                 pf->fd_atr_cnt = 0;
5519                 i40e_fdir_filter_restore(vsi);
5520         }
5521
5522         /* On the next run of the service_task, notify any clients of the new
5523          * opened netdev
5524          */
5525         pf->flags |= I40E_FLAG_SERVICE_CLIENT_REQUESTED;
5526         i40e_service_event_schedule(pf);
5527
5528         return 0;
5529 }
5530
5531 /**
5532  * i40e_vsi_reinit_locked - Reset the VSI
5533  * @vsi: the VSI being configured
5534  *
5535  * Rebuild the ring structs after some configuration
5536  * has changed, e.g. MTU size.
5537  **/
5538 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
5539 {
5540         struct i40e_pf *pf = vsi->back;
5541
5542         WARN_ON(in_interrupt());
5543         while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
5544                 usleep_range(1000, 2000);
5545         i40e_down(vsi);
5546
5547         i40e_up(vsi);
5548         clear_bit(__I40E_CONFIG_BUSY, pf->state);
5549 }
5550
5551 /**
5552  * i40e_up - Bring the connection back up after being down
5553  * @vsi: the VSI being configured
5554  **/
5555 int i40e_up(struct i40e_vsi *vsi)
5556 {
5557         int err;
5558
5559         err = i40e_vsi_configure(vsi);
5560         if (!err)
5561                 err = i40e_up_complete(vsi);
5562
5563         return err;
5564 }
5565
5566 /**
5567  * i40e_down - Shutdown the connection processing
5568  * @vsi: the VSI being stopped
5569  **/
5570 void i40e_down(struct i40e_vsi *vsi)
5571 {
5572         int i;
5573
5574         /* It is assumed that the caller of this function
5575          * sets the vsi->state __I40E_VSI_DOWN bit.
5576          */
5577         if (vsi->netdev) {
5578                 netif_carrier_off(vsi->netdev);
5579                 netif_tx_disable(vsi->netdev);
5580         }
5581         i40e_vsi_disable_irq(vsi);
5582         i40e_vsi_stop_rings(vsi);
5583         i40e_napi_disable_all(vsi);
5584
5585         for (i = 0; i < vsi->num_queue_pairs; i++) {
5586                 i40e_clean_tx_ring(vsi->tx_rings[i]);
5587                 if (i40e_enabled_xdp_vsi(vsi))
5588                         i40e_clean_tx_ring(vsi->xdp_rings[i]);
5589                 i40e_clean_rx_ring(vsi->rx_rings[i]);
5590         }
5591
5592 }
5593
5594 /**
5595  * i40e_setup_tc - configure multiple traffic classes
5596  * @netdev: net device to configure
5597  * @tc: number of traffic classes to enable
5598  **/
5599 static int i40e_setup_tc(struct net_device *netdev, u8 tc)
5600 {
5601         struct i40e_netdev_priv *np = netdev_priv(netdev);
5602         struct i40e_vsi *vsi = np->vsi;
5603         struct i40e_pf *pf = vsi->back;
5604         u8 enabled_tc = 0;
5605         int ret = -EINVAL;
5606         int i;
5607
5608         /* Check if DCB enabled to continue */
5609         if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5610                 netdev_info(netdev, "DCB is not enabled for adapter\n");
5611                 goto exit;
5612         }
5613
5614         /* Check if MFP enabled */
5615         if (pf->flags & I40E_FLAG_MFP_ENABLED) {
5616                 netdev_info(netdev, "Configuring TC not supported in MFP mode\n");
5617                 goto exit;
5618         }
5619
5620         /* Check whether tc count is within enabled limit */
5621         if (tc > i40e_pf_get_num_tc(pf)) {
5622                 netdev_info(netdev, "TC count greater than enabled on link for adapter\n");
5623                 goto exit;
5624         }
5625
5626         /* Generate TC map for number of tc requested */
5627         for (i = 0; i < tc; i++)
5628                 enabled_tc |= BIT(i);
5629
5630         /* Requesting same TC configuration as already enabled */
5631         if (enabled_tc == vsi->tc_config.enabled_tc)
5632                 return 0;
5633
5634         /* Quiesce VSI queues */
5635         i40e_quiesce_vsi(vsi);
5636
5637         /* Configure VSI for enabled TCs */
5638         ret = i40e_vsi_config_tc(vsi, enabled_tc);
5639         if (ret) {
5640                 netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
5641                             vsi->seid);
5642                 goto exit;
5643         }
5644
5645         /* Unquiesce VSI */
5646         i40e_unquiesce_vsi(vsi);
5647
5648 exit:
5649         return ret;
5650 }
5651
5652 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
5653                            void *type_data)
5654 {
5655         struct tc_mqprio_qopt *mqprio = type_data;
5656
5657         if (type != TC_SETUP_MQPRIO)
5658                 return -EOPNOTSUPP;
5659
5660         mqprio->hw = TC_MQPRIO_HW_OFFLOAD_TCS;
5661
5662         return i40e_setup_tc(netdev, mqprio->num_tc);
5663 }
5664
5665 /**
5666  * i40e_open - Called when a network interface is made active
5667  * @netdev: network interface device structure
5668  *
5669  * The open entry point is called when a network interface is made
5670  * active by the system (IFF_UP).  At this point all resources needed
5671  * for transmit and receive operations are allocated, the interrupt
5672  * handler is registered with the OS, the netdev watchdog subtask is
5673  * enabled, and the stack is notified that the interface is ready.
5674  *
5675  * Returns 0 on success, negative value on failure
5676  **/
5677 int i40e_open(struct net_device *netdev)
5678 {
5679         struct i40e_netdev_priv *np = netdev_priv(netdev);
5680         struct i40e_vsi *vsi = np->vsi;
5681         struct i40e_pf *pf = vsi->back;
5682         int err;
5683
5684         /* disallow open during test or if eeprom is broken */
5685         if (test_bit(__I40E_TESTING, pf->state) ||
5686             test_bit(__I40E_BAD_EEPROM, pf->state))
5687                 return -EBUSY;
5688
5689         netif_carrier_off(netdev);
5690
5691         err = i40e_vsi_open(vsi);
5692         if (err)
5693                 return err;
5694
5695         /* configure global TSO hardware offload settings */
5696         wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
5697                                                        TCP_FLAG_FIN) >> 16);
5698         wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
5699                                                        TCP_FLAG_FIN |
5700                                                        TCP_FLAG_CWR) >> 16);
5701         wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
5702
5703         udp_tunnel_get_rx_info(netdev);
5704
5705         return 0;
5706 }
5707
5708 /**
5709  * i40e_vsi_open -
5710  * @vsi: the VSI to open
5711  *
5712  * Finish initialization of the VSI.
5713  *
5714  * Returns 0 on success, negative value on failure
5715  *
5716  * Note: expects to be called while under rtnl_lock()
5717  **/
5718 int i40e_vsi_open(struct i40e_vsi *vsi)
5719 {
5720         struct i40e_pf *pf = vsi->back;
5721         char int_name[I40E_INT_NAME_STR_LEN];
5722         int err;
5723
5724         /* allocate descriptors */
5725         err = i40e_vsi_setup_tx_resources(vsi);
5726         if (err)
5727                 goto err_setup_tx;
5728         err = i40e_vsi_setup_rx_resources(vsi);
5729         if (err)
5730                 goto err_setup_rx;
5731
5732         err = i40e_vsi_configure(vsi);
5733         if (err)
5734                 goto err_setup_rx;
5735
5736         if (vsi->netdev) {
5737                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
5738                          dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
5739                 err = i40e_vsi_request_irq(vsi, int_name);
5740                 if (err)
5741                         goto err_setup_rx;
5742
5743                 /* Notify the stack of the actual queue counts. */
5744                 err = netif_set_real_num_tx_queues(vsi->netdev,
5745                                                    vsi->num_queue_pairs);
5746                 if (err)
5747                         goto err_set_queues;
5748
5749                 err = netif_set_real_num_rx_queues(vsi->netdev,
5750                                                    vsi->num_queue_pairs);
5751                 if (err)
5752                         goto err_set_queues;
5753
5754         } else if (vsi->type == I40E_VSI_FDIR) {
5755                 snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
5756                          dev_driver_string(&pf->pdev->dev),
5757                          dev_name(&pf->pdev->dev));
5758                 err = i40e_vsi_request_irq(vsi, int_name);
5759                 if (err)
5760                         goto err_setup_rx;
5761
5762         } else {
5763                 err = -EINVAL;
5764                 goto err_setup_rx;
5765         }
5766
5767         err = i40e_up_complete(vsi);
5768         if (err)
5769                 goto err_up_complete;
5770
5771         return 0;
5772
5773 err_up_complete:
5774         i40e_down(vsi);
5775 err_set_queues:
5776         i40e_vsi_free_irq(vsi);
5777 err_setup_rx:
5778         i40e_vsi_free_rx_resources(vsi);
5779 err_setup_tx:
5780         i40e_vsi_free_tx_resources(vsi);
5781         if (vsi == pf->vsi[pf->lan_vsi])
5782                 i40e_do_reset(pf, BIT_ULL(__I40E_PF_RESET_REQUESTED), true);
5783
5784         return err;
5785 }
5786
5787 /**
5788  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
5789  * @pf: Pointer to PF
5790  *
5791  * This function destroys the hlist where all the Flow Director
5792  * filters were saved.
5793  **/
5794 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
5795 {
5796         struct i40e_fdir_filter *filter;
5797         struct i40e_flex_pit *pit_entry, *tmp;
5798         struct hlist_node *node2;
5799
5800         hlist_for_each_entry_safe(filter, node2,
5801                                   &pf->fdir_filter_list, fdir_node) {
5802                 hlist_del(&filter->fdir_node);
5803                 kfree(filter);
5804         }
5805
5806         list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
5807                 list_del(&pit_entry->list);
5808                 kfree(pit_entry);
5809         }
5810         INIT_LIST_HEAD(&pf->l3_flex_pit_list);
5811
5812         list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
5813                 list_del(&pit_entry->list);
5814                 kfree(pit_entry);
5815         }
5816         INIT_LIST_HEAD(&pf->l4_flex_pit_list);
5817
5818         pf->fdir_pf_active_filters = 0;
5819         pf->fd_tcp4_filter_cnt = 0;
5820         pf->fd_udp4_filter_cnt = 0;
5821         pf->fd_sctp4_filter_cnt = 0;
5822         pf->fd_ip4_filter_cnt = 0;
5823
5824         /* Reprogram the default input set for TCP/IPv4 */
5825         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
5826                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
5827                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
5828
5829         /* Reprogram the default input set for UDP/IPv4 */
5830         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
5831                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
5832                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
5833
5834         /* Reprogram the default input set for SCTP/IPv4 */
5835         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
5836                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
5837                                 I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
5838
5839         /* Reprogram the default input set for Other/IPv4 */
5840         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
5841                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
5842
5843         i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
5844                                 I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
5845 }
5846
5847 /**
5848  * i40e_close - Disables a network interface
5849  * @netdev: network interface device structure
5850  *
5851  * The close entry point is called when an interface is de-activated
5852  * by the OS.  The hardware is still under the driver's control, but
5853  * this netdev interface is disabled.
5854  *
5855  * Returns 0, this is not allowed to fail
5856  **/
5857 int i40e_close(struct net_device *netdev)
5858 {
5859         struct i40e_netdev_priv *np = netdev_priv(netdev);
5860         struct i40e_vsi *vsi = np->vsi;
5861
5862         i40e_vsi_close(vsi);
5863
5864         return 0;
5865 }
5866
5867 /**
5868  * i40e_do_reset - Start a PF or Core Reset sequence
5869  * @pf: board private structure
5870  * @reset_flags: which reset is requested
5871  * @lock_acquired: indicates whether or not the lock has been acquired
5872  * before this function was called.
5873  *
5874  * The essential difference in resets is that the PF Reset
5875  * doesn't clear the packet buffers, doesn't reset the PE
5876  * firmware, and doesn't bother the other PFs on the chip.
5877  **/
5878 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
5879 {
5880         u32 val;
5881
5882         WARN_ON(in_interrupt());
5883
5884
5885         /* do the biggest reset indicated */
5886         if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
5887
5888                 /* Request a Global Reset
5889                  *
5890                  * This will start the chip's countdown to the actual full
5891                  * chip reset event, and a warning interrupt to be sent
5892                  * to all PFs, including the requestor.  Our handler
5893                  * for the warning interrupt will deal with the shutdown
5894                  * and recovery of the switch setup.
5895                  */
5896                 dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
5897                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
5898                 val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
5899                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
5900
5901         } else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
5902
5903                 /* Request a Core Reset
5904                  *
5905                  * Same as Global Reset, except does *not* include the MAC/PHY
5906                  */
5907                 dev_dbg(&pf->pdev->dev, "CoreR requested\n");
5908                 val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
5909                 val |= I40E_GLGEN_RTRIG_CORER_MASK;
5910                 wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
5911                 i40e_flush(&pf->hw);
5912
5913         } else if (reset_flags & BIT_ULL(__I40E_PF_RESET_REQUESTED)) {
5914
5915                 /* Request a PF Reset
5916                  *
5917                  * Resets only the PF-specific registers
5918                  *
5919                  * This goes directly to the tear-down and rebuild of
5920                  * the switch, since we need to do all the recovery as
5921                  * for the Core Reset.
5922                  */
5923                 dev_dbg(&pf->pdev->dev, "PFR requested\n");
5924                 i40e_handle_reset_warning(pf, lock_acquired);
5925
5926         } else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
5927                 int v;
5928
5929                 /* Find the VSI(s) that requested a re-init */
5930                 dev_info(&pf->pdev->dev,
5931                          "VSI reinit requested\n");
5932                 for (v = 0; v < pf->num_alloc_vsi; v++) {
5933                         struct i40e_vsi *vsi = pf->vsi[v];
5934
5935                         if (vsi != NULL &&
5936                             test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
5937                                                vsi->state))
5938                                 i40e_vsi_reinit_locked(pf->vsi[v]);
5939                 }
5940         } else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
5941                 int v;
5942
5943                 /* Find the VSI(s) that needs to be brought down */
5944                 dev_info(&pf->pdev->dev, "VSI down requested\n");
5945                 for (v = 0; v < pf->num_alloc_vsi; v++) {
5946                         struct i40e_vsi *vsi = pf->vsi[v];
5947
5948                         if (vsi != NULL &&
5949                             test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
5950                                                vsi->state)) {
5951                                 set_bit(__I40E_VSI_DOWN, vsi->state);
5952                                 i40e_down(vsi);
5953                         }
5954                 }
5955         } else {
5956                 dev_info(&pf->pdev->dev,
5957                          "bad reset request 0x%08x\n", reset_flags);
5958         }
5959 }
5960
5961 #ifdef CONFIG_I40E_DCB
5962 /**
5963  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
5964  * @pf: board private structure
5965  * @old_cfg: current DCB config
5966  * @new_cfg: new DCB config
5967  **/
5968 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
5969                             struct i40e_dcbx_config *old_cfg,
5970                             struct i40e_dcbx_config *new_cfg)
5971 {
5972         bool need_reconfig = false;
5973
5974         /* Check if ETS configuration has changed */
5975         if (memcmp(&new_cfg->etscfg,
5976                    &old_cfg->etscfg,
5977                    sizeof(new_cfg->etscfg))) {
5978                 /* If Priority Table has changed reconfig is needed */
5979                 if (memcmp(&new_cfg->etscfg.prioritytable,
5980                            &old_cfg->etscfg.prioritytable,
5981                            sizeof(new_cfg->etscfg.prioritytable))) {
5982                         need_reconfig = true;
5983                         dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
5984                 }
5985
5986                 if (memcmp(&new_cfg->etscfg.tcbwtable,
5987                            &old_cfg->etscfg.tcbwtable,
5988                            sizeof(new_cfg->etscfg.tcbwtable)))
5989                         dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
5990
5991                 if (memcmp(&new_cfg->etscfg.tsatable,
5992                            &old_cfg->etscfg.tsatable,
5993                            sizeof(new_cfg->etscfg.tsatable)))
5994                         dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
5995         }
5996
5997         /* Check if PFC configuration has changed */
5998         if (memcmp(&new_cfg->pfc,
5999                    &old_cfg->pfc,
6000                    sizeof(new_cfg->pfc))) {
6001                 need_reconfig = true;
6002                 dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
6003         }
6004
6005         /* Check if APP Table has changed */
6006         if (memcmp(&new_cfg->app,
6007                    &old_cfg->app,
6008                    sizeof(new_cfg->app))) {
6009                 need_reconfig = true;
6010                 dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
6011         }
6012
6013         dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
6014         return need_reconfig;
6015 }
6016
6017 /**
6018  * i40e_handle_lldp_event - Handle LLDP Change MIB event
6019  * @pf: board private structure
6020  * @e: event info posted on ARQ
6021  **/
6022 static int i40e_handle_lldp_event(struct i40e_pf *pf,
6023                                   struct i40e_arq_event_info *e)
6024 {
6025         struct i40e_aqc_lldp_get_mib *mib =
6026                 (struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
6027         struct i40e_hw *hw = &pf->hw;
6028         struct i40e_dcbx_config tmp_dcbx_cfg;
6029         bool need_reconfig = false;
6030         int ret = 0;
6031         u8 type;
6032
6033         /* Not DCB capable or capability disabled */
6034         if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
6035                 return ret;
6036
6037         /* Ignore if event is not for Nearest Bridge */
6038         type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
6039                 & I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
6040         dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
6041         if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
6042                 return ret;
6043
6044         /* Check MIB Type and return if event for Remote MIB update */
6045         type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
6046         dev_dbg(&pf->pdev->dev,
6047                 "LLDP event mib type %s\n", type ? "remote" : "local");
6048         if (type == I40E_AQ_LLDP_MIB_REMOTE) {
6049                 /* Update the remote cached instance and return */
6050                 ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
6051                                 I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
6052                                 &hw->remote_dcbx_config);
6053                 goto exit;
6054         }
6055
6056         /* Store the old configuration */
6057         tmp_dcbx_cfg = hw->local_dcbx_config;
6058
6059         /* Reset the old DCBx configuration data */
6060         memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
6061         /* Get updated DCBX data from firmware */
6062         ret = i40e_get_dcb_config(&pf->hw);
6063         if (ret) {
6064                 dev_info(&pf->pdev->dev,
6065                          "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
6066                          i40e_stat_str(&pf->hw, ret),
6067                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6068                 goto exit;
6069         }
6070
6071         /* No change detected in DCBX configs */
6072         if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
6073                     sizeof(tmp_dcbx_cfg))) {
6074                 dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
6075                 goto exit;
6076         }
6077
6078         need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
6079                                                &hw->local_dcbx_config);
6080
6081         i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
6082
6083         if (!need_reconfig)
6084                 goto exit;
6085
6086         /* Enable DCB tagging only when more than one TC */
6087         if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
6088                 pf->flags |= I40E_FLAG_DCB_ENABLED;
6089         else
6090                 pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6091
6092         set_bit(__I40E_PORT_SUSPENDED, pf->state);
6093         /* Reconfiguration needed quiesce all VSIs */
6094         i40e_pf_quiesce_all_vsi(pf);
6095
6096         /* Changes in configuration update VEB/VSI */
6097         i40e_dcb_reconfigure(pf);
6098
6099         ret = i40e_resume_port_tx(pf);
6100
6101         clear_bit(__I40E_PORT_SUSPENDED, pf->state);
6102         /* In case of error no point in resuming VSIs */
6103         if (ret)
6104                 goto exit;
6105
6106         /* Wait for the PF's queues to be disabled */
6107         ret = i40e_pf_wait_queues_disabled(pf);
6108         if (ret) {
6109                 /* Schedule PF reset to recover */
6110                 set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6111                 i40e_service_event_schedule(pf);
6112         } else {
6113                 i40e_pf_unquiesce_all_vsi(pf);
6114         pf->flags |= (I40E_FLAG_SERVICE_CLIENT_REQUESTED |
6115                       I40E_FLAG_CLIENT_L2_CHANGE);
6116         }
6117
6118 exit:
6119         return ret;
6120 }
6121 #endif /* CONFIG_I40E_DCB */
6122
6123 /**
6124  * i40e_do_reset_safe - Protected reset path for userland calls.
6125  * @pf: board private structure
6126  * @reset_flags: which reset is requested
6127  *
6128  **/
6129 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
6130 {
6131         rtnl_lock();
6132         i40e_do_reset(pf, reset_flags, true);
6133         rtnl_unlock();
6134 }
6135
6136 /**
6137  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
6138  * @pf: board private structure
6139  * @e: event info posted on ARQ
6140  *
6141  * Handler for LAN Queue Overflow Event generated by the firmware for PF
6142  * and VF queues
6143  **/
6144 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
6145                                            struct i40e_arq_event_info *e)
6146 {
6147         struct i40e_aqc_lan_overflow *data =
6148                 (struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
6149         u32 queue = le32_to_cpu(data->prtdcb_rupto);
6150         u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
6151         struct i40e_hw *hw = &pf->hw;
6152         struct i40e_vf *vf;
6153         u16 vf_id;
6154
6155         dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
6156                 queue, qtx_ctl);
6157
6158         /* Queue belongs to VF, find the VF and issue VF reset */
6159         if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
6160             >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
6161                 vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
6162                          >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
6163                 vf_id -= hw->func_caps.vf_base_id;
6164                 vf = &pf->vf[vf_id];
6165                 i40e_vc_notify_vf_reset(vf);
6166                 /* Allow VF to process pending reset notification */
6167                 msleep(20);
6168                 i40e_reset_vf(vf, false);
6169         }
6170 }
6171
6172 /**
6173  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
6174  * @pf: board private structure
6175  **/
6176 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
6177 {
6178         u32 val, fcnt_prog;
6179
6180         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
6181         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
6182         return fcnt_prog;
6183 }
6184
6185 /**
6186  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
6187  * @pf: board private structure
6188  **/
6189 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
6190 {
6191         u32 val, fcnt_prog;
6192
6193         val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
6194         fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
6195                     ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
6196                       I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
6197         return fcnt_prog;
6198 }
6199
6200 /**
6201  * i40e_get_global_fd_count - Get total FD filters programmed on device
6202  * @pf: board private structure
6203  **/
6204 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
6205 {
6206         u32 val, fcnt_prog;
6207
6208         val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
6209         fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
6210                     ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
6211                      I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
6212         return fcnt_prog;
6213 }
6214
6215 /**
6216  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
6217  * @pf: board private structure
6218  **/
6219 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
6220 {
6221         struct i40e_fdir_filter *filter;
6222         u32 fcnt_prog, fcnt_avail;
6223         struct hlist_node *node;
6224
6225         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
6226                 return;
6227
6228         /* Check if we have enough room to re-enable FDir SB capability. */
6229         fcnt_prog = i40e_get_global_fd_count(pf);
6230         fcnt_avail = pf->fdir_pf_filter_count;
6231         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
6232             (pf->fd_add_err == 0) ||
6233             (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt)) {
6234                 if (pf->flags & I40E_FLAG_FD_SB_AUTO_DISABLED) {
6235                         pf->flags &= ~I40E_FLAG_FD_SB_AUTO_DISABLED;
6236                         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
6237                             (I40E_DEBUG_FD & pf->hw.debug_mask))
6238                                 dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
6239                 }
6240         }
6241
6242         /* We should wait for even more space before re-enabling ATR.
6243          * Additionally, we cannot enable ATR as long as we still have TCP SB
6244          * rules active.
6245          */
6246         if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
6247             (pf->fd_tcp4_filter_cnt == 0)) {
6248                 if (pf->flags & I40E_FLAG_FD_ATR_AUTO_DISABLED) {
6249                         pf->flags &= ~I40E_FLAG_FD_ATR_AUTO_DISABLED;
6250                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
6251                             (I40E_DEBUG_FD & pf->hw.debug_mask))
6252                                 dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
6253                 }
6254         }
6255
6256         /* if hw had a problem adding a filter, delete it */
6257         if (pf->fd_inv > 0) {
6258                 hlist_for_each_entry_safe(filter, node,
6259                                           &pf->fdir_filter_list, fdir_node) {
6260                         if (filter->fd_id == pf->fd_inv) {
6261                                 hlist_del(&filter->fdir_node);
6262                                 kfree(filter);
6263                                 pf->fdir_pf_active_filters--;
6264                         }
6265                 }
6266         }
6267 }
6268
6269 #define I40E_MIN_FD_FLUSH_INTERVAL 10
6270 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
6271 /**
6272  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
6273  * @pf: board private structure
6274  **/
6275 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
6276 {
6277         unsigned long min_flush_time;
6278         int flush_wait_retry = 50;
6279         bool disable_atr = false;
6280         int fd_room;
6281         int reg;
6282
6283         if (!time_after(jiffies, pf->fd_flush_timestamp +
6284                                  (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
6285                 return;
6286
6287         /* If the flush is happening too quick and we have mostly SB rules we
6288          * should not re-enable ATR for some time.
6289          */
6290         min_flush_time = pf->fd_flush_timestamp +
6291                          (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
6292         fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
6293
6294         if (!(time_after(jiffies, min_flush_time)) &&
6295             (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
6296                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
6297                         dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
6298                 disable_atr = true;
6299         }
6300
6301         pf->fd_flush_timestamp = jiffies;
6302         pf->flags |= I40E_FLAG_FD_ATR_AUTO_DISABLED;
6303         /* flush all filters */
6304         wr32(&pf->hw, I40E_PFQF_CTL_1,
6305              I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
6306         i40e_flush(&pf->hw);
6307         pf->fd_flush_cnt++;
6308         pf->fd_add_err = 0;
6309         do {
6310                 /* Check FD flush status every 5-6msec */
6311                 usleep_range(5000, 6000);
6312                 reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
6313                 if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
6314                         break;
6315         } while (flush_wait_retry--);
6316         if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
6317                 dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
6318         } else {
6319                 /* replay sideband filters */
6320                 i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
6321                 if (!disable_atr && !pf->fd_tcp4_filter_cnt)
6322                         pf->flags &= ~I40E_FLAG_FD_ATR_AUTO_DISABLED;
6323                 clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
6324                 if (I40E_DEBUG_FD & pf->hw.debug_mask)
6325                         dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
6326         }
6327 }
6328
6329 /**
6330  * i40e_get_current_atr_count - Get the count of total FD ATR filters programmed
6331  * @pf: board private structure
6332  **/
6333 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
6334 {
6335         return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
6336 }
6337
6338 /* We can see up to 256 filter programming desc in transit if the filters are
6339  * being applied really fast; before we see the first
6340  * filter miss error on Rx queue 0. Accumulating enough error messages before
6341  * reacting will make sure we don't cause flush too often.
6342  */
6343 #define I40E_MAX_FD_PROGRAM_ERROR 256
6344
6345 /**
6346  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
6347  * @pf: board private structure
6348  **/
6349 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
6350 {
6351
6352         /* if interface is down do nothing */
6353         if (test_bit(__I40E_DOWN, pf->state))
6354                 return;
6355
6356         if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
6357                 i40e_fdir_flush_and_replay(pf);
6358
6359         i40e_fdir_check_and_reenable(pf);
6360
6361 }
6362
6363 /**
6364  * i40e_vsi_link_event - notify VSI of a link event
6365  * @vsi: vsi to be notified
6366  * @link_up: link up or down
6367  **/
6368 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
6369 {
6370         if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
6371                 return;
6372
6373         switch (vsi->type) {
6374         case I40E_VSI_MAIN:
6375                 if (!vsi->netdev || !vsi->netdev_registered)
6376                         break;
6377
6378                 if (link_up) {
6379                         netif_carrier_on(vsi->netdev);
6380                         netif_tx_wake_all_queues(vsi->netdev);
6381                 } else {
6382                         netif_carrier_off(vsi->netdev);
6383                         netif_tx_stop_all_queues(vsi->netdev);
6384                 }
6385                 break;
6386
6387         case I40E_VSI_SRIOV:
6388         case I40E_VSI_VMDQ2:
6389         case I40E_VSI_CTRL:
6390         case I40E_VSI_IWARP:
6391         case I40E_VSI_MIRROR:
6392         default:
6393                 /* there is no notification for other VSIs */
6394                 break;
6395         }
6396 }
6397
6398 /**
6399  * i40e_veb_link_event - notify elements on the veb of a link event
6400  * @veb: veb to be notified
6401  * @link_up: link up or down
6402  **/
6403 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
6404 {
6405         struct i40e_pf *pf;
6406         int i;
6407
6408         if (!veb || !veb->pf)
6409                 return;
6410         pf = veb->pf;
6411
6412         /* depth first... */
6413         for (i = 0; i < I40E_MAX_VEB; i++)
6414                 if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
6415                         i40e_veb_link_event(pf->veb[i], link_up);
6416
6417         /* ... now the local VSIs */
6418         for (i = 0; i < pf->num_alloc_vsi; i++)
6419                 if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
6420                         i40e_vsi_link_event(pf->vsi[i], link_up);
6421 }
6422
6423 /**
6424  * i40e_link_event - Update netif_carrier status
6425  * @pf: board private structure
6426  **/
6427 static void i40e_link_event(struct i40e_pf *pf)
6428 {
6429         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
6430         u8 new_link_speed, old_link_speed;
6431         i40e_status status;
6432         bool new_link, old_link;
6433
6434         /* save off old link status information */
6435         pf->hw.phy.link_info_old = pf->hw.phy.link_info;
6436
6437         /* set this to force the get_link_status call to refresh state */
6438         pf->hw.phy.get_link_info = true;
6439
6440         old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
6441
6442         status = i40e_get_link_status(&pf->hw, &new_link);
6443
6444         /* On success, disable temp link polling */
6445         if (status == I40E_SUCCESS) {
6446                 if (pf->flags & I40E_FLAG_TEMP_LINK_POLLING)
6447                         pf->flags &= ~I40E_FLAG_TEMP_LINK_POLLING;
6448         } else {
6449                 /* Enable link polling temporarily until i40e_get_link_status
6450                  * returns I40E_SUCCESS
6451                  */
6452                 pf->flags |= I40E_FLAG_TEMP_LINK_POLLING;
6453                 dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
6454                         status);
6455                 return;
6456         }
6457
6458         old_link_speed = pf->hw.phy.link_info_old.link_speed;
6459         new_link_speed = pf->hw.phy.link_info.link_speed;
6460
6461         if (new_link == old_link &&
6462             new_link_speed == old_link_speed &&
6463             (test_bit(__I40E_VSI_DOWN, vsi->state) ||
6464              new_link == netif_carrier_ok(vsi->netdev)))
6465                 return;
6466
6467         if (!test_bit(__I40E_VSI_DOWN, vsi->state))
6468                 i40e_print_link_message(vsi, new_link);
6469
6470         /* Notify the base of the switch tree connected to
6471          * the link.  Floating VEBs are not notified.
6472          */
6473         if (pf->lan_veb != I40E_NO_VEB && pf->veb[pf->lan_veb])
6474                 i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
6475         else
6476                 i40e_vsi_link_event(vsi, new_link);
6477
6478         if (pf->vf)
6479                 i40e_vc_notify_link_state(pf);
6480
6481         if (pf->flags & I40E_FLAG_PTP)
6482                 i40e_ptp_set_increment(pf);
6483 }
6484
6485 /**
6486  * i40e_watchdog_subtask - periodic checks not using event driven response
6487  * @pf: board private structure
6488  **/
6489 static void i40e_watchdog_subtask(struct i40e_pf *pf)
6490 {
6491         int i;
6492
6493         /* if interface is down do nothing */
6494         if (test_bit(__I40E_DOWN, pf->state) ||
6495             test_bit(__I40E_CONFIG_BUSY, pf->state))
6496                 return;
6497
6498         /* make sure we don't do these things too often */
6499         if (time_before(jiffies, (pf->service_timer_previous +
6500                                   pf->service_timer_period)))
6501                 return;
6502         pf->service_timer_previous = jiffies;
6503
6504         if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
6505             (pf->flags & I40E_FLAG_TEMP_LINK_POLLING))
6506                 i40e_link_event(pf);
6507
6508         /* Update the stats for active netdevs so the network stack
6509          * can look at updated numbers whenever it cares to
6510          */
6511         for (i = 0; i < pf->num_alloc_vsi; i++)
6512                 if (pf->vsi[i] && pf->vsi[i]->netdev)
6513                         i40e_update_stats(pf->vsi[i]);
6514
6515         if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
6516                 /* Update the stats for the active switching components */
6517                 for (i = 0; i < I40E_MAX_VEB; i++)
6518                         if (pf->veb[i])
6519                                 i40e_update_veb_stats(pf->veb[i]);
6520         }
6521
6522         i40e_ptp_rx_hang(pf);
6523         i40e_ptp_tx_hang(pf);
6524 }
6525
6526 /**
6527  * i40e_reset_subtask - Set up for resetting the device and driver
6528  * @pf: board private structure
6529  **/
6530 static void i40e_reset_subtask(struct i40e_pf *pf)
6531 {
6532         u32 reset_flags = 0;
6533
6534         if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
6535                 reset_flags |= BIT(__I40E_REINIT_REQUESTED);
6536                 clear_bit(__I40E_REINIT_REQUESTED, pf->state);
6537         }
6538         if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
6539                 reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
6540                 clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6541         }
6542         if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
6543                 reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
6544                 clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
6545         }
6546         if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
6547                 reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
6548                 clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
6549         }
6550         if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
6551                 reset_flags |= BIT(__I40E_DOWN_REQUESTED);
6552                 clear_bit(__I40E_DOWN_REQUESTED, pf->state);
6553         }
6554
6555         /* If there's a recovery already waiting, it takes
6556          * precedence before starting a new reset sequence.
6557          */
6558         if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
6559                 i40e_prep_for_reset(pf, false);
6560                 i40e_reset(pf);
6561                 i40e_rebuild(pf, false, false);
6562         }
6563
6564         /* If we're already down or resetting, just bail */
6565         if (reset_flags &&
6566             !test_bit(__I40E_DOWN, pf->state) &&
6567             !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
6568                 i40e_do_reset(pf, reset_flags, false);
6569         }
6570 }
6571
6572 /**
6573  * i40e_handle_link_event - Handle link event
6574  * @pf: board private structure
6575  * @e: event info posted on ARQ
6576  **/
6577 static void i40e_handle_link_event(struct i40e_pf *pf,
6578                                    struct i40e_arq_event_info *e)
6579 {
6580         struct i40e_aqc_get_link_status *status =
6581                 (struct i40e_aqc_get_link_status *)&e->desc.params.raw;
6582
6583         /* Do a new status request to re-enable LSE reporting
6584          * and load new status information into the hw struct
6585          * This completely ignores any state information
6586          * in the ARQ event info, instead choosing to always
6587          * issue the AQ update link status command.
6588          */
6589         i40e_link_event(pf);
6590
6591         /* check for unqualified module, if link is down */
6592         if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
6593             (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
6594             (!(status->link_info & I40E_AQ_LINK_UP)))
6595                 dev_err(&pf->pdev->dev,
6596                         "The driver failed to link because an unqualified module was detected.\n");
6597 }
6598
6599 /**
6600  * i40e_clean_adminq_subtask - Clean the AdminQ rings
6601  * @pf: board private structure
6602  **/
6603 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
6604 {
6605         struct i40e_arq_event_info event;
6606         struct i40e_hw *hw = &pf->hw;
6607         u16 pending, i = 0;
6608         i40e_status ret;
6609         u16 opcode;
6610         u32 oldval;
6611         u32 val;
6612
6613         /* Do not run clean AQ when PF reset fails */
6614         if (test_bit(__I40E_RESET_FAILED, pf->state))
6615                 return;
6616
6617         /* check for error indications */
6618         val = rd32(&pf->hw, pf->hw.aq.arq.len);
6619         oldval = val;
6620         if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
6621                 if (hw->debug_mask & I40E_DEBUG_AQ)
6622                         dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
6623                 val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
6624         }
6625         if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
6626                 if (hw->debug_mask & I40E_DEBUG_AQ)
6627                         dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
6628                 val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
6629                 pf->arq_overflows++;
6630         }
6631         if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
6632                 if (hw->debug_mask & I40E_DEBUG_AQ)
6633                         dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
6634                 val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
6635         }
6636         if (oldval != val)
6637                 wr32(&pf->hw, pf->hw.aq.arq.len, val);
6638
6639         val = rd32(&pf->hw, pf->hw.aq.asq.len);
6640         oldval = val;
6641         if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
6642                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
6643                         dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
6644                 val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
6645         }
6646         if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
6647                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
6648                         dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
6649                 val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
6650         }
6651         if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
6652                 if (pf->hw.debug_mask & I40E_DEBUG_AQ)
6653                         dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
6654                 val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
6655         }
6656         if (oldval != val)
6657                 wr32(&pf->hw, pf->hw.aq.asq.len, val);
6658
6659         event.buf_len = I40E_MAX_AQ_BUF_SIZE;
6660         event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
6661         if (!event.msg_buf)
6662                 return;
6663
6664         do {
6665                 ret = i40e_clean_arq_element(hw, &event, &pending);
6666                 if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
6667                         break;
6668                 else if (ret) {
6669                         dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
6670                         break;
6671                 }
6672
6673                 opcode = le16_to_cpu(event.desc.opcode);
6674                 switch (opcode) {
6675
6676                 case i40e_aqc_opc_get_link_status:
6677                         i40e_handle_link_event(pf, &event);
6678                         break;
6679                 case i40e_aqc_opc_send_msg_to_pf:
6680                         ret = i40e_vc_process_vf_msg(pf,
6681                                         le16_to_cpu(event.desc.retval),
6682                                         le32_to_cpu(event.desc.cookie_high),
6683                                         le32_to_cpu(event.desc.cookie_low),
6684                                         event.msg_buf,
6685                                         event.msg_len);
6686                         break;
6687                 case i40e_aqc_opc_lldp_update_mib:
6688                         dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
6689 #ifdef CONFIG_I40E_DCB
6690                         rtnl_lock();
6691                         ret = i40e_handle_lldp_event(pf, &event);
6692                         rtnl_unlock();
6693 #endif /* CONFIG_I40E_DCB */
6694                         break;
6695                 case i40e_aqc_opc_event_lan_overflow:
6696                         dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
6697                         i40e_handle_lan_overflow_event(pf, &event);
6698                         break;
6699                 case i40e_aqc_opc_send_msg_to_peer:
6700                         dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
6701                         break;
6702                 case i40e_aqc_opc_nvm_erase:
6703                 case i40e_aqc_opc_nvm_update:
6704                 case i40e_aqc_opc_oem_post_update:
6705                         i40e_debug(&pf->hw, I40E_DEBUG_NVM,
6706                                    "ARQ NVM operation 0x%04x completed\n",
6707                                    opcode);
6708                         break;
6709                 default:
6710                         dev_info(&pf->pdev->dev,
6711                                  "ARQ: Unknown event 0x%04x ignored\n",
6712                                  opcode);
6713                         break;
6714                 }
6715         } while (i++ < pf->adminq_work_limit);
6716
6717         if (i < pf->adminq_work_limit)
6718                 clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
6719
6720         /* re-enable Admin queue interrupt cause */
6721         val = rd32(hw, I40E_PFINT_ICR0_ENA);
6722         val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
6723         wr32(hw, I40E_PFINT_ICR0_ENA, val);
6724         i40e_flush(hw);
6725
6726         kfree(event.msg_buf);
6727 }
6728
6729 /**
6730  * i40e_verify_eeprom - make sure eeprom is good to use
6731  * @pf: board private structure
6732  **/
6733 static void i40e_verify_eeprom(struct i40e_pf *pf)
6734 {
6735         int err;
6736
6737         err = i40e_diag_eeprom_test(&pf->hw);
6738         if (err) {
6739                 /* retry in case of garbage read */
6740                 err = i40e_diag_eeprom_test(&pf->hw);
6741                 if (err) {
6742                         dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
6743                                  err);
6744                         set_bit(__I40E_BAD_EEPROM, pf->state);
6745                 }
6746         }
6747
6748         if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
6749                 dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
6750                 clear_bit(__I40E_BAD_EEPROM, pf->state);
6751         }
6752 }
6753
6754 /**
6755  * i40e_enable_pf_switch_lb
6756  * @pf: pointer to the PF structure
6757  *
6758  * enable switch loop back or die - no point in a return value
6759  **/
6760 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
6761 {
6762         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
6763         struct i40e_vsi_context ctxt;
6764         int ret;
6765
6766         ctxt.seid = pf->main_vsi_seid;
6767         ctxt.pf_num = pf->hw.pf_id;
6768         ctxt.vf_num = 0;
6769         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
6770         if (ret) {
6771                 dev_info(&pf->pdev->dev,
6772                          "couldn't get PF vsi config, err %s aq_err %s\n",
6773                          i40e_stat_str(&pf->hw, ret),
6774                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6775                 return;
6776         }
6777         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
6778         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6779         ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6780
6781         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
6782         if (ret) {
6783                 dev_info(&pf->pdev->dev,
6784                          "update vsi switch failed, err %s aq_err %s\n",
6785                          i40e_stat_str(&pf->hw, ret),
6786                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6787         }
6788 }
6789
6790 /**
6791  * i40e_disable_pf_switch_lb
6792  * @pf: pointer to the PF structure
6793  *
6794  * disable switch loop back or die - no point in a return value
6795  **/
6796 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
6797 {
6798         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
6799         struct i40e_vsi_context ctxt;
6800         int ret;
6801
6802         ctxt.seid = pf->main_vsi_seid;
6803         ctxt.pf_num = pf->hw.pf_id;
6804         ctxt.vf_num = 0;
6805         ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
6806         if (ret) {
6807                 dev_info(&pf->pdev->dev,
6808                          "couldn't get PF vsi config, err %s aq_err %s\n",
6809                          i40e_stat_str(&pf->hw, ret),
6810                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6811                 return;
6812         }
6813         ctxt.flags = I40E_AQ_VSI_TYPE_PF;
6814         ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
6815         ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
6816
6817         ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
6818         if (ret) {
6819                 dev_info(&pf->pdev->dev,
6820                          "update vsi switch failed, err %s aq_err %s\n",
6821                          i40e_stat_str(&pf->hw, ret),
6822                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6823         }
6824 }
6825
6826 /**
6827  * i40e_config_bridge_mode - Configure the HW bridge mode
6828  * @veb: pointer to the bridge instance
6829  *
6830  * Configure the loop back mode for the LAN VSI that is downlink to the
6831  * specified HW bridge instance. It is expected this function is called
6832  * when a new HW bridge is instantiated.
6833  **/
6834 static void i40e_config_bridge_mode(struct i40e_veb *veb)
6835 {
6836         struct i40e_pf *pf = veb->pf;
6837
6838         if (pf->hw.debug_mask & I40E_DEBUG_LAN)
6839                 dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
6840                          veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
6841         if (veb->bridge_mode & BRIDGE_MODE_VEPA)
6842                 i40e_disable_pf_switch_lb(pf);
6843         else
6844                 i40e_enable_pf_switch_lb(pf);
6845 }
6846
6847 /**
6848  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
6849  * @veb: pointer to the VEB instance
6850  *
6851  * This is a recursive function that first builds the attached VSIs then
6852  * recurses in to build the next layer of VEB.  We track the connections
6853  * through our own index numbers because the seid's from the HW could
6854  * change across the reset.
6855  **/
6856 static int i40e_reconstitute_veb(struct i40e_veb *veb)
6857 {
6858         struct i40e_vsi *ctl_vsi = NULL;
6859         struct i40e_pf *pf = veb->pf;
6860         int v, veb_idx;
6861         int ret;
6862
6863         /* build VSI that owns this VEB, temporarily attached to base VEB */
6864         for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
6865                 if (pf->vsi[v] &&
6866                     pf->vsi[v]->veb_idx == veb->idx &&
6867                     pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
6868                         ctl_vsi = pf->vsi[v];
6869                         break;
6870                 }
6871         }
6872         if (!ctl_vsi) {
6873                 dev_info(&pf->pdev->dev,
6874                          "missing owner VSI for veb_idx %d\n", veb->idx);
6875                 ret = -ENOENT;
6876                 goto end_reconstitute;
6877         }
6878         if (ctl_vsi != pf->vsi[pf->lan_vsi])
6879                 ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6880         ret = i40e_add_vsi(ctl_vsi);
6881         if (ret) {
6882                 dev_info(&pf->pdev->dev,
6883                          "rebuild of veb_idx %d owner VSI failed: %d\n",
6884                          veb->idx, ret);
6885                 goto end_reconstitute;
6886         }
6887         i40e_vsi_reset_stats(ctl_vsi);
6888
6889         /* create the VEB in the switch and move the VSI onto the VEB */
6890         ret = i40e_add_veb(veb, ctl_vsi);
6891         if (ret)
6892                 goto end_reconstitute;
6893
6894         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
6895                 veb->bridge_mode = BRIDGE_MODE_VEB;
6896         else
6897                 veb->bridge_mode = BRIDGE_MODE_VEPA;
6898         i40e_config_bridge_mode(veb);
6899
6900         /* create the remaining VSIs attached to this VEB */
6901         for (v = 0; v < pf->num_alloc_vsi; v++) {
6902                 if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
6903                         continue;
6904
6905                 if (pf->vsi[v]->veb_idx == veb->idx) {
6906                         struct i40e_vsi *vsi = pf->vsi[v];
6907
6908                         vsi->uplink_seid = veb->seid;
6909                         ret = i40e_add_vsi(vsi);
6910                         if (ret) {
6911                                 dev_info(&pf->pdev->dev,
6912                                          "rebuild of vsi_idx %d failed: %d\n",
6913                                          v, ret);
6914                                 goto end_reconstitute;
6915                         }
6916                         i40e_vsi_reset_stats(vsi);
6917                 }
6918         }
6919
6920         /* create any VEBs attached to this VEB - RECURSION */
6921         for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
6922                 if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
6923                         pf->veb[veb_idx]->uplink_seid = veb->seid;
6924                         ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
6925                         if (ret)
6926                                 break;
6927                 }
6928         }
6929
6930 end_reconstitute:
6931         return ret;
6932 }
6933
6934 /**
6935  * i40e_get_capabilities - get info about the HW
6936  * @pf: the PF struct
6937  **/
6938 static int i40e_get_capabilities(struct i40e_pf *pf)
6939 {
6940         struct i40e_aqc_list_capabilities_element_resp *cap_buf;
6941         u16 data_size;
6942         int buf_len;
6943         int err;
6944
6945         buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
6946         do {
6947                 cap_buf = kzalloc(buf_len, GFP_KERNEL);
6948                 if (!cap_buf)
6949                         return -ENOMEM;
6950
6951                 /* this loads the data into the hw struct for us */
6952                 err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
6953                                             &data_size,
6954                                             i40e_aqc_opc_list_func_capabilities,
6955                                             NULL);
6956                 /* data loaded, buffer no longer needed */
6957                 kfree(cap_buf);
6958
6959                 if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
6960                         /* retry with a larger buffer */
6961                         buf_len = data_size;
6962                 } else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK || err) {
6963                         dev_info(&pf->pdev->dev,
6964                                  "capability discovery failed, err %s aq_err %s\n",
6965                                  i40e_stat_str(&pf->hw, err),
6966                                  i40e_aq_str(&pf->hw,
6967                                              pf->hw.aq.asq_last_status));
6968                         return -ENODEV;
6969                 }
6970         } while (err);
6971
6972         if (pf->hw.debug_mask & I40E_DEBUG_USER)
6973                 dev_info(&pf->pdev->dev,
6974                          "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",
6975                          pf->hw.pf_id, pf->hw.func_caps.num_vfs,
6976                          pf->hw.func_caps.num_msix_vectors,
6977                          pf->hw.func_caps.num_msix_vectors_vf,
6978                          pf->hw.func_caps.fd_filters_guaranteed,
6979                          pf->hw.func_caps.fd_filters_best_effort,
6980                          pf->hw.func_caps.num_tx_qp,
6981                          pf->hw.func_caps.num_vsis);
6982
6983 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
6984                        + pf->hw.func_caps.num_vfs)
6985         if (pf->hw.revision_id == 0 && (DEF_NUM_VSI > pf->hw.func_caps.num_vsis)) {
6986                 dev_info(&pf->pdev->dev,
6987                          "got num_vsis %d, setting num_vsis to %d\n",
6988                          pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
6989                 pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
6990         }
6991
6992         return 0;
6993 }
6994
6995 static int i40e_vsi_clear(struct i40e_vsi *vsi);
6996
6997 /**
6998  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
6999  * @pf: board private structure
7000  **/
7001 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
7002 {
7003         struct i40e_vsi *vsi;
7004
7005         /* quick workaround for an NVM issue that leaves a critical register
7006          * uninitialized
7007          */
7008         if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
7009                 static const u32 hkey[] = {
7010                         0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
7011                         0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
7012                         0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
7013                         0x95b3a76d};
7014                 int i;
7015
7016                 for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
7017                         wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
7018         }
7019
7020         if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
7021                 return;
7022
7023         /* find existing VSI and see if it needs configuring */
7024         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
7025
7026         /* create a new VSI if none exists */
7027         if (!vsi) {
7028                 vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
7029                                      pf->vsi[pf->lan_vsi]->seid, 0);
7030                 if (!vsi) {
7031                         dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
7032                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
7033                         return;
7034                 }
7035         }
7036
7037         i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
7038 }
7039
7040 /**
7041  * i40e_fdir_teardown - release the Flow Director resources
7042  * @pf: board private structure
7043  **/
7044 static void i40e_fdir_teardown(struct i40e_pf *pf)
7045 {
7046         struct i40e_vsi *vsi;
7047
7048         i40e_fdir_filter_exit(pf);
7049         vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
7050         if (vsi)
7051                 i40e_vsi_release(vsi);
7052 }
7053
7054 /**
7055  * i40e_prep_for_reset - prep for the core to reset
7056  * @pf: board private structure
7057  * @lock_acquired: indicates whether or not the lock has been acquired
7058  * before this function was called.
7059  *
7060  * Close up the VFs and other things in prep for PF Reset.
7061   **/
7062 static void i40e_prep_for_reset(struct i40e_pf *pf, bool lock_acquired)
7063 {
7064         struct i40e_hw *hw = &pf->hw;
7065         i40e_status ret = 0;
7066         u32 v;
7067
7068         clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
7069         if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
7070                 return;
7071         if (i40e_check_asq_alive(&pf->hw))
7072                 i40e_vc_notify_reset(pf);
7073
7074         dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
7075
7076         /* quiesce the VSIs and their queues that are not already DOWN */
7077         /* pf_quiesce_all_vsi modifies netdev structures -rtnl_lock needed */
7078         if (!lock_acquired)
7079                 rtnl_lock();
7080         i40e_pf_quiesce_all_vsi(pf);
7081         if (!lock_acquired)
7082                 rtnl_unlock();
7083
7084         for (v = 0; v < pf->num_alloc_vsi; v++) {
7085                 if (pf->vsi[v])
7086                         pf->vsi[v]->seid = 0;
7087         }
7088
7089         i40e_shutdown_adminq(&pf->hw);
7090
7091         /* call shutdown HMC */
7092         if (hw->hmc.hmc_obj) {
7093                 ret = i40e_shutdown_lan_hmc(hw);
7094                 if (ret)
7095                         dev_warn(&pf->pdev->dev,
7096                                  "shutdown_lan_hmc failed: %d\n", ret);
7097         }
7098 }
7099
7100 /**
7101  * i40e_send_version - update firmware with driver version
7102  * @pf: PF struct
7103  */
7104 static void i40e_send_version(struct i40e_pf *pf)
7105 {
7106         struct i40e_driver_version dv;
7107
7108         dv.major_version = DRV_VERSION_MAJOR;
7109         dv.minor_version = DRV_VERSION_MINOR;
7110         dv.build_version = DRV_VERSION_BUILD;
7111         dv.subbuild_version = 0;
7112         strlcpy(dv.driver_string, DRV_VERSION, sizeof(dv.driver_string));
7113         i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
7114 }
7115
7116 /**
7117  * i40e_get_oem_version - get OEM specific version information
7118  * @hw: pointer to the hardware structure
7119  **/
7120 static void i40e_get_oem_version(struct i40e_hw *hw)
7121 {
7122         u16 block_offset = 0xffff;
7123         u16 block_length = 0;
7124         u16 capabilities = 0;
7125         u16 gen_snap = 0;
7126         u16 release = 0;
7127
7128 #define I40E_SR_NVM_OEM_VERSION_PTR             0x1B
7129 #define I40E_NVM_OEM_LENGTH_OFFSET              0x00
7130 #define I40E_NVM_OEM_CAPABILITIES_OFFSET        0x01
7131 #define I40E_NVM_OEM_GEN_OFFSET                 0x02
7132 #define I40E_NVM_OEM_RELEASE_OFFSET             0x03
7133 #define I40E_NVM_OEM_CAPABILITIES_MASK          0x000F
7134 #define I40E_NVM_OEM_LENGTH                     3
7135
7136         /* Check if pointer to OEM version block is valid. */
7137         i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
7138         if (block_offset == 0xffff)
7139                 return;
7140
7141         /* Check if OEM version block has correct length. */
7142         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
7143                            &block_length);
7144         if (block_length < I40E_NVM_OEM_LENGTH)
7145                 return;
7146
7147         /* Check if OEM version format is as expected. */
7148         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
7149                            &capabilities);
7150         if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
7151                 return;
7152
7153         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
7154                            &gen_snap);
7155         i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
7156                            &release);
7157         hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
7158         hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
7159 }
7160
7161 /**
7162  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
7163  * @pf: board private structure
7164  **/
7165 static int i40e_reset(struct i40e_pf *pf)
7166 {
7167         struct i40e_hw *hw = &pf->hw;
7168         i40e_status ret;
7169
7170         ret = i40e_pf_reset(hw);
7171         if (ret) {
7172                 dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
7173                 set_bit(__I40E_RESET_FAILED, pf->state);
7174                 clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
7175         } else {
7176                 pf->pfr_count++;
7177         }
7178         return ret;
7179 }
7180
7181 /**
7182  * i40e_rebuild - rebuild using a saved config
7183  * @pf: board private structure
7184  * @reinit: if the Main VSI needs to re-initialized.
7185  * @lock_acquired: indicates whether or not the lock has been acquired
7186  * before this function was called.
7187  **/
7188 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
7189 {
7190         struct i40e_hw *hw = &pf->hw;
7191         i40e_status ret;
7192         u32 val;
7193         int v;
7194
7195         if (test_bit(__I40E_DOWN, pf->state))
7196                 goto clear_recovery;
7197         dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
7198
7199         /* rebuild the basics for the AdminQ, HMC, and initial HW switch */
7200         ret = i40e_init_adminq(&pf->hw);
7201         if (ret) {
7202                 dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
7203                          i40e_stat_str(&pf->hw, ret),
7204                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7205                 goto clear_recovery;
7206         }
7207         i40e_get_oem_version(&pf->hw);
7208
7209         if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
7210             ((hw->aq.fw_maj_ver == 4 && hw->aq.fw_min_ver <= 33) ||
7211              hw->aq.fw_maj_ver < 4) && hw->mac.type == I40E_MAC_XL710) {
7212                 /* The following delay is necessary for 4.33 firmware and older
7213                  * to recover after EMP reset. 200 ms should suffice but we
7214                  * put here 300 ms to be sure that FW is ready to operate
7215                  * after reset.
7216                  */
7217                 mdelay(300);
7218         }
7219
7220         /* re-verify the eeprom if we just had an EMP reset */
7221         if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
7222                 i40e_verify_eeprom(pf);
7223
7224         i40e_clear_pxe_mode(hw);
7225         ret = i40e_get_capabilities(pf);
7226         if (ret)
7227                 goto end_core_reset;
7228
7229         ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
7230                                 hw->func_caps.num_rx_qp, 0, 0);
7231         if (ret) {
7232                 dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
7233                 goto end_core_reset;
7234         }
7235         ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
7236         if (ret) {
7237                 dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
7238                 goto end_core_reset;
7239         }
7240
7241 #ifdef CONFIG_I40E_DCB
7242         ret = i40e_init_pf_dcb(pf);
7243         if (ret) {
7244                 dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n", ret);
7245                 pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
7246                 /* Continue without DCB enabled */
7247         }
7248 #endif /* CONFIG_I40E_DCB */
7249         /* do basic switch setup */
7250         if (!lock_acquired)
7251                 rtnl_lock();
7252         ret = i40e_setup_pf_switch(pf, reinit);
7253         if (ret)
7254                 goto end_unlock;
7255
7256         /* The driver only wants link up/down and module qualification
7257          * reports from firmware.  Note the negative logic.
7258          */
7259         ret = i40e_aq_set_phy_int_mask(&pf->hw,
7260                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
7261                                          I40E_AQ_EVENT_MEDIA_NA |
7262                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
7263         if (ret)
7264                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
7265                          i40e_stat_str(&pf->hw, ret),
7266                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
7267
7268         /* Rebuild the VSIs and VEBs that existed before reset.
7269          * They are still in our local switch element arrays, so only
7270          * need to rebuild the switch model in the HW.
7271          *
7272          * If there were VEBs but the reconstitution failed, we'll try
7273          * try to recover minimal use by getting the basic PF VSI working.
7274          */
7275         if (pf->vsi[pf->lan_vsi]->uplink_seid != pf->mac_seid) {
7276                 dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
7277                 /* find the one VEB connected to the MAC, and find orphans */
7278                 for (v = 0; v < I40E_MAX_VEB; v++) {
7279                         if (!pf->veb[v])
7280                                 continue;
7281
7282                         if (pf->veb[v]->uplink_seid == pf->mac_seid ||
7283                             pf->veb[v]->uplink_seid == 0) {
7284                                 ret = i40e_reconstitute_veb(pf->veb[v]);
7285
7286                                 if (!ret)
7287                                         continue;
7288
7289                                 /* If Main VEB failed, we're in deep doodoo,
7290                                  * so give up rebuilding the switch and set up
7291                                  * for minimal rebuild of PF VSI.
7292                                  * If orphan failed, we'll report the error
7293                                  * but try to keep going.
7294                                  */
7295                                 if (pf->veb[v]->uplink_seid == pf->mac_seid) {
7296                                         dev_info(&pf->pdev->dev,
7297                                                  "rebuild of switch failed: %d, will try to set up simple PF connection\n",
7298                                                  ret);
7299                                         pf->vsi[pf->lan_vsi]->uplink_seid
7300                                                                 = pf->mac_seid;
7301                                         break;
7302                                 } else if (pf->veb[v]->uplink_seid == 0) {
7303                                         dev_info(&pf->pdev->dev,
7304                                                  "rebuild of orphan VEB failed: %d\n",
7305                                                  ret);
7306                                 }
7307                         }
7308                 }
7309         }
7310
7311         if (pf->vsi[pf->lan_vsi]->uplink_seid == pf->mac_seid) {
7312                 dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
7313                 /* no VEB, so rebuild only the Main VSI */
7314                 ret = i40e_add_vsi(pf->vsi[pf->lan_vsi]);
7315                 if (ret) {
7316                         dev_info(&pf->pdev->dev,
7317                                  "rebuild of Main VSI failed: %d\n", ret);
7318                         goto end_unlock;
7319                 }
7320         }
7321
7322         /* Reconfigure hardware for allowing smaller MSS in the case
7323          * of TSO, so that we avoid the MDD being fired and causing
7324          * a reset in the case of small MSS+TSO.
7325          */
7326 #define I40E_REG_MSS          0x000E64DC
7327 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
7328 #define I40E_64BYTE_MSS       0x400000
7329         val = rd32(hw, I40E_REG_MSS);
7330         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
7331                 val &= ~I40E_REG_MSS_MIN_MASK;
7332                 val |= I40E_64BYTE_MSS;
7333                 wr32(hw, I40E_REG_MSS, val);
7334         }
7335
7336         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
7337                 msleep(75);
7338                 ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
7339                 if (ret)
7340                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
7341                                  i40e_stat_str(&pf->hw, ret),
7342                                  i40e_aq_str(&pf->hw,
7343                                              pf->hw.aq.asq_last_status));
7344         }
7345         /* reinit the misc interrupt */
7346         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7347                 ret = i40e_setup_misc_vector(pf);
7348
7349         /* Add a filter to drop all Flow control frames from any VSI from being
7350          * transmitted. By doing so we stop a malicious VF from sending out
7351          * PAUSE or PFC frames and potentially controlling traffic for other
7352          * PF/VF VSIs.
7353          * The FW can still send Flow control frames if enabled.
7354          */
7355         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
7356                                                        pf->main_vsi_seid);
7357
7358         /* restart the VSIs that were rebuilt and running before the reset */
7359         i40e_pf_unquiesce_all_vsi(pf);
7360
7361         /* Release the RTNL lock before we start resetting VFs */
7362         if (!lock_acquired)
7363                 rtnl_unlock();
7364
7365         i40e_reset_all_vfs(pf, true);
7366
7367         /* tell the firmware that we're starting */
7368         i40e_send_version(pf);
7369
7370         /* We've already released the lock, so don't do it again */
7371         goto end_core_reset;
7372
7373 end_unlock:
7374         if (!lock_acquired)
7375                 rtnl_unlock();
7376 end_core_reset:
7377         clear_bit(__I40E_RESET_FAILED, pf->state);
7378 clear_recovery:
7379         clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
7380 }
7381
7382 /**
7383  * i40e_reset_and_rebuild - reset and rebuild using a saved config
7384  * @pf: board private structure
7385  * @reinit: if the Main VSI needs to re-initialized.
7386  * @lock_acquired: indicates whether or not the lock has been acquired
7387  * before this function was called.
7388  **/
7389 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
7390                                    bool lock_acquired)
7391 {
7392         int ret;
7393         /* Now we wait for GRST to settle out.
7394          * We don't have to delete the VEBs or VSIs from the hw switch
7395          * because the reset will make them disappear.
7396          */
7397         ret = i40e_reset(pf);
7398         if (!ret)
7399                 i40e_rebuild(pf, reinit, lock_acquired);
7400 }
7401
7402 /**
7403  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
7404  * @pf: board private structure
7405  *
7406  * Close up the VFs and other things in prep for a Core Reset,
7407  * then get ready to rebuild the world.
7408  * @lock_acquired: indicates whether or not the lock has been acquired
7409  * before this function was called.
7410  **/
7411 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
7412 {
7413         i40e_prep_for_reset(pf, lock_acquired);
7414         i40e_reset_and_rebuild(pf, false, lock_acquired);
7415 }
7416
7417 /**
7418  * i40e_handle_mdd_event
7419  * @pf: pointer to the PF structure
7420  *
7421  * Called from the MDD irq handler to identify possibly malicious vfs
7422  **/
7423 static void i40e_handle_mdd_event(struct i40e_pf *pf)
7424 {
7425         struct i40e_hw *hw = &pf->hw;
7426         bool mdd_detected = false;
7427         bool pf_mdd_detected = false;
7428         struct i40e_vf *vf;
7429         u32 reg;
7430         int i;
7431
7432         if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
7433                 return;
7434
7435         /* find what triggered the MDD event */
7436         reg = rd32(hw, I40E_GL_MDET_TX);
7437         if (reg & I40E_GL_MDET_TX_VALID_MASK) {
7438                 u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
7439                                 I40E_GL_MDET_TX_PF_NUM_SHIFT;
7440                 u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
7441                                 I40E_GL_MDET_TX_VF_NUM_SHIFT;
7442                 u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
7443                                 I40E_GL_MDET_TX_EVENT_SHIFT;
7444                 u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
7445                                 I40E_GL_MDET_TX_QUEUE_SHIFT) -
7446                                 pf->hw.func_caps.base_queue;
7447                 if (netif_msg_tx_err(pf))
7448                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
7449                                  event, queue, pf_num, vf_num);
7450                 wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
7451                 mdd_detected = true;
7452         }
7453         reg = rd32(hw, I40E_GL_MDET_RX);
7454         if (reg & I40E_GL_MDET_RX_VALID_MASK) {
7455                 u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
7456                                 I40E_GL_MDET_RX_FUNCTION_SHIFT;
7457                 u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
7458                                 I40E_GL_MDET_RX_EVENT_SHIFT;
7459                 u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
7460                                 I40E_GL_MDET_RX_QUEUE_SHIFT) -
7461                                 pf->hw.func_caps.base_queue;
7462                 if (netif_msg_rx_err(pf))
7463                         dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
7464                                  event, queue, func);
7465                 wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
7466                 mdd_detected = true;
7467         }
7468
7469         if (mdd_detected) {
7470                 reg = rd32(hw, I40E_PF_MDET_TX);
7471                 if (reg & I40E_PF_MDET_TX_VALID_MASK) {
7472                         wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
7473                         dev_info(&pf->pdev->dev, "TX driver issue detected, PF reset issued\n");
7474                         pf_mdd_detected = true;
7475                 }
7476                 reg = rd32(hw, I40E_PF_MDET_RX);
7477                 if (reg & I40E_PF_MDET_RX_VALID_MASK) {
7478                         wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
7479                         dev_info(&pf->pdev->dev, "RX driver issue detected, PF reset issued\n");
7480                         pf_mdd_detected = true;
7481                 }
7482                 /* Queue belongs to the PF, initiate a reset */
7483                 if (pf_mdd_detected) {
7484                         set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
7485                         i40e_service_event_schedule(pf);
7486                 }
7487         }
7488
7489         /* see if one of the VFs needs its hand slapped */
7490         for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
7491                 vf = &(pf->vf[i]);
7492                 reg = rd32(hw, I40E_VP_MDET_TX(i));
7493                 if (reg & I40E_VP_MDET_TX_VALID_MASK) {
7494                         wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
7495                         vf->num_mdd_events++;
7496                         dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
7497                                  i);
7498                 }
7499
7500                 reg = rd32(hw, I40E_VP_MDET_RX(i));
7501                 if (reg & I40E_VP_MDET_RX_VALID_MASK) {
7502                         wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
7503                         vf->num_mdd_events++;
7504                         dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
7505                                  i);
7506                 }
7507
7508                 if (vf->num_mdd_events > I40E_DEFAULT_NUM_MDD_EVENTS_ALLOWED) {
7509                         dev_info(&pf->pdev->dev,
7510                                  "Too many MDD events on VF %d, disabled\n", i);
7511                         dev_info(&pf->pdev->dev,
7512                                  "Use PF Control I/F to re-enable the VF\n");
7513                         set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
7514                 }
7515         }
7516
7517         /* re-enable mdd interrupt cause */
7518         clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
7519         reg = rd32(hw, I40E_PFINT_ICR0_ENA);
7520         reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
7521         wr32(hw, I40E_PFINT_ICR0_ENA, reg);
7522         i40e_flush(hw);
7523 }
7524
7525 static const char *i40e_tunnel_name(struct i40e_udp_port_config *port)
7526 {
7527         switch (port->type) {
7528         case UDP_TUNNEL_TYPE_VXLAN:
7529                 return "vxlan";
7530         case UDP_TUNNEL_TYPE_GENEVE:
7531                 return "geneve";
7532         default:
7533                 return "unknown";
7534         }
7535 }
7536
7537 /**
7538  * i40e_sync_udp_filters - Trigger a sync event for existing UDP filters
7539  * @pf: board private structure
7540  **/
7541 static void i40e_sync_udp_filters(struct i40e_pf *pf)
7542 {
7543         int i;
7544
7545         /* loop through and set pending bit for all active UDP filters */
7546         for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
7547                 if (pf->udp_ports[i].port)
7548                         pf->pending_udp_bitmap |= BIT_ULL(i);
7549         }
7550
7551         pf->flags |= I40E_FLAG_UDP_FILTER_SYNC;
7552 }
7553
7554 /**
7555  * i40e_sync_udp_filters_subtask - Sync the VSI filter list with HW
7556  * @pf: board private structure
7557  **/
7558 static void i40e_sync_udp_filters_subtask(struct i40e_pf *pf)
7559 {
7560         struct i40e_hw *hw = &pf->hw;
7561         i40e_status ret;
7562         u16 port;
7563         int i;
7564
7565         if (!(pf->flags & I40E_FLAG_UDP_FILTER_SYNC))
7566                 return;
7567
7568         pf->flags &= ~I40E_FLAG_UDP_FILTER_SYNC;
7569
7570         for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
7571                 if (pf->pending_udp_bitmap & BIT_ULL(i)) {
7572                         pf->pending_udp_bitmap &= ~BIT_ULL(i);
7573                         port = pf->udp_ports[i].port;
7574                         if (port)
7575                                 ret = i40e_aq_add_udp_tunnel(hw, port,
7576                                                         pf->udp_ports[i].type,
7577                                                         NULL, NULL);
7578                         else
7579                                 ret = i40e_aq_del_udp_tunnel(hw, i, NULL);
7580
7581                         if (ret) {
7582                                 dev_info(&pf->pdev->dev,
7583                                          "%s %s port %d, index %d failed, err %s aq_err %s\n",
7584                                          i40e_tunnel_name(&pf->udp_ports[i]),
7585                                          port ? "add" : "delete",
7586                                          port, i,
7587                                          i40e_stat_str(&pf->hw, ret),
7588                                          i40e_aq_str(&pf->hw,
7589                                                      pf->hw.aq.asq_last_status));
7590                                 pf->udp_ports[i].port = 0;
7591                         }
7592                 }
7593         }
7594 }
7595
7596 /**
7597  * i40e_service_task - Run the driver's async subtasks
7598  * @work: pointer to work_struct containing our data
7599  **/
7600 static void i40e_service_task(struct work_struct *work)
7601 {
7602         struct i40e_pf *pf = container_of(work,
7603                                           struct i40e_pf,
7604                                           service_task);
7605         unsigned long start_time = jiffies;
7606
7607         /* don't bother with service tasks if a reset is in progress */
7608         if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
7609                 return;
7610
7611         if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
7612                 return;
7613
7614         i40e_detect_recover_hung(pf);
7615         i40e_sync_filters_subtask(pf);
7616         i40e_reset_subtask(pf);
7617         i40e_handle_mdd_event(pf);
7618         i40e_vc_process_vflr_event(pf);
7619         i40e_watchdog_subtask(pf);
7620         i40e_fdir_reinit_subtask(pf);
7621         if (pf->flags & I40E_FLAG_CLIENT_RESET) {
7622                 /* Client subtask will reopen next time through. */
7623                 i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], true);
7624                 pf->flags &= ~I40E_FLAG_CLIENT_RESET;
7625         } else {
7626                 i40e_client_subtask(pf);
7627                 if (pf->flags & I40E_FLAG_CLIENT_L2_CHANGE) {
7628                         i40e_notify_client_of_l2_param_changes(
7629                                                         pf->vsi[pf->lan_vsi]);
7630                         pf->flags &= ~I40E_FLAG_CLIENT_L2_CHANGE;
7631                 }
7632         }
7633         i40e_sync_filters_subtask(pf);
7634         i40e_sync_udp_filters_subtask(pf);
7635         i40e_clean_adminq_subtask(pf);
7636
7637         /* flush memory to make sure state is correct before next watchdog */
7638         smp_mb__before_atomic();
7639         clear_bit(__I40E_SERVICE_SCHED, pf->state);
7640
7641         /* If the tasks have taken longer than one timer cycle or there
7642          * is more work to be done, reschedule the service task now
7643          * rather than wait for the timer to tick again.
7644          */
7645         if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
7646             test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)             ||
7647             test_bit(__I40E_MDD_EVENT_PENDING, pf->state)                ||
7648             test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
7649                 i40e_service_event_schedule(pf);
7650 }
7651
7652 /**
7653  * i40e_service_timer - timer callback
7654  * @data: pointer to PF struct
7655  **/
7656 static void i40e_service_timer(unsigned long data)
7657 {
7658         struct i40e_pf *pf = (struct i40e_pf *)data;
7659
7660         mod_timer(&pf->service_timer,
7661                   round_jiffies(jiffies + pf->service_timer_period));
7662         i40e_service_event_schedule(pf);
7663 }
7664
7665 /**
7666  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
7667  * @vsi: the VSI being configured
7668  **/
7669 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
7670 {
7671         struct i40e_pf *pf = vsi->back;
7672
7673         switch (vsi->type) {
7674         case I40E_VSI_MAIN:
7675                 vsi->alloc_queue_pairs = pf->num_lan_qps;
7676                 vsi->num_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
7677                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7678                 if (pf->flags & I40E_FLAG_MSIX_ENABLED)
7679                         vsi->num_q_vectors = pf->num_lan_msix;
7680                 else
7681                         vsi->num_q_vectors = 1;
7682
7683                 break;
7684
7685         case I40E_VSI_FDIR:
7686                 vsi->alloc_queue_pairs = 1;
7687                 vsi->num_desc = ALIGN(I40E_FDIR_RING_COUNT,
7688                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7689                 vsi->num_q_vectors = pf->num_fdsb_msix;
7690                 break;
7691
7692         case I40E_VSI_VMDQ2:
7693                 vsi->alloc_queue_pairs = pf->num_vmdq_qps;
7694                 vsi->num_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
7695                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7696                 vsi->num_q_vectors = pf->num_vmdq_msix;
7697                 break;
7698
7699         case I40E_VSI_SRIOV:
7700                 vsi->alloc_queue_pairs = pf->num_vf_qps;
7701                 vsi->num_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
7702                                       I40E_REQ_DESCRIPTOR_MULTIPLE);
7703                 break;
7704
7705         default:
7706                 WARN_ON(1);
7707                 return -ENODATA;
7708         }
7709
7710         return 0;
7711 }
7712
7713 /**
7714  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
7715  * @type: VSI pointer
7716  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
7717  *
7718  * On error: returns error code (negative)
7719  * On success: returns 0
7720  **/
7721 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
7722 {
7723         struct i40e_ring **next_rings;
7724         int size;
7725         int ret = 0;
7726
7727         /* allocate memory for both Tx, XDP Tx and Rx ring pointers */
7728         size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
7729                (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
7730         vsi->tx_rings = kzalloc(size, GFP_KERNEL);
7731         if (!vsi->tx_rings)
7732                 return -ENOMEM;
7733         next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
7734         if (i40e_enabled_xdp_vsi(vsi)) {
7735                 vsi->xdp_rings = next_rings;
7736                 next_rings += vsi->alloc_queue_pairs;
7737         }
7738         vsi->rx_rings = next_rings;
7739
7740         if (alloc_qvectors) {
7741                 /* allocate memory for q_vector pointers */
7742                 size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
7743                 vsi->q_vectors = kzalloc(size, GFP_KERNEL);
7744                 if (!vsi->q_vectors) {
7745                         ret = -ENOMEM;
7746                         goto err_vectors;
7747                 }
7748         }
7749         return ret;
7750
7751 err_vectors:
7752         kfree(vsi->tx_rings);
7753         return ret;
7754 }
7755
7756 /**
7757  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
7758  * @pf: board private structure
7759  * @type: type of VSI
7760  *
7761  * On error: returns error code (negative)
7762  * On success: returns vsi index in PF (positive)
7763  **/
7764 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
7765 {
7766         int ret = -ENODEV;
7767         struct i40e_vsi *vsi;
7768         int vsi_idx;
7769         int i;
7770
7771         /* Need to protect the allocation of the VSIs at the PF level */
7772         mutex_lock(&pf->switch_mutex);
7773
7774         /* VSI list may be fragmented if VSI creation/destruction has
7775          * been happening.  We can afford to do a quick scan to look
7776          * for any free VSIs in the list.
7777          *
7778          * find next empty vsi slot, looping back around if necessary
7779          */
7780         i = pf->next_vsi;
7781         while (i < pf->num_alloc_vsi && pf->vsi[i])
7782                 i++;
7783         if (i >= pf->num_alloc_vsi) {
7784                 i = 0;
7785                 while (i < pf->next_vsi && pf->vsi[i])
7786                         i++;
7787         }
7788
7789         if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
7790                 vsi_idx = i;             /* Found one! */
7791         } else {
7792                 ret = -ENODEV;
7793                 goto unlock_pf;  /* out of VSI slots! */
7794         }
7795         pf->next_vsi = ++i;
7796
7797         vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
7798         if (!vsi) {
7799                 ret = -ENOMEM;
7800                 goto unlock_pf;
7801         }
7802         vsi->type = type;
7803         vsi->back = pf;
7804         set_bit(__I40E_VSI_DOWN, vsi->state);
7805         vsi->flags = 0;
7806         vsi->idx = vsi_idx;
7807         vsi->int_rate_limit = 0;
7808         vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
7809                                 pf->rss_table_size : 64;
7810         vsi->netdev_registered = false;
7811         vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
7812         hash_init(vsi->mac_filter_hash);
7813         vsi->irqs_ready = false;
7814
7815         ret = i40e_set_num_rings_in_vsi(vsi);
7816         if (ret)
7817                 goto err_rings;
7818
7819         ret = i40e_vsi_alloc_arrays(vsi, true);
7820         if (ret)
7821                 goto err_rings;
7822
7823         /* Setup default MSIX irq handler for VSI */
7824         i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
7825
7826         /* Initialize VSI lock */
7827         spin_lock_init(&vsi->mac_filter_hash_lock);
7828         pf->vsi[vsi_idx] = vsi;
7829         ret = vsi_idx;
7830         goto unlock_pf;
7831
7832 err_rings:
7833         pf->next_vsi = i - 1;
7834         kfree(vsi);
7835 unlock_pf:
7836         mutex_unlock(&pf->switch_mutex);
7837         return ret;
7838 }
7839
7840 /**
7841  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
7842  * @type: VSI pointer
7843  * @free_qvectors: a bool to specify if q_vectors need to be freed.
7844  *
7845  * On error: returns error code (negative)
7846  * On success: returns 0
7847  **/
7848 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
7849 {
7850         /* free the ring and vector containers */
7851         if (free_qvectors) {
7852                 kfree(vsi->q_vectors);
7853                 vsi->q_vectors = NULL;
7854         }
7855         kfree(vsi->tx_rings);
7856         vsi->tx_rings = NULL;
7857         vsi->rx_rings = NULL;
7858         vsi->xdp_rings = NULL;
7859 }
7860
7861 /**
7862  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
7863  * and lookup table
7864  * @vsi: Pointer to VSI structure
7865  */
7866 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
7867 {
7868         if (!vsi)
7869                 return;
7870
7871         kfree(vsi->rss_hkey_user);
7872         vsi->rss_hkey_user = NULL;
7873
7874         kfree(vsi->rss_lut_user);
7875         vsi->rss_lut_user = NULL;
7876 }
7877
7878 /**
7879  * i40e_vsi_clear - Deallocate the VSI provided
7880  * @vsi: the VSI being un-configured
7881  **/
7882 static int i40e_vsi_clear(struct i40e_vsi *vsi)
7883 {
7884         struct i40e_pf *pf;
7885
7886         if (!vsi)
7887                 return 0;
7888
7889         if (!vsi->back)
7890                 goto free_vsi;
7891         pf = vsi->back;
7892
7893         mutex_lock(&pf->switch_mutex);
7894         if (!pf->vsi[vsi->idx]) {
7895                 dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](%p,type %d)\n",
7896                         vsi->idx, vsi->idx, vsi, vsi->type);
7897                 goto unlock_vsi;
7898         }
7899
7900         if (pf->vsi[vsi->idx] != vsi) {
7901                 dev_err(&pf->pdev->dev,
7902                         "pf->vsi[%d](%p, type %d) != vsi[%d](%p,type %d): no free!\n",
7903                         pf->vsi[vsi->idx]->idx,
7904                         pf->vsi[vsi->idx],
7905                         pf->vsi[vsi->idx]->type,
7906                         vsi->idx, vsi, vsi->type);
7907                 goto unlock_vsi;
7908         }
7909
7910         /* updates the PF for this cleared vsi */
7911         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
7912         i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
7913
7914         i40e_vsi_free_arrays(vsi, true);
7915         i40e_clear_rss_config_user(vsi);
7916
7917         pf->vsi[vsi->idx] = NULL;
7918         if (vsi->idx < pf->next_vsi)
7919                 pf->next_vsi = vsi->idx;
7920
7921 unlock_vsi:
7922         mutex_unlock(&pf->switch_mutex);
7923 free_vsi:
7924         kfree(vsi);
7925
7926         return 0;
7927 }
7928
7929 /**
7930  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
7931  * @vsi: the VSI being cleaned
7932  **/
7933 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
7934 {
7935         int i;
7936
7937         if (vsi->tx_rings && vsi->tx_rings[0]) {
7938                 for (i = 0; i < vsi->alloc_queue_pairs; i++) {
7939                         kfree_rcu(vsi->tx_rings[i], rcu);
7940                         vsi->tx_rings[i] = NULL;
7941                         vsi->rx_rings[i] = NULL;
7942                         if (vsi->xdp_rings)
7943                                 vsi->xdp_rings[i] = NULL;
7944                 }
7945         }
7946 }
7947
7948 /**
7949  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
7950  * @vsi: the VSI being configured
7951  **/
7952 static int i40e_alloc_rings(struct i40e_vsi *vsi)
7953 {
7954         int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
7955         struct i40e_pf *pf = vsi->back;
7956         struct i40e_ring *ring;
7957
7958         /* Set basic values in the rings to be used later during open() */
7959         for (i = 0; i < vsi->alloc_queue_pairs; i++) {
7960                 /* allocate space for both Tx and Rx in one shot */
7961                 ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
7962                 if (!ring)
7963                         goto err_out;
7964
7965                 ring->queue_index = i;
7966                 ring->reg_idx = vsi->base_queue + i;
7967                 ring->ring_active = false;
7968                 ring->vsi = vsi;
7969                 ring->netdev = vsi->netdev;
7970                 ring->dev = &pf->pdev->dev;
7971                 ring->count = vsi->num_desc;
7972                 ring->size = 0;
7973                 ring->dcb_tc = 0;
7974                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
7975                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
7976                 ring->tx_itr_setting = pf->tx_itr_default;
7977                 vsi->tx_rings[i] = ring++;
7978
7979                 if (!i40e_enabled_xdp_vsi(vsi))
7980                         goto setup_rx;
7981
7982                 ring->queue_index = vsi->alloc_queue_pairs + i;
7983                 ring->reg_idx = vsi->base_queue + ring->queue_index;
7984                 ring->ring_active = false;
7985                 ring->vsi = vsi;
7986                 ring->netdev = NULL;
7987                 ring->dev = &pf->pdev->dev;
7988                 ring->count = vsi->num_desc;
7989                 ring->size = 0;
7990                 ring->dcb_tc = 0;
7991                 if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
7992                         ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
7993                 set_ring_xdp(ring);
7994                 ring->tx_itr_setting = pf->tx_itr_default;
7995                 vsi->xdp_rings[i] = ring++;
7996
7997 setup_rx:
7998                 ring->queue_index = i;
7999                 ring->reg_idx = vsi->base_queue + i;
8000                 ring->ring_active = false;
8001                 ring->vsi = vsi;
8002                 ring->netdev = vsi->netdev;
8003                 ring->dev = &pf->pdev->dev;
8004                 ring->count = vsi->num_desc;
8005                 ring->size = 0;
8006                 ring->dcb_tc = 0;
8007                 ring->rx_itr_setting = pf->rx_itr_default;
8008                 vsi->rx_rings[i] = ring;
8009         }
8010
8011         return 0;
8012
8013 err_out:
8014         i40e_vsi_clear_rings(vsi);
8015         return -ENOMEM;
8016 }
8017
8018 /**
8019  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
8020  * @pf: board private structure
8021  * @vectors: the number of MSI-X vectors to request
8022  *
8023  * Returns the number of vectors reserved, or error
8024  **/
8025 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
8026 {
8027         vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
8028                                         I40E_MIN_MSIX, vectors);
8029         if (vectors < 0) {
8030                 dev_info(&pf->pdev->dev,
8031                          "MSI-X vector reservation failed: %d\n", vectors);
8032                 vectors = 0;
8033         }
8034
8035         return vectors;
8036 }
8037
8038 /**
8039  * i40e_init_msix - Setup the MSIX capability
8040  * @pf: board private structure
8041  *
8042  * Work with the OS to set up the MSIX vectors needed.
8043  *
8044  * Returns the number of vectors reserved or negative on failure
8045  **/
8046 static int i40e_init_msix(struct i40e_pf *pf)
8047 {
8048         struct i40e_hw *hw = &pf->hw;
8049         int cpus, extra_vectors;
8050         int vectors_left;
8051         int v_budget, i;
8052         int v_actual;
8053         int iwarp_requested = 0;
8054
8055         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
8056                 return -ENODEV;
8057
8058         /* The number of vectors we'll request will be comprised of:
8059          *   - Add 1 for "other" cause for Admin Queue events, etc.
8060          *   - The number of LAN queue pairs
8061          *      - Queues being used for RSS.
8062          *              We don't need as many as max_rss_size vectors.
8063          *              use rss_size instead in the calculation since that
8064          *              is governed by number of cpus in the system.
8065          *      - assumes symmetric Tx/Rx pairing
8066          *   - The number of VMDq pairs
8067          *   - The CPU count within the NUMA node if iWARP is enabled
8068          * Once we count this up, try the request.
8069          *
8070          * If we can't get what we want, we'll simplify to nearly nothing
8071          * and try again.  If that still fails, we punt.
8072          */
8073         vectors_left = hw->func_caps.num_msix_vectors;
8074         v_budget = 0;
8075
8076         /* reserve one vector for miscellaneous handler */
8077         if (vectors_left) {
8078                 v_budget++;
8079                 vectors_left--;
8080         }
8081
8082         /* reserve some vectors for the main PF traffic queues. Initially we
8083          * only reserve at most 50% of the available vectors, in the case that
8084          * the number of online CPUs is large. This ensures that we can enable
8085          * extra features as well. Once we've enabled the other features, we
8086          * will use any remaining vectors to reach as close as we can to the
8087          * number of online CPUs.
8088          */
8089         cpus = num_online_cpus();
8090         pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
8091         vectors_left -= pf->num_lan_msix;
8092
8093         /* reserve one vector for sideband flow director */
8094         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
8095                 if (vectors_left) {
8096                         pf->num_fdsb_msix = 1;
8097                         v_budget++;
8098                         vectors_left--;
8099                 } else {
8100                         pf->num_fdsb_msix = 0;
8101                 }
8102         }
8103
8104         /* can we reserve enough for iWARP? */
8105         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
8106                 iwarp_requested = pf->num_iwarp_msix;
8107
8108                 if (!vectors_left)
8109                         pf->num_iwarp_msix = 0;
8110                 else if (vectors_left < pf->num_iwarp_msix)
8111                         pf->num_iwarp_msix = 1;
8112                 v_budget += pf->num_iwarp_msix;
8113                 vectors_left -= pf->num_iwarp_msix;
8114         }
8115
8116         /* any vectors left over go for VMDq support */
8117         if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
8118                 int vmdq_vecs_wanted = pf->num_vmdq_vsis * pf->num_vmdq_qps;
8119                 int vmdq_vecs = min_t(int, vectors_left, vmdq_vecs_wanted);
8120
8121                 if (!vectors_left) {
8122                         pf->num_vmdq_msix = 0;
8123                         pf->num_vmdq_qps = 0;
8124                 } else {
8125                         /* if we're short on vectors for what's desired, we limit
8126                          * the queues per vmdq.  If this is still more than are
8127                          * available, the user will need to change the number of
8128                          * queues/vectors used by the PF later with the ethtool
8129                          * channels command
8130                          */
8131                         if (vmdq_vecs < vmdq_vecs_wanted)
8132                                 pf->num_vmdq_qps = 1;
8133                         pf->num_vmdq_msix = pf->num_vmdq_qps;
8134
8135                         v_budget += vmdq_vecs;
8136                         vectors_left -= vmdq_vecs;
8137                 }
8138         }
8139
8140         /* On systems with a large number of SMP cores, we previously limited
8141          * the number of vectors for num_lan_msix to be at most 50% of the
8142          * available vectors, to allow for other features. Now, we add back
8143          * the remaining vectors. However, we ensure that the total
8144          * num_lan_msix will not exceed num_online_cpus(). To do this, we
8145          * calculate the number of vectors we can add without going over the
8146          * cap of CPUs. For systems with a small number of CPUs this will be
8147          * zero.
8148          */
8149         extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
8150         pf->num_lan_msix += extra_vectors;
8151         vectors_left -= extra_vectors;
8152
8153         WARN(vectors_left < 0,
8154              "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
8155
8156         v_budget += pf->num_lan_msix;
8157         pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
8158                                    GFP_KERNEL);
8159         if (!pf->msix_entries)
8160                 return -ENOMEM;
8161
8162         for (i = 0; i < v_budget; i++)
8163                 pf->msix_entries[i].entry = i;
8164         v_actual = i40e_reserve_msix_vectors(pf, v_budget);
8165
8166         if (v_actual < I40E_MIN_MSIX) {
8167                 pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
8168                 kfree(pf->msix_entries);
8169                 pf->msix_entries = NULL;
8170                 pci_disable_msix(pf->pdev);
8171                 return -ENODEV;
8172
8173         } else if (v_actual == I40E_MIN_MSIX) {
8174                 /* Adjust for minimal MSIX use */
8175                 pf->num_vmdq_vsis = 0;
8176                 pf->num_vmdq_qps = 0;
8177                 pf->num_lan_qps = 1;
8178                 pf->num_lan_msix = 1;
8179
8180         } else if (!vectors_left) {
8181                 /* If we have limited resources, we will start with no vectors
8182                  * for the special features and then allocate vectors to some
8183                  * of these features based on the policy and at the end disable
8184                  * the features that did not get any vectors.
8185                  */
8186                 int vec;
8187
8188                 dev_info(&pf->pdev->dev,
8189                          "MSI-X vector limit reached, attempting to redistribute vectors\n");
8190                 /* reserve the misc vector */
8191                 vec = v_actual - 1;
8192
8193                 /* Scale vector usage down */
8194                 pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
8195                 pf->num_vmdq_vsis = 1;
8196                 pf->num_vmdq_qps = 1;
8197
8198                 /* partition out the remaining vectors */
8199                 switch (vec) {
8200                 case 2:
8201                         pf->num_lan_msix = 1;
8202                         break;
8203                 case 3:
8204                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
8205                                 pf->num_lan_msix = 1;
8206                                 pf->num_iwarp_msix = 1;
8207                         } else {
8208                                 pf->num_lan_msix = 2;
8209                         }
8210                         break;
8211                 default:
8212                         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
8213                                 pf->num_iwarp_msix = min_t(int, (vec / 3),
8214                                                  iwarp_requested);
8215                                 pf->num_vmdq_vsis = min_t(int, (vec / 3),
8216                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
8217                         } else {
8218                                 pf->num_vmdq_vsis = min_t(int, (vec / 2),
8219                                                   I40E_DEFAULT_NUM_VMDQ_VSI);
8220                         }
8221                         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
8222                                 pf->num_fdsb_msix = 1;
8223                                 vec--;
8224                         }
8225                         pf->num_lan_msix = min_t(int,
8226                                (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
8227                                                               pf->num_lan_msix);
8228                         pf->num_lan_qps = pf->num_lan_msix;
8229                         break;
8230                 }
8231         }
8232
8233         if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
8234             (pf->num_fdsb_msix == 0)) {
8235                 dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
8236                 pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
8237         }
8238         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
8239             (pf->num_vmdq_msix == 0)) {
8240                 dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
8241                 pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
8242         }
8243
8244         if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
8245             (pf->num_iwarp_msix == 0)) {
8246                 dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
8247                 pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
8248         }
8249         i40e_debug(&pf->hw, I40E_DEBUG_INIT,
8250                    "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
8251                    pf->num_lan_msix,
8252                    pf->num_vmdq_msix * pf->num_vmdq_vsis,
8253                    pf->num_fdsb_msix,
8254                    pf->num_iwarp_msix);
8255
8256         return v_actual;
8257 }
8258
8259 /**
8260  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
8261  * @vsi: the VSI being configured
8262  * @v_idx: index of the vector in the vsi struct
8263  * @cpu: cpu to be used on affinity_mask
8264  *
8265  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
8266  **/
8267 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx, int cpu)
8268 {
8269         struct i40e_q_vector *q_vector;
8270
8271         /* allocate q_vector */
8272         q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
8273         if (!q_vector)
8274                 return -ENOMEM;
8275
8276         q_vector->vsi = vsi;
8277         q_vector->v_idx = v_idx;
8278         cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
8279
8280         if (vsi->netdev)
8281                 netif_napi_add(vsi->netdev, &q_vector->napi,
8282                                i40e_napi_poll, NAPI_POLL_WEIGHT);
8283
8284         q_vector->rx.latency_range = I40E_LOW_LATENCY;
8285         q_vector->tx.latency_range = I40E_LOW_LATENCY;
8286
8287         /* tie q_vector and vsi together */
8288         vsi->q_vectors[v_idx] = q_vector;
8289
8290         return 0;
8291 }
8292
8293 /**
8294  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
8295  * @vsi: the VSI being configured
8296  *
8297  * We allocate one q_vector per queue interrupt.  If allocation fails we
8298  * return -ENOMEM.
8299  **/
8300 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
8301 {
8302         struct i40e_pf *pf = vsi->back;
8303         int err, v_idx, num_q_vectors, current_cpu;
8304
8305         /* if not MSIX, give the one vector only to the LAN VSI */
8306         if (pf->flags & I40E_FLAG_MSIX_ENABLED)
8307                 num_q_vectors = vsi->num_q_vectors;
8308         else if (vsi == pf->vsi[pf->lan_vsi])
8309                 num_q_vectors = 1;
8310         else
8311                 return -EINVAL;
8312
8313         current_cpu = cpumask_first(cpu_online_mask);
8314
8315         for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
8316                 err = i40e_vsi_alloc_q_vector(vsi, v_idx, current_cpu);
8317                 if (err)
8318                         goto err_out;
8319                 current_cpu = cpumask_next(current_cpu, cpu_online_mask);
8320                 if (unlikely(current_cpu >= nr_cpu_ids))
8321                         current_cpu = cpumask_first(cpu_online_mask);
8322         }
8323
8324         return 0;
8325
8326 err_out:
8327         while (v_idx--)
8328                 i40e_free_q_vector(vsi, v_idx);
8329
8330         return err;
8331 }
8332
8333 /**
8334  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
8335  * @pf: board private structure to initialize
8336  **/
8337 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
8338 {
8339         int vectors = 0;
8340         ssize_t size;
8341
8342         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
8343                 vectors = i40e_init_msix(pf);
8344                 if (vectors < 0) {
8345                         pf->flags &= ~(I40E_FLAG_MSIX_ENABLED   |
8346                                        I40E_FLAG_IWARP_ENABLED  |
8347                                        I40E_FLAG_RSS_ENABLED    |
8348                                        I40E_FLAG_DCB_CAPABLE    |
8349                                        I40E_FLAG_DCB_ENABLED    |
8350                                        I40E_FLAG_SRIOV_ENABLED  |
8351                                        I40E_FLAG_FD_SB_ENABLED  |
8352                                        I40E_FLAG_FD_ATR_ENABLED |
8353                                        I40E_FLAG_VMDQ_ENABLED);
8354
8355                         /* rework the queue expectations without MSIX */
8356                         i40e_determine_queue_usage(pf);
8357                 }
8358         }
8359
8360         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
8361             (pf->flags & I40E_FLAG_MSI_ENABLED)) {
8362                 dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
8363                 vectors = pci_enable_msi(pf->pdev);
8364                 if (vectors < 0) {
8365                         dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
8366                                  vectors);
8367                         pf->flags &= ~I40E_FLAG_MSI_ENABLED;
8368                 }
8369                 vectors = 1;  /* one MSI or Legacy vector */
8370         }
8371
8372         if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
8373                 dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
8374
8375         /* set up vector assignment tracking */
8376         size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
8377         pf->irq_pile = kzalloc(size, GFP_KERNEL);
8378         if (!pf->irq_pile) {
8379                 dev_err(&pf->pdev->dev, "error allocating irq_pile memory\n");
8380                 return -ENOMEM;
8381         }
8382         pf->irq_pile->num_entries = vectors;
8383         pf->irq_pile->search_hint = 0;
8384
8385         /* track first vector for misc interrupts, ignore return */
8386         (void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
8387
8388         return 0;
8389 }
8390
8391 /**
8392  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
8393  * @pf: board private structure
8394  *
8395  * This sets up the handler for MSIX 0, which is used to manage the
8396  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
8397  * when in MSI or Legacy interrupt mode.
8398  **/
8399 static int i40e_setup_misc_vector(struct i40e_pf *pf)
8400 {
8401         struct i40e_hw *hw = &pf->hw;
8402         int err = 0;
8403
8404         /* Only request the irq if this is the first time through, and
8405          * not when we're rebuilding after a Reset
8406          */
8407         if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) {
8408                 err = request_irq(pf->msix_entries[0].vector,
8409                                   i40e_intr, 0, pf->int_name, pf);
8410                 if (err) {
8411                         dev_info(&pf->pdev->dev,
8412                                  "request_irq for %s failed: %d\n",
8413                                  pf->int_name, err);
8414                         return -EFAULT;
8415                 }
8416         }
8417
8418         i40e_enable_misc_int_causes(pf);
8419
8420         /* associate no queues to the misc vector */
8421         wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
8422         wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K);
8423
8424         i40e_flush(hw);
8425
8426         i40e_irq_dynamic_enable_icr0(pf, true);
8427
8428         return err;
8429 }
8430
8431 /**
8432  * i40e_config_rss_aq - Prepare for RSS using AQ commands
8433  * @vsi: vsi structure
8434  * @seed: RSS hash seed
8435  **/
8436 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
8437                               u8 *lut, u16 lut_size)
8438 {
8439         struct i40e_pf *pf = vsi->back;
8440         struct i40e_hw *hw = &pf->hw;
8441         int ret = 0;
8442
8443         if (seed) {
8444                 struct i40e_aqc_get_set_rss_key_data *seed_dw =
8445                         (struct i40e_aqc_get_set_rss_key_data *)seed;
8446                 ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
8447                 if (ret) {
8448                         dev_info(&pf->pdev->dev,
8449                                  "Cannot set RSS key, err %s aq_err %s\n",
8450                                  i40e_stat_str(hw, ret),
8451                                  i40e_aq_str(hw, hw->aq.asq_last_status));
8452                         return ret;
8453                 }
8454         }
8455         if (lut) {
8456                 bool pf_lut = vsi->type == I40E_VSI_MAIN ? true : false;
8457
8458                 ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
8459                 if (ret) {
8460                         dev_info(&pf->pdev->dev,
8461                                  "Cannot set RSS lut, err %s aq_err %s\n",
8462                                  i40e_stat_str(hw, ret),
8463                                  i40e_aq_str(hw, hw->aq.asq_last_status));
8464                         return ret;
8465                 }
8466         }
8467         return ret;
8468 }
8469
8470 /**
8471  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
8472  * @vsi: Pointer to vsi structure
8473  * @seed: Buffter to store the hash keys
8474  * @lut: Buffer to store the lookup table entries
8475  * @lut_size: Size of buffer to store the lookup table entries
8476  *
8477  * Return 0 on success, negative on failure
8478  */
8479 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
8480                            u8 *lut, u16 lut_size)
8481 {
8482         struct i40e_pf *pf = vsi->back;
8483         struct i40e_hw *hw = &pf->hw;
8484         int ret = 0;
8485
8486         if (seed) {
8487                 ret = i40e_aq_get_rss_key(hw, vsi->id,
8488                         (struct i40e_aqc_get_set_rss_key_data *)seed);
8489                 if (ret) {
8490                         dev_info(&pf->pdev->dev,
8491                                  "Cannot get RSS key, err %s aq_err %s\n",
8492                                  i40e_stat_str(&pf->hw, ret),
8493                                  i40e_aq_str(&pf->hw,
8494                                              pf->hw.aq.asq_last_status));
8495                         return ret;
8496                 }
8497         }
8498
8499         if (lut) {
8500                 bool pf_lut = vsi->type == I40E_VSI_MAIN ? true : false;
8501
8502                 ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
8503                 if (ret) {
8504                         dev_info(&pf->pdev->dev,
8505                                  "Cannot get RSS lut, err %s aq_err %s\n",
8506                                  i40e_stat_str(&pf->hw, ret),
8507                                  i40e_aq_str(&pf->hw,
8508                                              pf->hw.aq.asq_last_status));
8509                         return ret;
8510                 }
8511         }
8512
8513         return ret;
8514 }
8515
8516 /**
8517  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
8518  * @vsi: VSI structure
8519  **/
8520 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
8521 {
8522         u8 seed[I40E_HKEY_ARRAY_SIZE];
8523         struct i40e_pf *pf = vsi->back;
8524         u8 *lut;
8525         int ret;
8526
8527         if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
8528                 return 0;
8529
8530         if (!vsi->rss_size)
8531                 vsi->rss_size = min_t(int, pf->alloc_rss_size,
8532                                       vsi->num_queue_pairs);
8533         if (!vsi->rss_size)
8534                 return -EINVAL;
8535
8536         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
8537         if (!lut)
8538                 return -ENOMEM;
8539         /* Use the user configured hash keys and lookup table if there is one,
8540          * otherwise use default
8541          */
8542         if (vsi->rss_lut_user)
8543                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
8544         else
8545                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
8546         if (vsi->rss_hkey_user)
8547                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
8548         else
8549                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
8550         ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
8551         kfree(lut);
8552
8553         return ret;
8554 }
8555
8556 /**
8557  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
8558  * @vsi: Pointer to vsi structure
8559  * @seed: RSS hash seed
8560  * @lut: Lookup table
8561  * @lut_size: Lookup table size
8562  *
8563  * Returns 0 on success, negative on failure
8564  **/
8565 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
8566                                const u8 *lut, u16 lut_size)
8567 {
8568         struct i40e_pf *pf = vsi->back;
8569         struct i40e_hw *hw = &pf->hw;
8570         u16 vf_id = vsi->vf_id;
8571         u8 i;
8572
8573         /* Fill out hash function seed */
8574         if (seed) {
8575                 u32 *seed_dw = (u32 *)seed;
8576
8577                 if (vsi->type == I40E_VSI_MAIN) {
8578                         for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
8579                                 wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
8580                 } else if (vsi->type == I40E_VSI_SRIOV) {
8581                         for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
8582                                 wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
8583                 } else {
8584                         dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
8585                 }
8586         }
8587
8588         if (lut) {
8589                 u32 *lut_dw = (u32 *)lut;
8590
8591                 if (vsi->type == I40E_VSI_MAIN) {
8592                         if (lut_size != I40E_HLUT_ARRAY_SIZE)
8593                                 return -EINVAL;
8594                         for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
8595                                 wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
8596                 } else if (vsi->type == I40E_VSI_SRIOV) {
8597                         if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
8598                                 return -EINVAL;
8599                         for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
8600                                 wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
8601                 } else {
8602                         dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
8603                 }
8604         }
8605         i40e_flush(hw);
8606
8607         return 0;
8608 }
8609
8610 /**
8611  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
8612  * @vsi: Pointer to VSI structure
8613  * @seed: Buffer to store the keys
8614  * @lut: Buffer to store the lookup table entries
8615  * @lut_size: Size of buffer to store the lookup table entries
8616  *
8617  * Returns 0 on success, negative on failure
8618  */
8619 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
8620                             u8 *lut, u16 lut_size)
8621 {
8622         struct i40e_pf *pf = vsi->back;
8623         struct i40e_hw *hw = &pf->hw;
8624         u16 i;
8625
8626         if (seed) {
8627                 u32 *seed_dw = (u32 *)seed;
8628
8629                 for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
8630                         seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
8631         }
8632         if (lut) {
8633                 u32 *lut_dw = (u32 *)lut;
8634
8635                 if (lut_size != I40E_HLUT_ARRAY_SIZE)
8636                         return -EINVAL;
8637                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
8638                         lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
8639         }
8640
8641         return 0;
8642 }
8643
8644 /**
8645  * i40e_config_rss - Configure RSS keys and lut
8646  * @vsi: Pointer to VSI structure
8647  * @seed: RSS hash seed
8648  * @lut: Lookup table
8649  * @lut_size: Lookup table size
8650  *
8651  * Returns 0 on success, negative on failure
8652  */
8653 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
8654 {
8655         struct i40e_pf *pf = vsi->back;
8656
8657         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
8658                 return i40e_config_rss_aq(vsi, seed, lut, lut_size);
8659         else
8660                 return i40e_config_rss_reg(vsi, seed, lut, lut_size);
8661 }
8662
8663 /**
8664  * i40e_get_rss - Get RSS keys and lut
8665  * @vsi: Pointer to VSI structure
8666  * @seed: Buffer to store the keys
8667  * @lut: Buffer to store the lookup table entries
8668  * lut_size: Size of buffer to store the lookup table entries
8669  *
8670  * Returns 0 on success, negative on failure
8671  */
8672 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
8673 {
8674         struct i40e_pf *pf = vsi->back;
8675
8676         if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
8677                 return i40e_get_rss_aq(vsi, seed, lut, lut_size);
8678         else
8679                 return i40e_get_rss_reg(vsi, seed, lut, lut_size);
8680 }
8681
8682 /**
8683  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
8684  * @pf: Pointer to board private structure
8685  * @lut: Lookup table
8686  * @rss_table_size: Lookup table size
8687  * @rss_size: Range of queue number for hashing
8688  */
8689 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
8690                        u16 rss_table_size, u16 rss_size)
8691 {
8692         u16 i;
8693
8694         for (i = 0; i < rss_table_size; i++)
8695                 lut[i] = i % rss_size;
8696 }
8697
8698 /**
8699  * i40e_pf_config_rss - Prepare for RSS if used
8700  * @pf: board private structure
8701  **/
8702 static int i40e_pf_config_rss(struct i40e_pf *pf)
8703 {
8704         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
8705         u8 seed[I40E_HKEY_ARRAY_SIZE];
8706         u8 *lut;
8707         struct i40e_hw *hw = &pf->hw;
8708         u32 reg_val;
8709         u64 hena;
8710         int ret;
8711
8712         /* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
8713         hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
8714                 ((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
8715         hena |= i40e_pf_get_default_rss_hena(pf);
8716
8717         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
8718         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
8719
8720         /* Determine the RSS table size based on the hardware capabilities */
8721         reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
8722         reg_val = (pf->rss_table_size == 512) ?
8723                         (reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
8724                         (reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
8725         i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
8726
8727         /* Determine the RSS size of the VSI */
8728         if (!vsi->rss_size) {
8729                 u16 qcount;
8730
8731                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
8732                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
8733         }
8734         if (!vsi->rss_size)
8735                 return -EINVAL;
8736
8737         lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
8738         if (!lut)
8739                 return -ENOMEM;
8740
8741         /* Use user configured lut if there is one, otherwise use default */
8742         if (vsi->rss_lut_user)
8743                 memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
8744         else
8745                 i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
8746
8747         /* Use user configured hash key if there is one, otherwise
8748          * use default.
8749          */
8750         if (vsi->rss_hkey_user)
8751                 memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
8752         else
8753                 netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
8754         ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
8755         kfree(lut);
8756
8757         return ret;
8758 }
8759
8760 /**
8761  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
8762  * @pf: board private structure
8763  * @queue_count: the requested queue count for rss.
8764  *
8765  * returns 0 if rss is not enabled, if enabled returns the final rss queue
8766  * count which may be different from the requested queue count.
8767  * Note: expects to be called while under rtnl_lock()
8768  **/
8769 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
8770 {
8771         struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
8772         int new_rss_size;
8773
8774         if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
8775                 return 0;
8776
8777         new_rss_size = min_t(int, queue_count, pf->rss_size_max);
8778
8779         if (queue_count != vsi->num_queue_pairs) {
8780                 u16 qcount;
8781
8782                 vsi->req_queue_pairs = queue_count;
8783                 i40e_prep_for_reset(pf, true);
8784
8785                 pf->alloc_rss_size = new_rss_size;
8786
8787                 i40e_reset_and_rebuild(pf, true, true);
8788
8789                 /* Discard the user configured hash keys and lut, if less
8790                  * queues are enabled.
8791                  */
8792                 if (queue_count < vsi->rss_size) {
8793                         i40e_clear_rss_config_user(vsi);
8794                         dev_dbg(&pf->pdev->dev,
8795                                 "discard user configured hash keys and lut\n");
8796                 }
8797
8798                 /* Reset vsi->rss_size, as number of enabled queues changed */
8799                 qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
8800                 vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
8801
8802                 i40e_pf_config_rss(pf);
8803         }
8804         dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
8805                  vsi->req_queue_pairs, pf->rss_size_max);
8806         return pf->alloc_rss_size;
8807 }
8808
8809 /**
8810  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
8811  * @pf: board private structure
8812  **/
8813 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
8814 {
8815         i40e_status status;
8816         bool min_valid, max_valid;
8817         u32 max_bw, min_bw;
8818
8819         status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
8820                                            &min_valid, &max_valid);
8821
8822         if (!status) {
8823                 if (min_valid)
8824                         pf->min_bw = min_bw;
8825                 if (max_valid)
8826                         pf->max_bw = max_bw;
8827         }
8828
8829         return status;
8830 }
8831
8832 /**
8833  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
8834  * @pf: board private structure
8835  **/
8836 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
8837 {
8838         struct i40e_aqc_configure_partition_bw_data bw_data;
8839         i40e_status status;
8840
8841         /* Set the valid bit for this PF */
8842         bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
8843         bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
8844         bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
8845
8846         /* Set the new bandwidths */
8847         status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
8848
8849         return status;
8850 }
8851
8852 /**
8853  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
8854  * @pf: board private structure
8855  **/
8856 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
8857 {
8858         /* Commit temporary BW setting to permanent NVM image */
8859         enum i40e_admin_queue_err last_aq_status;
8860         i40e_status ret;
8861         u16 nvm_word;
8862
8863         if (pf->hw.partition_id != 1) {
8864                 dev_info(&pf->pdev->dev,
8865                          "Commit BW only works on partition 1! This is partition %d",
8866                          pf->hw.partition_id);
8867                 ret = I40E_NOT_SUPPORTED;
8868                 goto bw_commit_out;
8869         }
8870
8871         /* Acquire NVM for read access */
8872         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
8873         last_aq_status = pf->hw.aq.asq_last_status;
8874         if (ret) {
8875                 dev_info(&pf->pdev->dev,
8876                          "Cannot acquire NVM for read access, err %s aq_err %s\n",
8877                          i40e_stat_str(&pf->hw, ret),
8878                          i40e_aq_str(&pf->hw, last_aq_status));
8879                 goto bw_commit_out;
8880         }
8881
8882         /* Read word 0x10 of NVM - SW compatibility word 1 */
8883         ret = i40e_aq_read_nvm(&pf->hw,
8884                                I40E_SR_NVM_CONTROL_WORD,
8885                                0x10, sizeof(nvm_word), &nvm_word,
8886                                false, NULL);
8887         /* Save off last admin queue command status before releasing
8888          * the NVM
8889          */
8890         last_aq_status = pf->hw.aq.asq_last_status;
8891         i40e_release_nvm(&pf->hw);
8892         if (ret) {
8893                 dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
8894                          i40e_stat_str(&pf->hw, ret),
8895                          i40e_aq_str(&pf->hw, last_aq_status));
8896                 goto bw_commit_out;
8897         }
8898
8899         /* Wait a bit for NVM release to complete */
8900         msleep(50);
8901
8902         /* Acquire NVM for write access */
8903         ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
8904         last_aq_status = pf->hw.aq.asq_last_status;
8905         if (ret) {
8906                 dev_info(&pf->pdev->dev,
8907                          "Cannot acquire NVM for write access, err %s aq_err %s\n",
8908                          i40e_stat_str(&pf->hw, ret),
8909                          i40e_aq_str(&pf->hw, last_aq_status));
8910                 goto bw_commit_out;
8911         }
8912         /* Write it back out unchanged to initiate update NVM,
8913          * which will force a write of the shadow (alt) RAM to
8914          * the NVM - thus storing the bandwidth values permanently.
8915          */
8916         ret = i40e_aq_update_nvm(&pf->hw,
8917                                  I40E_SR_NVM_CONTROL_WORD,
8918                                  0x10, sizeof(nvm_word),
8919                                  &nvm_word, true, NULL);
8920         /* Save off last admin queue command status before releasing
8921          * the NVM
8922          */
8923         last_aq_status = pf->hw.aq.asq_last_status;
8924         i40e_release_nvm(&pf->hw);
8925         if (ret)
8926                 dev_info(&pf->pdev->dev,
8927                          "BW settings NOT SAVED, err %s aq_err %s\n",
8928                          i40e_stat_str(&pf->hw, ret),
8929                          i40e_aq_str(&pf->hw, last_aq_status));
8930 bw_commit_out:
8931
8932         return ret;
8933 }
8934
8935 /**
8936  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
8937  * @pf: board private structure to initialize
8938  *
8939  * i40e_sw_init initializes the Adapter private data structure.
8940  * Fields are initialized based on PCI device information and
8941  * OS network device settings (MTU size).
8942  **/
8943 static int i40e_sw_init(struct i40e_pf *pf)
8944 {
8945         int err = 0;
8946         int size;
8947         u16 pow;
8948
8949         /* Set default capability flags */
8950         pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
8951                     I40E_FLAG_MSI_ENABLED     |
8952                     I40E_FLAG_MSIX_ENABLED;
8953
8954         /* Set default ITR */
8955         pf->rx_itr_default = I40E_ITR_DYNAMIC | I40E_ITR_RX_DEF;
8956         pf->tx_itr_default = I40E_ITR_DYNAMIC | I40E_ITR_TX_DEF;
8957
8958         /* Depending on PF configurations, it is possible that the RSS
8959          * maximum might end up larger than the available queues
8960          */
8961         pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
8962         pf->alloc_rss_size = 1;
8963         pf->rss_table_size = pf->hw.func_caps.rss_table_size;
8964         pf->rss_size_max = min_t(int, pf->rss_size_max,
8965                                  pf->hw.func_caps.num_tx_qp);
8966
8967         /* find the next higher power-of-2 of num cpus */
8968         pow = roundup_pow_of_two(num_online_cpus());
8969         pf->rss_size_max = min_t(int, pf->rss_size_max, pow);
8970
8971         if (pf->hw.func_caps.rss) {
8972                 pf->flags |= I40E_FLAG_RSS_ENABLED;
8973                 pf->alloc_rss_size = min_t(int, pf->rss_size_max,
8974                                            num_online_cpus());
8975         }
8976
8977         /* MFP mode enabled */
8978         if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
8979                 pf->flags |= I40E_FLAG_MFP_ENABLED;
8980                 dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
8981                 if (i40e_get_partition_bw_setting(pf)) {
8982                         dev_warn(&pf->pdev->dev,
8983                                  "Could not get partition bw settings\n");
8984                 } else {
8985                         dev_info(&pf->pdev->dev,
8986                                  "Partition BW Min = %8.8x, Max = %8.8x\n",
8987                                  pf->min_bw, pf->max_bw);
8988
8989                         /* nudge the Tx scheduler */
8990                         i40e_set_partition_bw_setting(pf);
8991                 }
8992         }
8993
8994         if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
8995             (pf->hw.func_caps.fd_filters_best_effort > 0)) {
8996                 pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
8997                 pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
8998                 if (pf->flags & I40E_FLAG_MFP_ENABLED &&
8999                     pf->hw.num_partitions > 1)
9000                         dev_info(&pf->pdev->dev,
9001                                  "Flow Director Sideband mode Disabled in MFP mode\n");
9002                 else
9003                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9004                 pf->fdir_pf_filter_count =
9005                                  pf->hw.func_caps.fd_filters_guaranteed;
9006                 pf->hw.fdir_shared_filter_count =
9007                                  pf->hw.func_caps.fd_filters_best_effort;
9008         }
9009
9010         if (pf->hw.mac.type == I40E_MAC_X722) {
9011                 pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
9012                                     I40E_HW_128_QP_RSS_CAPABLE |
9013                                     I40E_HW_ATR_EVICT_CAPABLE |
9014                                     I40E_HW_WB_ON_ITR_CAPABLE |
9015                                     I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
9016                                     I40E_HW_NO_PCI_LINK_CHECK |
9017                                     I40E_HW_USE_SET_LLDP_MIB |
9018                                     I40E_HW_GENEVE_OFFLOAD_CAPABLE |
9019                                     I40E_HW_PTP_L4_CAPABLE |
9020                                     I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
9021                                     I40E_HW_OUTER_UDP_CSUM_CAPABLE);
9022
9023 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
9024                 if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
9025                     I40E_FDEVICT_PCTYPE_DEFAULT) {
9026                         dev_warn(&pf->pdev->dev,
9027                                  "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
9028                         pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
9029                 }
9030         } else if ((pf->hw.aq.api_maj_ver > 1) ||
9031                    ((pf->hw.aq.api_maj_ver == 1) &&
9032                     (pf->hw.aq.api_min_ver > 4))) {
9033                 /* Supported in FW API version higher than 1.4 */
9034                 pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
9035         }
9036
9037         /* Enable HW ATR eviction if possible */
9038         if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
9039                 pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
9040
9041         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
9042             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
9043             (pf->hw.aq.fw_maj_ver < 4))) {
9044                 pf->hw_features |= I40E_HW_RESTART_AUTONEG;
9045                 /* No DCB support  for FW < v4.33 */
9046                 pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
9047         }
9048
9049         /* Disable FW LLDP if FW < v4.3 */
9050         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
9051             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
9052             (pf->hw.aq.fw_maj_ver < 4)))
9053                 pf->hw_features |= I40E_HW_STOP_FW_LLDP;
9054
9055         /* Use the FW Set LLDP MIB API if FW > v4.40 */
9056         if ((pf->hw.mac.type == I40E_MAC_XL710) &&
9057             (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
9058             (pf->hw.aq.fw_maj_ver >= 5)))
9059                 pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
9060
9061         if (pf->hw.func_caps.vmdq) {
9062                 pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
9063                 pf->flags |= I40E_FLAG_VMDQ_ENABLED;
9064                 pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
9065         }
9066
9067         if (pf->hw.func_caps.iwarp) {
9068                 pf->flags |= I40E_FLAG_IWARP_ENABLED;
9069                 /* IWARP needs one extra vector for CQP just like MISC.*/
9070                 pf->num_iwarp_msix = (int)num_online_cpus() + 1;
9071         }
9072
9073 #ifdef CONFIG_PCI_IOV
9074         if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
9075                 pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
9076                 pf->flags |= I40E_FLAG_SRIOV_ENABLED;
9077                 pf->num_req_vfs = min_t(int,
9078                                         pf->hw.func_caps.num_vfs,
9079                                         I40E_MAX_VF_COUNT);
9080         }
9081 #endif /* CONFIG_PCI_IOV */
9082         pf->eeprom_version = 0xDEAD;
9083         pf->lan_veb = I40E_NO_VEB;
9084         pf->lan_vsi = I40E_NO_VSI;
9085
9086         /* By default FW has this off for performance reasons */
9087         pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
9088
9089         /* set up queue assignment tracking */
9090         size = sizeof(struct i40e_lump_tracking)
9091                 + (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
9092         pf->qp_pile = kzalloc(size, GFP_KERNEL);
9093         if (!pf->qp_pile) {
9094                 err = -ENOMEM;
9095                 goto sw_init_done;
9096         }
9097         pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
9098         pf->qp_pile->search_hint = 0;
9099
9100         pf->tx_timeout_recovery_level = 1;
9101
9102         mutex_init(&pf->switch_mutex);
9103
9104 sw_init_done:
9105         return err;
9106 }
9107
9108 /**
9109  * i40e_set_ntuple - set the ntuple feature flag and take action
9110  * @pf: board private structure to initialize
9111  * @features: the feature set that the stack is suggesting
9112  *
9113  * returns a bool to indicate if reset needs to happen
9114  **/
9115 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
9116 {
9117         bool need_reset = false;
9118
9119         /* Check if Flow Director n-tuple support was enabled or disabled.  If
9120          * the state changed, we need to reset.
9121          */
9122         if (features & NETIF_F_NTUPLE) {
9123                 /* Enable filters and mark for reset */
9124                 if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
9125                         need_reset = true;
9126                 /* enable FD_SB only if there is MSI-X vector */
9127                 if (pf->num_fdsb_msix > 0)
9128                         pf->flags |= I40E_FLAG_FD_SB_ENABLED;
9129         } else {
9130                 /* turn off filters, mark for reset and clear SW filter list */
9131                 if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
9132                         need_reset = true;
9133                         i40e_fdir_filter_exit(pf);
9134                 }
9135                 pf->flags &= ~(I40E_FLAG_FD_SB_ENABLED |
9136                                I40E_FLAG_FD_SB_AUTO_DISABLED);
9137                 /* reset fd counters */
9138                 pf->fd_add_err = 0;
9139                 pf->fd_atr_cnt = 0;
9140                 /* if ATR was auto disabled it can be re-enabled. */
9141                 if (pf->flags & I40E_FLAG_FD_ATR_AUTO_DISABLED) {
9142                         pf->flags &= ~I40E_FLAG_FD_ATR_AUTO_DISABLED;
9143                         if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
9144                             (I40E_DEBUG_FD & pf->hw.debug_mask))
9145                                 dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
9146                 }
9147         }
9148         return need_reset;
9149 }
9150
9151 /**
9152  * i40e_clear_rss_lut - clear the rx hash lookup table
9153  * @vsi: the VSI being configured
9154  **/
9155 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
9156 {
9157         struct i40e_pf *pf = vsi->back;
9158         struct i40e_hw *hw = &pf->hw;
9159         u16 vf_id = vsi->vf_id;
9160         u8 i;
9161
9162         if (vsi->type == I40E_VSI_MAIN) {
9163                 for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
9164                         wr32(hw, I40E_PFQF_HLUT(i), 0);
9165         } else if (vsi->type == I40E_VSI_SRIOV) {
9166                 for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
9167                         i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
9168         } else {
9169                 dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
9170         }
9171 }
9172
9173 /**
9174  * i40e_set_features - set the netdev feature flags
9175  * @netdev: ptr to the netdev being adjusted
9176  * @features: the feature set that the stack is suggesting
9177  * Note: expects to be called while under rtnl_lock()
9178  **/
9179 static int i40e_set_features(struct net_device *netdev,
9180                              netdev_features_t features)
9181 {
9182         struct i40e_netdev_priv *np = netdev_priv(netdev);
9183         struct i40e_vsi *vsi = np->vsi;
9184         struct i40e_pf *pf = vsi->back;
9185         bool need_reset;
9186
9187         if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
9188                 i40e_pf_config_rss(pf);
9189         else if (!(features & NETIF_F_RXHASH) &&
9190                  netdev->features & NETIF_F_RXHASH)
9191                 i40e_clear_rss_lut(vsi);
9192
9193         if (features & NETIF_F_HW_VLAN_CTAG_RX)
9194                 i40e_vlan_stripping_enable(vsi);
9195         else
9196                 i40e_vlan_stripping_disable(vsi);
9197
9198         need_reset = i40e_set_ntuple(pf, features);
9199
9200         if (need_reset)
9201                 i40e_do_reset(pf, BIT_ULL(__I40E_PF_RESET_REQUESTED), true);
9202
9203         return 0;
9204 }
9205
9206 /**
9207  * i40e_get_udp_port_idx - Lookup a possibly offloaded for Rx UDP port
9208  * @pf: board private structure
9209  * @port: The UDP port to look up
9210  *
9211  * Returns the index number or I40E_MAX_PF_UDP_OFFLOAD_PORTS if port not found
9212  **/
9213 static u8 i40e_get_udp_port_idx(struct i40e_pf *pf, u16 port)
9214 {
9215         u8 i;
9216
9217         for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
9218                 if (pf->udp_ports[i].port == port)
9219                         return i;
9220         }
9221
9222         return i;
9223 }
9224
9225 /**
9226  * i40e_udp_tunnel_add - Get notifications about UDP tunnel ports that come up
9227  * @netdev: This physical port's netdev
9228  * @ti: Tunnel endpoint information
9229  **/
9230 static void i40e_udp_tunnel_add(struct net_device *netdev,
9231                                 struct udp_tunnel_info *ti)
9232 {
9233         struct i40e_netdev_priv *np = netdev_priv(netdev);
9234         struct i40e_vsi *vsi = np->vsi;
9235         struct i40e_pf *pf = vsi->back;
9236         u16 port = ntohs(ti->port);
9237         u8 next_idx;
9238         u8 idx;
9239
9240         idx = i40e_get_udp_port_idx(pf, port);
9241
9242         /* Check if port already exists */
9243         if (idx < I40E_MAX_PF_UDP_OFFLOAD_PORTS) {
9244                 netdev_info(netdev, "port %d already offloaded\n", port);
9245                 return;
9246         }
9247
9248         /* Now check if there is space to add the new port */
9249         next_idx = i40e_get_udp_port_idx(pf, 0);
9250
9251         if (next_idx == I40E_MAX_PF_UDP_OFFLOAD_PORTS) {
9252                 netdev_info(netdev, "maximum number of offloaded UDP ports reached, not adding port %d\n",
9253                             port);
9254                 return;
9255         }
9256
9257         switch (ti->type) {
9258         case UDP_TUNNEL_TYPE_VXLAN:
9259                 pf->udp_ports[next_idx].type = I40E_AQC_TUNNEL_TYPE_VXLAN;
9260                 break;
9261         case UDP_TUNNEL_TYPE_GENEVE:
9262                 if (!(pf->hw_features & I40E_HW_GENEVE_OFFLOAD_CAPABLE))
9263                         return;
9264                 pf->udp_ports[next_idx].type = I40E_AQC_TUNNEL_TYPE_NGE;
9265                 break;
9266         default:
9267                 return;
9268         }
9269
9270         /* New port: add it and mark its index in the bitmap */
9271         pf->udp_ports[next_idx].port = port;
9272         pf->pending_udp_bitmap |= BIT_ULL(next_idx);
9273         pf->flags |= I40E_FLAG_UDP_FILTER_SYNC;
9274 }
9275
9276 /**
9277  * i40e_udp_tunnel_del - Get notifications about UDP tunnel ports that go away
9278  * @netdev: This physical port's netdev
9279  * @ti: Tunnel endpoint information
9280  **/
9281 static void i40e_udp_tunnel_del(struct net_device *netdev,
9282                                 struct udp_tunnel_info *ti)
9283 {
9284         struct i40e_netdev_priv *np = netdev_priv(netdev);
9285         struct i40e_vsi *vsi = np->vsi;
9286         struct i40e_pf *pf = vsi->back;
9287         u16 port = ntohs(ti->port);
9288         u8 idx;
9289
9290         idx = i40e_get_udp_port_idx(pf, port);
9291
9292         /* Check if port already exists */
9293         if (idx >= I40E_MAX_PF_UDP_OFFLOAD_PORTS)
9294                 goto not_found;
9295
9296         switch (ti->type) {
9297         case UDP_TUNNEL_TYPE_VXLAN:
9298                 if (pf->udp_ports[idx].type != I40E_AQC_TUNNEL_TYPE_VXLAN)
9299                         goto not_found;
9300                 break;
9301         case UDP_TUNNEL_TYPE_GENEVE:
9302                 if (pf->udp_ports[idx].type != I40E_AQC_TUNNEL_TYPE_NGE)
9303                         goto not_found;
9304                 break;
9305         default:
9306                 goto not_found;
9307         }
9308
9309         /* if port exists, set it to 0 (mark for deletion)
9310          * and make it pending
9311          */
9312         pf->udp_ports[idx].port = 0;
9313         pf->pending_udp_bitmap |= BIT_ULL(idx);
9314         pf->flags |= I40E_FLAG_UDP_FILTER_SYNC;
9315
9316         return;
9317 not_found:
9318         netdev_warn(netdev, "UDP port %d was not found, not deleting\n",
9319                     port);
9320 }
9321
9322 static int i40e_get_phys_port_id(struct net_device *netdev,
9323                                  struct netdev_phys_item_id *ppid)
9324 {
9325         struct i40e_netdev_priv *np = netdev_priv(netdev);
9326         struct i40e_pf *pf = np->vsi->back;
9327         struct i40e_hw *hw = &pf->hw;
9328
9329         if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
9330                 return -EOPNOTSUPP;
9331
9332         ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
9333         memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
9334
9335         return 0;
9336 }
9337
9338 /**
9339  * i40e_ndo_fdb_add - add an entry to the hardware database
9340  * @ndm: the input from the stack
9341  * @tb: pointer to array of nladdr (unused)
9342  * @dev: the net device pointer
9343  * @addr: the MAC address entry being added
9344  * @flags: instructions from stack about fdb operation
9345  */
9346 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
9347                             struct net_device *dev,
9348                             const unsigned char *addr, u16 vid,
9349                             u16 flags)
9350 {
9351         struct i40e_netdev_priv *np = netdev_priv(dev);
9352         struct i40e_pf *pf = np->vsi->back;
9353         int err = 0;
9354
9355         if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
9356                 return -EOPNOTSUPP;
9357
9358         if (vid) {
9359                 pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
9360                 return -EINVAL;
9361         }
9362
9363         /* Hardware does not support aging addresses so if a
9364          * ndm_state is given only allow permanent addresses
9365          */
9366         if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
9367                 netdev_info(dev, "FDB only supports static addresses\n");
9368                 return -EINVAL;
9369         }
9370
9371         if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
9372                 err = dev_uc_add_excl(dev, addr);
9373         else if (is_multicast_ether_addr(addr))
9374                 err = dev_mc_add_excl(dev, addr);
9375         else
9376                 err = -EINVAL;
9377
9378         /* Only return duplicate errors if NLM_F_EXCL is set */
9379         if (err == -EEXIST && !(flags & NLM_F_EXCL))
9380                 err = 0;
9381
9382         return err;
9383 }
9384
9385 /**
9386  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
9387  * @dev: the netdev being configured
9388  * @nlh: RTNL message
9389  *
9390  * Inserts a new hardware bridge if not already created and
9391  * enables the bridging mode requested (VEB or VEPA). If the
9392  * hardware bridge has already been inserted and the request
9393  * is to change the mode then that requires a PF reset to
9394  * allow rebuild of the components with required hardware
9395  * bridge mode enabled.
9396  *
9397  * Note: expects to be called while under rtnl_lock()
9398  **/
9399 static int i40e_ndo_bridge_setlink(struct net_device *dev,
9400                                    struct nlmsghdr *nlh,
9401                                    u16 flags)
9402 {
9403         struct i40e_netdev_priv *np = netdev_priv(dev);
9404         struct i40e_vsi *vsi = np->vsi;
9405         struct i40e_pf *pf = vsi->back;
9406         struct i40e_veb *veb = NULL;
9407         struct nlattr *attr, *br_spec;
9408         int i, rem;
9409
9410         /* Only for PF VSI for now */
9411         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
9412                 return -EOPNOTSUPP;
9413
9414         /* Find the HW bridge for PF VSI */
9415         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
9416                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
9417                         veb = pf->veb[i];
9418         }
9419
9420         br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
9421
9422         nla_for_each_nested(attr, br_spec, rem) {
9423                 __u16 mode;
9424
9425                 if (nla_type(attr) != IFLA_BRIDGE_MODE)
9426                         continue;
9427
9428                 mode = nla_get_u16(attr);
9429                 if ((mode != BRIDGE_MODE_VEPA) &&
9430                     (mode != BRIDGE_MODE_VEB))
9431                         return -EINVAL;
9432
9433                 /* Insert a new HW bridge */
9434                 if (!veb) {
9435                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
9436                                              vsi->tc_config.enabled_tc);
9437                         if (veb) {
9438                                 veb->bridge_mode = mode;
9439                                 i40e_config_bridge_mode(veb);
9440                         } else {
9441                                 /* No Bridge HW offload available */
9442                                 return -ENOENT;
9443                         }
9444                         break;
9445                 } else if (mode != veb->bridge_mode) {
9446                         /* Existing HW bridge but different mode needs reset */
9447                         veb->bridge_mode = mode;
9448                         /* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
9449                         if (mode == BRIDGE_MODE_VEB)
9450                                 pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
9451                         else
9452                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
9453                         i40e_do_reset(pf, BIT_ULL(__I40E_PF_RESET_REQUESTED),
9454                                       true);
9455                         break;
9456                 }
9457         }
9458
9459         return 0;
9460 }
9461
9462 /**
9463  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
9464  * @skb: skb buff
9465  * @pid: process id
9466  * @seq: RTNL message seq #
9467  * @dev: the netdev being configured
9468  * @filter_mask: unused
9469  * @nlflags: netlink flags passed in
9470  *
9471  * Return the mode in which the hardware bridge is operating in
9472  * i.e VEB or VEPA.
9473  **/
9474 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
9475                                    struct net_device *dev,
9476                                    u32 __always_unused filter_mask,
9477                                    int nlflags)
9478 {
9479         struct i40e_netdev_priv *np = netdev_priv(dev);
9480         struct i40e_vsi *vsi = np->vsi;
9481         struct i40e_pf *pf = vsi->back;
9482         struct i40e_veb *veb = NULL;
9483         int i;
9484
9485         /* Only for PF VSI for now */
9486         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
9487                 return -EOPNOTSUPP;
9488
9489         /* Find the HW bridge for the PF VSI */
9490         for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
9491                 if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
9492                         veb = pf->veb[i];
9493         }
9494
9495         if (!veb)
9496                 return 0;
9497
9498         return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
9499                                        0, 0, nlflags, filter_mask, NULL);
9500 }
9501
9502 /**
9503  * i40e_features_check - Validate encapsulated packet conforms to limits
9504  * @skb: skb buff
9505  * @dev: This physical port's netdev
9506  * @features: Offload features that the stack believes apply
9507  **/
9508 static netdev_features_t i40e_features_check(struct sk_buff *skb,
9509                                              struct net_device *dev,
9510                                              netdev_features_t features)
9511 {
9512         size_t len;
9513
9514         /* No point in doing any of this if neither checksum nor GSO are
9515          * being requested for this frame.  We can rule out both by just
9516          * checking for CHECKSUM_PARTIAL
9517          */
9518         if (skb->ip_summed != CHECKSUM_PARTIAL)
9519                 return features;
9520
9521         /* We cannot support GSO if the MSS is going to be less than
9522          * 64 bytes.  If it is then we need to drop support for GSO.
9523          */
9524         if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
9525                 features &= ~NETIF_F_GSO_MASK;
9526
9527         /* MACLEN can support at most 63 words */
9528         len = skb_network_header(skb) - skb->data;
9529         if (len & ~(63 * 2))
9530                 goto out_err;
9531
9532         /* IPLEN and EIPLEN can support at most 127 dwords */
9533         len = skb_transport_header(skb) - skb_network_header(skb);
9534         if (len & ~(127 * 4))
9535                 goto out_err;
9536
9537         if (skb->encapsulation) {
9538                 /* L4TUNLEN can support 127 words */
9539                 len = skb_inner_network_header(skb) - skb_transport_header(skb);
9540                 if (len & ~(127 * 2))
9541                         goto out_err;
9542
9543                 /* IPLEN can support at most 127 dwords */
9544                 len = skb_inner_transport_header(skb) -
9545                       skb_inner_network_header(skb);
9546                 if (len & ~(127 * 4))
9547                         goto out_err;
9548         }
9549
9550         /* No need to validate L4LEN as TCP is the only protocol with a
9551          * a flexible value and we support all possible values supported
9552          * by TCP, which is at most 15 dwords
9553          */
9554
9555         return features;
9556 out_err:
9557         return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
9558 }
9559
9560 /**
9561  * i40e_xdp_setup - add/remove an XDP program
9562  * @vsi: VSI to changed
9563  * @prog: XDP program
9564  **/
9565 static int i40e_xdp_setup(struct i40e_vsi *vsi,
9566                           struct bpf_prog *prog)
9567 {
9568         int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
9569         struct i40e_pf *pf = vsi->back;
9570         struct bpf_prog *old_prog;
9571         bool need_reset;
9572         int i;
9573
9574         /* Don't allow frames that span over multiple buffers */
9575         if (frame_size > vsi->rx_buf_len)
9576                 return -EINVAL;
9577
9578         if (!i40e_enabled_xdp_vsi(vsi) && !prog)
9579                 return 0;
9580
9581         /* When turning XDP on->off/off->on we reset and rebuild the rings. */
9582         need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
9583
9584         if (need_reset)
9585                 i40e_prep_for_reset(pf, true);
9586
9587         old_prog = xchg(&vsi->xdp_prog, prog);
9588
9589         if (need_reset)
9590                 i40e_reset_and_rebuild(pf, true, true);
9591
9592         for (i = 0; i < vsi->num_queue_pairs; i++)
9593                 WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
9594
9595         if (old_prog)
9596                 bpf_prog_put(old_prog);
9597
9598         return 0;
9599 }
9600
9601 /**
9602  * i40e_xdp - implements ndo_xdp for i40e
9603  * @dev: netdevice
9604  * @xdp: XDP command
9605  **/
9606 static int i40e_xdp(struct net_device *dev,
9607                     struct netdev_xdp *xdp)
9608 {
9609         struct i40e_netdev_priv *np = netdev_priv(dev);
9610         struct i40e_vsi *vsi = np->vsi;
9611
9612         if (vsi->type != I40E_VSI_MAIN)
9613                 return -EINVAL;
9614
9615         switch (xdp->command) {
9616         case XDP_SETUP_PROG:
9617                 return i40e_xdp_setup(vsi, xdp->prog);
9618         case XDP_QUERY_PROG:
9619                 xdp->prog_attached = i40e_enabled_xdp_vsi(vsi);
9620                 xdp->prog_id = vsi->xdp_prog ? vsi->xdp_prog->aux->id : 0;
9621                 return 0;
9622         default:
9623                 return -EINVAL;
9624         }
9625 }
9626
9627 static const struct net_device_ops i40e_netdev_ops = {
9628         .ndo_open               = i40e_open,
9629         .ndo_stop               = i40e_close,
9630         .ndo_start_xmit         = i40e_lan_xmit_frame,
9631         .ndo_get_stats64        = i40e_get_netdev_stats_struct,
9632         .ndo_set_rx_mode        = i40e_set_rx_mode,
9633         .ndo_validate_addr      = eth_validate_addr,
9634         .ndo_set_mac_address    = i40e_set_mac,
9635         .ndo_change_mtu         = i40e_change_mtu,
9636         .ndo_do_ioctl           = i40e_ioctl,
9637         .ndo_tx_timeout         = i40e_tx_timeout,
9638         .ndo_vlan_rx_add_vid    = i40e_vlan_rx_add_vid,
9639         .ndo_vlan_rx_kill_vid   = i40e_vlan_rx_kill_vid,
9640 #ifdef CONFIG_NET_POLL_CONTROLLER
9641         .ndo_poll_controller    = i40e_netpoll,
9642 #endif
9643         .ndo_setup_tc           = __i40e_setup_tc,
9644         .ndo_set_features       = i40e_set_features,
9645         .ndo_set_vf_mac         = i40e_ndo_set_vf_mac,
9646         .ndo_set_vf_vlan        = i40e_ndo_set_vf_port_vlan,
9647         .ndo_set_vf_rate        = i40e_ndo_set_vf_bw,
9648         .ndo_get_vf_config      = i40e_ndo_get_vf_config,
9649         .ndo_set_vf_link_state  = i40e_ndo_set_vf_link_state,
9650         .ndo_set_vf_spoofchk    = i40e_ndo_set_vf_spoofchk,
9651         .ndo_set_vf_trust       = i40e_ndo_set_vf_trust,
9652         .ndo_udp_tunnel_add     = i40e_udp_tunnel_add,
9653         .ndo_udp_tunnel_del     = i40e_udp_tunnel_del,
9654         .ndo_get_phys_port_id   = i40e_get_phys_port_id,
9655         .ndo_fdb_add            = i40e_ndo_fdb_add,
9656         .ndo_features_check     = i40e_features_check,
9657         .ndo_bridge_getlink     = i40e_ndo_bridge_getlink,
9658         .ndo_bridge_setlink     = i40e_ndo_bridge_setlink,
9659         .ndo_xdp                = i40e_xdp,
9660 };
9661
9662 /**
9663  * i40e_config_netdev - Setup the netdev flags
9664  * @vsi: the VSI being configured
9665  *
9666  * Returns 0 on success, negative value on failure
9667  **/
9668 static int i40e_config_netdev(struct i40e_vsi *vsi)
9669 {
9670         struct i40e_pf *pf = vsi->back;
9671         struct i40e_hw *hw = &pf->hw;
9672         struct i40e_netdev_priv *np;
9673         struct net_device *netdev;
9674         u8 broadcast[ETH_ALEN];
9675         u8 mac_addr[ETH_ALEN];
9676         int etherdev_size;
9677         netdev_features_t hw_enc_features;
9678         netdev_features_t hw_features;
9679
9680         etherdev_size = sizeof(struct i40e_netdev_priv);
9681         netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
9682         if (!netdev)
9683                 return -ENOMEM;
9684
9685         vsi->netdev = netdev;
9686         np = netdev_priv(netdev);
9687         np->vsi = vsi;
9688
9689         hw_enc_features = NETIF_F_SG                    |
9690                           NETIF_F_IP_CSUM               |
9691                           NETIF_F_IPV6_CSUM             |
9692                           NETIF_F_HIGHDMA               |
9693                           NETIF_F_SOFT_FEATURES         |
9694                           NETIF_F_TSO                   |
9695                           NETIF_F_TSO_ECN               |
9696                           NETIF_F_TSO6                  |
9697                           NETIF_F_GSO_GRE               |
9698                           NETIF_F_GSO_GRE_CSUM          |
9699                           NETIF_F_GSO_PARTIAL           |
9700                           NETIF_F_GSO_IPXIP4            |
9701                           NETIF_F_GSO_IPXIP6            |
9702                           NETIF_F_GSO_UDP_TUNNEL        |
9703                           NETIF_F_GSO_UDP_TUNNEL_CSUM   |
9704                           NETIF_F_SCTP_CRC              |
9705                           NETIF_F_RXHASH                |
9706                           NETIF_F_RXCSUM                |
9707                           0;
9708
9709         if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
9710                 netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
9711
9712         netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
9713
9714         netdev->hw_enc_features |= hw_enc_features;
9715
9716         /* record features VLANs can make use of */
9717         netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
9718
9719         if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
9720                 netdev->hw_features |= NETIF_F_NTUPLE;
9721         hw_features = hw_enc_features           |
9722                       NETIF_F_HW_VLAN_CTAG_TX   |
9723                       NETIF_F_HW_VLAN_CTAG_RX;
9724
9725         netdev->hw_features |= hw_features;
9726
9727         netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
9728         netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
9729
9730         if (vsi->type == I40E_VSI_MAIN) {
9731                 SET_NETDEV_DEV(netdev, &pf->pdev->dev);
9732                 ether_addr_copy(mac_addr, hw->mac.perm_addr);
9733                 /* The following steps are necessary for two reasons. First,
9734                  * some older NVM configurations load a default MAC-VLAN
9735                  * filter that will accept any tagged packet, and we want to
9736                  * replace this with a normal filter. Additionally, it is
9737                  * possible our MAC address was provided by the platform using
9738                  * Open Firmware or similar.
9739                  *
9740                  * Thus, we need to remove the default filter and install one
9741                  * specific to the MAC address.
9742                  */
9743                 i40e_rm_default_mac_filter(vsi, mac_addr);
9744                 spin_lock_bh(&vsi->mac_filter_hash_lock);
9745                 i40e_add_mac_filter(vsi, mac_addr);
9746                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
9747         } else {
9748                 /* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
9749                  * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
9750                  * the end, which is 4 bytes long, so force truncation of the
9751                  * original name by IFNAMSIZ - 4
9752                  */
9753                 snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
9754                          IFNAMSIZ - 4,
9755                          pf->vsi[pf->lan_vsi]->netdev->name);
9756                 random_ether_addr(mac_addr);
9757
9758                 spin_lock_bh(&vsi->mac_filter_hash_lock);
9759                 i40e_add_mac_filter(vsi, mac_addr);
9760                 spin_unlock_bh(&vsi->mac_filter_hash_lock);
9761         }
9762
9763         /* Add the broadcast filter so that we initially will receive
9764          * broadcast packets. Note that when a new VLAN is first added the
9765          * driver will convert all filters marked I40E_VLAN_ANY into VLAN
9766          * specific filters as part of transitioning into "vlan" operation.
9767          * When more VLANs are added, the driver will copy each existing MAC
9768          * filter and add it for the new VLAN.
9769          *
9770          * Broadcast filters are handled specially by
9771          * i40e_sync_filters_subtask, as the driver must to set the broadcast
9772          * promiscuous bit instead of adding this directly as a MAC/VLAN
9773          * filter. The subtask will update the correct broadcast promiscuous
9774          * bits as VLANs become active or inactive.
9775          */
9776         eth_broadcast_addr(broadcast);
9777         spin_lock_bh(&vsi->mac_filter_hash_lock);
9778         i40e_add_mac_filter(vsi, broadcast);
9779         spin_unlock_bh(&vsi->mac_filter_hash_lock);
9780
9781         ether_addr_copy(netdev->dev_addr, mac_addr);
9782         ether_addr_copy(netdev->perm_addr, mac_addr);
9783
9784         /* i40iw_net_event() reads 16 bytes from neigh->primary_key */
9785         netdev->neigh_priv_len = sizeof(u32) * 4;
9786
9787         netdev->priv_flags |= IFF_UNICAST_FLT;
9788         netdev->priv_flags |= IFF_SUPP_NOFCS;
9789         /* Setup netdev TC information */
9790         i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
9791
9792         netdev->netdev_ops = &i40e_netdev_ops;
9793         netdev->watchdog_timeo = 5 * HZ;
9794         i40e_set_ethtool_ops(netdev);
9795
9796         /* MTU range: 68 - 9706 */
9797         netdev->min_mtu = ETH_MIN_MTU;
9798         netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
9799
9800         return 0;
9801 }
9802
9803 /**
9804  * i40e_vsi_delete - Delete a VSI from the switch
9805  * @vsi: the VSI being removed
9806  *
9807  * Returns 0 on success, negative value on failure
9808  **/
9809 static void i40e_vsi_delete(struct i40e_vsi *vsi)
9810 {
9811         /* remove default VSI is not allowed */
9812         if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
9813                 return;
9814
9815         i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
9816 }
9817
9818 /**
9819  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
9820  * @vsi: the VSI being queried
9821  *
9822  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
9823  **/
9824 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
9825 {
9826         struct i40e_veb *veb;
9827         struct i40e_pf *pf = vsi->back;
9828
9829         /* Uplink is not a bridge so default to VEB */
9830         if (vsi->veb_idx == I40E_NO_VEB)
9831                 return 1;
9832
9833         veb = pf->veb[vsi->veb_idx];
9834         if (!veb) {
9835                 dev_info(&pf->pdev->dev,
9836                          "There is no veb associated with the bridge\n");
9837                 return -ENOENT;
9838         }
9839
9840         /* Uplink is a bridge in VEPA mode */
9841         if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
9842                 return 0;
9843         } else {
9844                 /* Uplink is a bridge in VEB mode */
9845                 return 1;
9846         }
9847
9848         /* VEPA is now default bridge, so return 0 */
9849         return 0;
9850 }
9851
9852 /**
9853  * i40e_add_vsi - Add a VSI to the switch
9854  * @vsi: the VSI being configured
9855  *
9856  * This initializes a VSI context depending on the VSI type to be added and
9857  * passes it down to the add_vsi aq command.
9858  **/
9859 static int i40e_add_vsi(struct i40e_vsi *vsi)
9860 {
9861         int ret = -ENODEV;
9862         struct i40e_pf *pf = vsi->back;
9863         struct i40e_hw *hw = &pf->hw;
9864         struct i40e_vsi_context ctxt;
9865         struct i40e_mac_filter *f;
9866         struct hlist_node *h;
9867         int bkt;
9868
9869         u8 enabled_tc = 0x1; /* TC0 enabled */
9870         int f_count = 0;
9871
9872         memset(&ctxt, 0, sizeof(ctxt));
9873         switch (vsi->type) {
9874         case I40E_VSI_MAIN:
9875                 /* The PF's main VSI is already setup as part of the
9876                  * device initialization, so we'll not bother with
9877                  * the add_vsi call, but we will retrieve the current
9878                  * VSI context.
9879                  */
9880                 ctxt.seid = pf->main_vsi_seid;
9881                 ctxt.pf_num = pf->hw.pf_id;
9882                 ctxt.vf_num = 0;
9883                 ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
9884                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9885                 if (ret) {
9886                         dev_info(&pf->pdev->dev,
9887                                  "couldn't get PF vsi config, err %s aq_err %s\n",
9888                                  i40e_stat_str(&pf->hw, ret),
9889                                  i40e_aq_str(&pf->hw,
9890                                              pf->hw.aq.asq_last_status));
9891                         return -ENOENT;
9892                 }
9893                 vsi->info = ctxt.info;
9894                 vsi->info.valid_sections = 0;
9895
9896                 vsi->seid = ctxt.seid;
9897                 vsi->id = ctxt.vsi_number;
9898
9899                 enabled_tc = i40e_pf_get_tc_map(pf);
9900
9901                 /* MFP mode setup queue map and update VSI */
9902                 if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
9903                     !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
9904                         memset(&ctxt, 0, sizeof(ctxt));
9905                         ctxt.seid = pf->main_vsi_seid;
9906                         ctxt.pf_num = pf->hw.pf_id;
9907                         ctxt.vf_num = 0;
9908                         i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
9909                         ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
9910                         if (ret) {
9911                                 dev_info(&pf->pdev->dev,
9912                                          "update vsi failed, err %s aq_err %s\n",
9913                                          i40e_stat_str(&pf->hw, ret),
9914                                          i40e_aq_str(&pf->hw,
9915                                                     pf->hw.aq.asq_last_status));
9916                                 ret = -ENOENT;
9917                                 goto err;
9918                         }
9919                         /* update the local VSI info queue map */
9920                         i40e_vsi_update_queue_map(vsi, &ctxt);
9921                         vsi->info.valid_sections = 0;
9922                 } else {
9923                         /* Default/Main VSI is only enabled for TC0
9924                          * reconfigure it to enable all TCs that are
9925                          * available on the port in SFP mode.
9926                          * For MFP case the iSCSI PF would use this
9927                          * flow to enable LAN+iSCSI TC.
9928                          */
9929                         ret = i40e_vsi_config_tc(vsi, enabled_tc);
9930                         if (ret) {
9931                                 /* Single TC condition is not fatal,
9932                                  * message and continue
9933                                  */
9934                                 dev_info(&pf->pdev->dev,
9935                                          "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
9936                                          enabled_tc,
9937                                          i40e_stat_str(&pf->hw, ret),
9938                                          i40e_aq_str(&pf->hw,
9939                                                     pf->hw.aq.asq_last_status));
9940                         }
9941                 }
9942                 break;
9943
9944         case I40E_VSI_FDIR:
9945                 ctxt.pf_num = hw->pf_id;
9946                 ctxt.vf_num = 0;
9947                 ctxt.uplink_seid = vsi->uplink_seid;
9948                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
9949                 ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9950                 if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
9951                     (i40e_is_vsi_uplink_mode_veb(vsi))) {
9952                         ctxt.info.valid_sections |=
9953                              cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9954                         ctxt.info.switch_id =
9955                            cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9956                 }
9957                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
9958                 break;
9959
9960         case I40E_VSI_VMDQ2:
9961                 ctxt.pf_num = hw->pf_id;
9962                 ctxt.vf_num = 0;
9963                 ctxt.uplink_seid = vsi->uplink_seid;
9964                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
9965                 ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
9966
9967                 /* This VSI is connected to VEB so the switch_id
9968                  * should be set to zero by default.
9969                  */
9970                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
9971                         ctxt.info.valid_sections |=
9972                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9973                         ctxt.info.switch_id =
9974                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9975                 }
9976
9977                 /* Setup the VSI tx/rx queue map for TC0 only for now */
9978                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
9979                 break;
9980
9981         case I40E_VSI_SRIOV:
9982                 ctxt.pf_num = hw->pf_id;
9983                 ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
9984                 ctxt.uplink_seid = vsi->uplink_seid;
9985                 ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
9986                 ctxt.flags = I40E_AQ_VSI_TYPE_VF;
9987
9988                 /* This VSI is connected to VEB so the switch_id
9989                  * should be set to zero by default.
9990                  */
9991                 if (i40e_is_vsi_uplink_mode_veb(vsi)) {
9992                         ctxt.info.valid_sections |=
9993                                 cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9994                         ctxt.info.switch_id =
9995                                 cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9996                 }
9997
9998                 if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
9999                         ctxt.info.valid_sections |=
10000                                 cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
10001                         ctxt.info.queueing_opt_flags |=
10002                                 (I40E_AQ_VSI_QUE_OPT_TCP_ENA |
10003                                  I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
10004                 }
10005
10006                 ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
10007                 ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
10008                 if (pf->vf[vsi->vf_id].spoofchk) {
10009                         ctxt.info.valid_sections |=
10010                                 cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
10011                         ctxt.info.sec_flags |=
10012                                 (I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
10013                                  I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
10014                 }
10015                 /* Setup the VSI tx/rx queue map for TC0 only for now */
10016                 i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
10017                 break;
10018
10019         case I40E_VSI_IWARP:
10020                 /* send down message to iWARP */
10021                 break;
10022
10023         default:
10024                 return -ENODEV;
10025         }
10026
10027         if (vsi->type != I40E_VSI_MAIN) {
10028                 ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
10029                 if (ret) {
10030                         dev_info(&vsi->back->pdev->dev,
10031                                  "add vsi failed, err %s aq_err %s\n",
10032                                  i40e_stat_str(&pf->hw, ret),
10033                                  i40e_aq_str(&pf->hw,
10034                                              pf->hw.aq.asq_last_status));
10035                         ret = -ENOENT;
10036                         goto err;
10037                 }
10038                 vsi->info = ctxt.info;
10039                 vsi->info.valid_sections = 0;
10040                 vsi->seid = ctxt.seid;
10041                 vsi->id = ctxt.vsi_number;
10042         }
10043
10044         vsi->active_filters = 0;
10045         clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
10046         spin_lock_bh(&vsi->mac_filter_hash_lock);
10047         /* If macvlan filters already exist, force them to get loaded */
10048         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
10049                 f->state = I40E_FILTER_NEW;
10050                 f_count++;
10051         }
10052         spin_unlock_bh(&vsi->mac_filter_hash_lock);
10053
10054         if (f_count) {
10055                 vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
10056                 pf->flags |= I40E_FLAG_FILTER_SYNC;
10057         }
10058
10059         /* Update VSI BW information */
10060         ret = i40e_vsi_get_bw_info(vsi);
10061         if (ret) {
10062                 dev_info(&pf->pdev->dev,
10063                          "couldn't get vsi bw info, err %s aq_err %s\n",
10064                          i40e_stat_str(&pf->hw, ret),
10065                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10066                 /* VSI is already added so not tearing that up */
10067                 ret = 0;
10068         }
10069
10070 err:
10071         return ret;
10072 }
10073
10074 /**
10075  * i40e_vsi_release - Delete a VSI and free its resources
10076  * @vsi: the VSI being removed
10077  *
10078  * Returns 0 on success or < 0 on error
10079  **/
10080 int i40e_vsi_release(struct i40e_vsi *vsi)
10081 {
10082         struct i40e_mac_filter *f;
10083         struct hlist_node *h;
10084         struct i40e_veb *veb = NULL;
10085         struct i40e_pf *pf;
10086         u16 uplink_seid;
10087         int i, n, bkt;
10088
10089         pf = vsi->back;
10090
10091         /* release of a VEB-owner or last VSI is not allowed */
10092         if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
10093                 dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
10094                          vsi->seid, vsi->uplink_seid);
10095                 return -ENODEV;
10096         }
10097         if (vsi == pf->vsi[pf->lan_vsi] &&
10098             !test_bit(__I40E_DOWN, pf->state)) {
10099                 dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
10100                 return -ENODEV;
10101         }
10102         set_bit(__I40E_VSI_RELEASING, vsi->state);
10103         uplink_seid = vsi->uplink_seid;
10104         if (vsi->type != I40E_VSI_SRIOV) {
10105                 if (vsi->netdev_registered) {
10106                         vsi->netdev_registered = false;
10107                         if (vsi->netdev) {
10108                                 /* results in a call to i40e_close() */
10109                                 unregister_netdev(vsi->netdev);
10110                         }
10111                 } else {
10112                         i40e_vsi_close(vsi);
10113                 }
10114                 i40e_vsi_disable_irq(vsi);
10115         }
10116
10117         spin_lock_bh(&vsi->mac_filter_hash_lock);
10118
10119         /* clear the sync flag on all filters */
10120         if (vsi->netdev) {
10121                 __dev_uc_unsync(vsi->netdev, NULL);
10122                 __dev_mc_unsync(vsi->netdev, NULL);
10123         }
10124
10125         /* make sure any remaining filters are marked for deletion */
10126         hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
10127                 __i40e_del_filter(vsi, f);
10128
10129         spin_unlock_bh(&vsi->mac_filter_hash_lock);
10130
10131         i40e_sync_vsi_filters(vsi);
10132
10133         i40e_vsi_delete(vsi);
10134         i40e_vsi_free_q_vectors(vsi);
10135         if (vsi->netdev) {
10136                 free_netdev(vsi->netdev);
10137                 vsi->netdev = NULL;
10138         }
10139         i40e_vsi_clear_rings(vsi);
10140         i40e_vsi_clear(vsi);
10141
10142         /* If this was the last thing on the VEB, except for the
10143          * controlling VSI, remove the VEB, which puts the controlling
10144          * VSI onto the next level down in the switch.
10145          *
10146          * Well, okay, there's one more exception here: don't remove
10147          * the orphan VEBs yet.  We'll wait for an explicit remove request
10148          * from up the network stack.
10149          */
10150         for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
10151                 if (pf->vsi[i] &&
10152                     pf->vsi[i]->uplink_seid == uplink_seid &&
10153                     (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
10154                         n++;      /* count the VSIs */
10155                 }
10156         }
10157         for (i = 0; i < I40E_MAX_VEB; i++) {
10158                 if (!pf->veb[i])
10159                         continue;
10160                 if (pf->veb[i]->uplink_seid == uplink_seid)
10161                         n++;     /* count the VEBs */
10162                 if (pf->veb[i]->seid == uplink_seid)
10163                         veb = pf->veb[i];
10164         }
10165         if (n == 0 && veb && veb->uplink_seid != 0)
10166                 i40e_veb_release(veb);
10167
10168         return 0;
10169 }
10170
10171 /**
10172  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
10173  * @vsi: ptr to the VSI
10174  *
10175  * This should only be called after i40e_vsi_mem_alloc() which allocates the
10176  * corresponding SW VSI structure and initializes num_queue_pairs for the
10177  * newly allocated VSI.
10178  *
10179  * Returns 0 on success or negative on failure
10180  **/
10181 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
10182 {
10183         int ret = -ENOENT;
10184         struct i40e_pf *pf = vsi->back;
10185
10186         if (vsi->q_vectors[0]) {
10187                 dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
10188                          vsi->seid);
10189                 return -EEXIST;
10190         }
10191
10192         if (vsi->base_vector) {
10193                 dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
10194                          vsi->seid, vsi->base_vector);
10195                 return -EEXIST;
10196         }
10197
10198         ret = i40e_vsi_alloc_q_vectors(vsi);
10199         if (ret) {
10200                 dev_info(&pf->pdev->dev,
10201                          "failed to allocate %d q_vector for VSI %d, ret=%d\n",
10202                          vsi->num_q_vectors, vsi->seid, ret);
10203                 vsi->num_q_vectors = 0;
10204                 goto vector_setup_out;
10205         }
10206
10207         /* In Legacy mode, we do not have to get any other vector since we
10208          * piggyback on the misc/ICR0 for queue interrupts.
10209         */
10210         if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
10211                 return ret;
10212         if (vsi->num_q_vectors)
10213                 vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
10214                                                  vsi->num_q_vectors, vsi->idx);
10215         if (vsi->base_vector < 0) {
10216                 dev_info(&pf->pdev->dev,
10217                          "failed to get tracking for %d vectors for VSI %d, err=%d\n",
10218                          vsi->num_q_vectors, vsi->seid, vsi->base_vector);
10219                 i40e_vsi_free_q_vectors(vsi);
10220                 ret = -ENOENT;
10221                 goto vector_setup_out;
10222         }
10223
10224 vector_setup_out:
10225         return ret;
10226 }
10227
10228 /**
10229  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
10230  * @vsi: pointer to the vsi.
10231  *
10232  * This re-allocates a vsi's queue resources.
10233  *
10234  * Returns pointer to the successfully allocated and configured VSI sw struct
10235  * on success, otherwise returns NULL on failure.
10236  **/
10237 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
10238 {
10239         u16 alloc_queue_pairs;
10240         struct i40e_pf *pf;
10241         u8 enabled_tc;
10242         int ret;
10243
10244         if (!vsi)
10245                 return NULL;
10246
10247         pf = vsi->back;
10248
10249         i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
10250         i40e_vsi_clear_rings(vsi);
10251
10252         i40e_vsi_free_arrays(vsi, false);
10253         i40e_set_num_rings_in_vsi(vsi);
10254         ret = i40e_vsi_alloc_arrays(vsi, false);
10255         if (ret)
10256                 goto err_vsi;
10257
10258         alloc_queue_pairs = vsi->alloc_queue_pairs *
10259                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
10260
10261         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
10262         if (ret < 0) {
10263                 dev_info(&pf->pdev->dev,
10264                          "failed to get tracking for %d queues for VSI %d err %d\n",
10265                          alloc_queue_pairs, vsi->seid, ret);
10266                 goto err_vsi;
10267         }
10268         vsi->base_queue = ret;
10269
10270         /* Update the FW view of the VSI. Force a reset of TC and queue
10271          * layout configurations.
10272          */
10273         enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
10274         pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
10275         pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
10276         i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
10277         if (vsi->type == I40E_VSI_MAIN)
10278                 i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
10279
10280         /* assign it some queues */
10281         ret = i40e_alloc_rings(vsi);
10282         if (ret)
10283                 goto err_rings;
10284
10285         /* map all of the rings to the q_vectors */
10286         i40e_vsi_map_rings_to_vectors(vsi);
10287         return vsi;
10288
10289 err_rings:
10290         i40e_vsi_free_q_vectors(vsi);
10291         if (vsi->netdev_registered) {
10292                 vsi->netdev_registered = false;
10293                 unregister_netdev(vsi->netdev);
10294                 free_netdev(vsi->netdev);
10295                 vsi->netdev = NULL;
10296         }
10297         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
10298 err_vsi:
10299         i40e_vsi_clear(vsi);
10300         return NULL;
10301 }
10302
10303 /**
10304  * i40e_vsi_setup - Set up a VSI by a given type
10305  * @pf: board private structure
10306  * @type: VSI type
10307  * @uplink_seid: the switch element to link to
10308  * @param1: usage depends upon VSI type. For VF types, indicates VF id
10309  *
10310  * This allocates the sw VSI structure and its queue resources, then add a VSI
10311  * to the identified VEB.
10312  *
10313  * Returns pointer to the successfully allocated and configure VSI sw struct on
10314  * success, otherwise returns NULL on failure.
10315  **/
10316 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
10317                                 u16 uplink_seid, u32 param1)
10318 {
10319         struct i40e_vsi *vsi = NULL;
10320         struct i40e_veb *veb = NULL;
10321         u16 alloc_queue_pairs;
10322         int ret, i;
10323         int v_idx;
10324
10325         /* The requested uplink_seid must be either
10326          *     - the PF's port seid
10327          *              no VEB is needed because this is the PF
10328          *              or this is a Flow Director special case VSI
10329          *     - seid of an existing VEB
10330          *     - seid of a VSI that owns an existing VEB
10331          *     - seid of a VSI that doesn't own a VEB
10332          *              a new VEB is created and the VSI becomes the owner
10333          *     - seid of the PF VSI, which is what creates the first VEB
10334          *              this is a special case of the previous
10335          *
10336          * Find which uplink_seid we were given and create a new VEB if needed
10337          */
10338         for (i = 0; i < I40E_MAX_VEB; i++) {
10339                 if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
10340                         veb = pf->veb[i];
10341                         break;
10342                 }
10343         }
10344
10345         if (!veb && uplink_seid != pf->mac_seid) {
10346
10347                 for (i = 0; i < pf->num_alloc_vsi; i++) {
10348                         if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
10349                                 vsi = pf->vsi[i];
10350                                 break;
10351                         }
10352                 }
10353                 if (!vsi) {
10354                         dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
10355                                  uplink_seid);
10356                         return NULL;
10357                 }
10358
10359                 if (vsi->uplink_seid == pf->mac_seid)
10360                         veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
10361                                              vsi->tc_config.enabled_tc);
10362                 else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
10363                         veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
10364                                              vsi->tc_config.enabled_tc);
10365                 if (veb) {
10366                         if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
10367                                 dev_info(&vsi->back->pdev->dev,
10368                                          "New VSI creation error, uplink seid of LAN VSI expected.\n");
10369                                 return NULL;
10370                         }
10371                         /* We come up by default in VEPA mode if SRIOV is not
10372                          * already enabled, in which case we can't force VEPA
10373                          * mode.
10374                          */
10375                         if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
10376                                 veb->bridge_mode = BRIDGE_MODE_VEPA;
10377                                 pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
10378                         }
10379                         i40e_config_bridge_mode(veb);
10380                 }
10381                 for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
10382                         if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
10383                                 veb = pf->veb[i];
10384                 }
10385                 if (!veb) {
10386                         dev_info(&pf->pdev->dev, "couldn't add VEB\n");
10387                         return NULL;
10388                 }
10389
10390                 vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
10391                 uplink_seid = veb->seid;
10392         }
10393
10394         /* get vsi sw struct */
10395         v_idx = i40e_vsi_mem_alloc(pf, type);
10396         if (v_idx < 0)
10397                 goto err_alloc;
10398         vsi = pf->vsi[v_idx];
10399         if (!vsi)
10400                 goto err_alloc;
10401         vsi->type = type;
10402         vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
10403
10404         if (type == I40E_VSI_MAIN)
10405                 pf->lan_vsi = v_idx;
10406         else if (type == I40E_VSI_SRIOV)
10407                 vsi->vf_id = param1;
10408         /* assign it some queues */
10409         alloc_queue_pairs = vsi->alloc_queue_pairs *
10410                             (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
10411
10412         ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
10413         if (ret < 0) {
10414                 dev_info(&pf->pdev->dev,
10415                          "failed to get tracking for %d queues for VSI %d err=%d\n",
10416                          alloc_queue_pairs, vsi->seid, ret);
10417                 goto err_vsi;
10418         }
10419         vsi->base_queue = ret;
10420
10421         /* get a VSI from the hardware */
10422         vsi->uplink_seid = uplink_seid;
10423         ret = i40e_add_vsi(vsi);
10424         if (ret)
10425                 goto err_vsi;
10426
10427         switch (vsi->type) {
10428         /* setup the netdev if needed */
10429         case I40E_VSI_MAIN:
10430         case I40E_VSI_VMDQ2:
10431                 ret = i40e_config_netdev(vsi);
10432                 if (ret)
10433                         goto err_netdev;
10434                 ret = register_netdev(vsi->netdev);
10435                 if (ret)
10436                         goto err_netdev;
10437                 vsi->netdev_registered = true;
10438                 netif_carrier_off(vsi->netdev);
10439 #ifdef CONFIG_I40E_DCB
10440                 /* Setup DCB netlink interface */
10441                 i40e_dcbnl_setup(vsi);
10442 #endif /* CONFIG_I40E_DCB */
10443                 /* fall through */
10444
10445         case I40E_VSI_FDIR:
10446                 /* set up vectors and rings if needed */
10447                 ret = i40e_vsi_setup_vectors(vsi);
10448                 if (ret)
10449                         goto err_msix;
10450
10451                 ret = i40e_alloc_rings(vsi);
10452                 if (ret)
10453                         goto err_rings;
10454
10455                 /* map all of the rings to the q_vectors */
10456                 i40e_vsi_map_rings_to_vectors(vsi);
10457
10458                 i40e_vsi_reset_stats(vsi);
10459                 break;
10460
10461         default:
10462                 /* no netdev or rings for the other VSI types */
10463                 break;
10464         }
10465
10466         if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
10467             (vsi->type == I40E_VSI_VMDQ2)) {
10468                 ret = i40e_vsi_config_rss(vsi);
10469         }
10470         return vsi;
10471
10472 err_rings:
10473         i40e_vsi_free_q_vectors(vsi);
10474 err_msix:
10475         if (vsi->netdev_registered) {
10476                 vsi->netdev_registered = false;
10477                 unregister_netdev(vsi->netdev);
10478                 free_netdev(vsi->netdev);
10479                 vsi->netdev = NULL;
10480         }
10481 err_netdev:
10482         i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
10483 err_vsi:
10484         i40e_vsi_clear(vsi);
10485 err_alloc:
10486         return NULL;
10487 }
10488
10489 /**
10490  * i40e_veb_get_bw_info - Query VEB BW information
10491  * @veb: the veb to query
10492  *
10493  * Query the Tx scheduler BW configuration data for given VEB
10494  **/
10495 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
10496 {
10497         struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
10498         struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
10499         struct i40e_pf *pf = veb->pf;
10500         struct i40e_hw *hw = &pf->hw;
10501         u32 tc_bw_max;
10502         int ret = 0;
10503         int i;
10504
10505         ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
10506                                                   &bw_data, NULL);
10507         if (ret) {
10508                 dev_info(&pf->pdev->dev,
10509                          "query veb bw config failed, err %s aq_err %s\n",
10510                          i40e_stat_str(&pf->hw, ret),
10511                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
10512                 goto out;
10513         }
10514
10515         ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
10516                                                    &ets_data, NULL);
10517         if (ret) {
10518                 dev_info(&pf->pdev->dev,
10519                          "query veb bw ets config failed, err %s aq_err %s\n",
10520                          i40e_stat_str(&pf->hw, ret),
10521                          i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
10522                 goto out;
10523         }
10524
10525         veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
10526         veb->bw_max_quanta = ets_data.tc_bw_max;
10527         veb->is_abs_credits = bw_data.absolute_credits_enable;
10528         veb->enabled_tc = ets_data.tc_valid_bits;
10529         tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
10530                     (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
10531         for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
10532                 veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
10533                 veb->bw_tc_limit_credits[i] =
10534                                         le16_to_cpu(bw_data.tc_bw_limits[i]);
10535                 veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
10536         }
10537
10538 out:
10539         return ret;
10540 }
10541
10542 /**
10543  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
10544  * @pf: board private structure
10545  *
10546  * On error: returns error code (negative)
10547  * On success: returns vsi index in PF (positive)
10548  **/
10549 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
10550 {
10551         int ret = -ENOENT;
10552         struct i40e_veb *veb;
10553         int i;
10554
10555         /* Need to protect the allocation of switch elements at the PF level */
10556         mutex_lock(&pf->switch_mutex);
10557
10558         /* VEB list may be fragmented if VEB creation/destruction has
10559          * been happening.  We can afford to do a quick scan to look
10560          * for any free slots in the list.
10561          *
10562          * find next empty veb slot, looping back around if necessary
10563          */
10564         i = 0;
10565         while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
10566                 i++;
10567         if (i >= I40E_MAX_VEB) {
10568                 ret = -ENOMEM;
10569                 goto err_alloc_veb;  /* out of VEB slots! */
10570         }
10571
10572         veb = kzalloc(sizeof(*veb), GFP_KERNEL);
10573         if (!veb) {
10574                 ret = -ENOMEM;
10575                 goto err_alloc_veb;
10576         }
10577         veb->pf = pf;
10578         veb->idx = i;
10579         veb->enabled_tc = 1;
10580
10581         pf->veb[i] = veb;
10582         ret = i;
10583 err_alloc_veb:
10584         mutex_unlock(&pf->switch_mutex);
10585         return ret;
10586 }
10587
10588 /**
10589  * i40e_switch_branch_release - Delete a branch of the switch tree
10590  * @branch: where to start deleting
10591  *
10592  * This uses recursion to find the tips of the branch to be
10593  * removed, deleting until we get back to and can delete this VEB.
10594  **/
10595 static void i40e_switch_branch_release(struct i40e_veb *branch)
10596 {
10597         struct i40e_pf *pf = branch->pf;
10598         u16 branch_seid = branch->seid;
10599         u16 veb_idx = branch->idx;
10600         int i;
10601
10602         /* release any VEBs on this VEB - RECURSION */
10603         for (i = 0; i < I40E_MAX_VEB; i++) {
10604                 if (!pf->veb[i])
10605                         continue;
10606                 if (pf->veb[i]->uplink_seid == branch->seid)
10607                         i40e_switch_branch_release(pf->veb[i]);
10608         }
10609
10610         /* Release the VSIs on this VEB, but not the owner VSI.
10611          *
10612          * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
10613          *       the VEB itself, so don't use (*branch) after this loop.
10614          */
10615         for (i = 0; i < pf->num_alloc_vsi; i++) {
10616                 if (!pf->vsi[i])
10617                         continue;
10618                 if (pf->vsi[i]->uplink_seid == branch_seid &&
10619                    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
10620                         i40e_vsi_release(pf->vsi[i]);
10621                 }
10622         }
10623
10624         /* There's one corner case where the VEB might not have been
10625          * removed, so double check it here and remove it if needed.
10626          * This case happens if the veb was created from the debugfs
10627          * commands and no VSIs were added to it.
10628          */
10629         if (pf->veb[veb_idx])
10630                 i40e_veb_release(pf->veb[veb_idx]);
10631 }
10632
10633 /**
10634  * i40e_veb_clear - remove veb struct
10635  * @veb: the veb to remove
10636  **/
10637 static void i40e_veb_clear(struct i40e_veb *veb)
10638 {
10639         if (!veb)
10640                 return;
10641
10642         if (veb->pf) {
10643                 struct i40e_pf *pf = veb->pf;
10644
10645                 mutex_lock(&pf->switch_mutex);
10646                 if (pf->veb[veb->idx] == veb)
10647                         pf->veb[veb->idx] = NULL;
10648                 mutex_unlock(&pf->switch_mutex);
10649         }
10650
10651         kfree(veb);
10652 }
10653
10654 /**
10655  * i40e_veb_release - Delete a VEB and free its resources
10656  * @veb: the VEB being removed
10657  **/
10658 void i40e_veb_release(struct i40e_veb *veb)
10659 {
10660         struct i40e_vsi *vsi = NULL;
10661         struct i40e_pf *pf;
10662         int i, n = 0;
10663
10664         pf = veb->pf;
10665
10666         /* find the remaining VSI and check for extras */
10667         for (i = 0; i < pf->num_alloc_vsi; i++) {
10668                 if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
10669                         n++;
10670                         vsi = pf->vsi[i];
10671                 }
10672         }
10673         if (n != 1) {
10674                 dev_info(&pf->pdev->dev,
10675                          "can't remove VEB %d with %d VSIs left\n",
10676                          veb->seid, n);
10677                 return;
10678         }
10679
10680         /* move the remaining VSI to uplink veb */
10681         vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
10682         if (veb->uplink_seid) {
10683                 vsi->uplink_seid = veb->uplink_seid;
10684                 if (veb->uplink_seid == pf->mac_seid)
10685                         vsi->veb_idx = I40E_NO_VEB;
10686                 else
10687                         vsi->veb_idx = veb->veb_idx;
10688         } else {
10689                 /* floating VEB */
10690                 vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
10691                 vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
10692         }
10693
10694         i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
10695         i40e_veb_clear(veb);
10696 }
10697
10698 /**
10699  * i40e_add_veb - create the VEB in the switch
10700  * @veb: the VEB to be instantiated
10701  * @vsi: the controlling VSI
10702  **/
10703 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
10704 {
10705         struct i40e_pf *pf = veb->pf;
10706         bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
10707         int ret;
10708
10709         ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
10710                               veb->enabled_tc, false,
10711                               &veb->seid, enable_stats, NULL);
10712
10713         /* get a VEB from the hardware */
10714         if (ret) {
10715                 dev_info(&pf->pdev->dev,
10716                          "couldn't add VEB, err %s aq_err %s\n",
10717                          i40e_stat_str(&pf->hw, ret),
10718                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10719                 return -EPERM;
10720         }
10721
10722         /* get statistics counter */
10723         ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
10724                                          &veb->stats_idx, NULL, NULL, NULL);
10725         if (ret) {
10726                 dev_info(&pf->pdev->dev,
10727                          "couldn't get VEB statistics idx, err %s aq_err %s\n",
10728                          i40e_stat_str(&pf->hw, ret),
10729                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10730                 return -EPERM;
10731         }
10732         ret = i40e_veb_get_bw_info(veb);
10733         if (ret) {
10734                 dev_info(&pf->pdev->dev,
10735                          "couldn't get VEB bw info, err %s aq_err %s\n",
10736                          i40e_stat_str(&pf->hw, ret),
10737                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10738                 i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
10739                 return -ENOENT;
10740         }
10741
10742         vsi->uplink_seid = veb->seid;
10743         vsi->veb_idx = veb->idx;
10744         vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
10745
10746         return 0;
10747 }
10748
10749 /**
10750  * i40e_veb_setup - Set up a VEB
10751  * @pf: board private structure
10752  * @flags: VEB setup flags
10753  * @uplink_seid: the switch element to link to
10754  * @vsi_seid: the initial VSI seid
10755  * @enabled_tc: Enabled TC bit-map
10756  *
10757  * This allocates the sw VEB structure and links it into the switch
10758  * It is possible and legal for this to be a duplicate of an already
10759  * existing VEB.  It is also possible for both uplink and vsi seids
10760  * to be zero, in order to create a floating VEB.
10761  *
10762  * Returns pointer to the successfully allocated VEB sw struct on
10763  * success, otherwise returns NULL on failure.
10764  **/
10765 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
10766                                 u16 uplink_seid, u16 vsi_seid,
10767                                 u8 enabled_tc)
10768 {
10769         struct i40e_veb *veb, *uplink_veb = NULL;
10770         int vsi_idx, veb_idx;
10771         int ret;
10772
10773         /* if one seid is 0, the other must be 0 to create a floating relay */
10774         if ((uplink_seid == 0 || vsi_seid == 0) &&
10775             (uplink_seid + vsi_seid != 0)) {
10776                 dev_info(&pf->pdev->dev,
10777                          "one, not both seid's are 0: uplink=%d vsi=%d\n",
10778                          uplink_seid, vsi_seid);
10779                 return NULL;
10780         }
10781
10782         /* make sure there is such a vsi and uplink */
10783         for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
10784                 if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
10785                         break;
10786         if (vsi_idx >= pf->num_alloc_vsi && vsi_seid != 0) {
10787                 dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
10788                          vsi_seid);
10789                 return NULL;
10790         }
10791
10792         if (uplink_seid && uplink_seid != pf->mac_seid) {
10793                 for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
10794                         if (pf->veb[veb_idx] &&
10795                             pf->veb[veb_idx]->seid == uplink_seid) {
10796                                 uplink_veb = pf->veb[veb_idx];
10797                                 break;
10798                         }
10799                 }
10800                 if (!uplink_veb) {
10801                         dev_info(&pf->pdev->dev,
10802                                  "uplink seid %d not found\n", uplink_seid);
10803                         return NULL;
10804                 }
10805         }
10806
10807         /* get veb sw struct */
10808         veb_idx = i40e_veb_mem_alloc(pf);
10809         if (veb_idx < 0)
10810                 goto err_alloc;
10811         veb = pf->veb[veb_idx];
10812         veb->flags = flags;
10813         veb->uplink_seid = uplink_seid;
10814         veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
10815         veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
10816
10817         /* create the VEB in the switch */
10818         ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
10819         if (ret)
10820                 goto err_veb;
10821         if (vsi_idx == pf->lan_vsi)
10822                 pf->lan_veb = veb->idx;
10823
10824         return veb;
10825
10826 err_veb:
10827         i40e_veb_clear(veb);
10828 err_alloc:
10829         return NULL;
10830 }
10831
10832 /**
10833  * i40e_setup_pf_switch_element - set PF vars based on switch type
10834  * @pf: board private structure
10835  * @ele: element we are building info from
10836  * @num_reported: total number of elements
10837  * @printconfig: should we print the contents
10838  *
10839  * helper function to assist in extracting a few useful SEID values.
10840  **/
10841 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
10842                                 struct i40e_aqc_switch_config_element_resp *ele,
10843                                 u16 num_reported, bool printconfig)
10844 {
10845         u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
10846         u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
10847         u8 element_type = ele->element_type;
10848         u16 seid = le16_to_cpu(ele->seid);
10849
10850         if (printconfig)
10851                 dev_info(&pf->pdev->dev,
10852                          "type=%d seid=%d uplink=%d downlink=%d\n",
10853                          element_type, seid, uplink_seid, downlink_seid);
10854
10855         switch (element_type) {
10856         case I40E_SWITCH_ELEMENT_TYPE_MAC:
10857                 pf->mac_seid = seid;
10858                 break;
10859         case I40E_SWITCH_ELEMENT_TYPE_VEB:
10860                 /* Main VEB? */
10861                 if (uplink_seid != pf->mac_seid)
10862                         break;
10863                 if (pf->lan_veb == I40E_NO_VEB) {
10864                         int v;
10865
10866                         /* find existing or else empty VEB */
10867                         for (v = 0; v < I40E_MAX_VEB; v++) {
10868                                 if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
10869                                         pf->lan_veb = v;
10870                                         break;
10871                                 }
10872                         }
10873                         if (pf->lan_veb == I40E_NO_VEB) {
10874                                 v = i40e_veb_mem_alloc(pf);
10875                                 if (v < 0)
10876                                         break;
10877                                 pf->lan_veb = v;
10878                         }
10879                 }
10880
10881                 pf->veb[pf->lan_veb]->seid = seid;
10882                 pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
10883                 pf->veb[pf->lan_veb]->pf = pf;
10884                 pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
10885                 break;
10886         case I40E_SWITCH_ELEMENT_TYPE_VSI:
10887                 if (num_reported != 1)
10888                         break;
10889                 /* This is immediately after a reset so we can assume this is
10890                  * the PF's VSI
10891                  */
10892                 pf->mac_seid = uplink_seid;
10893                 pf->pf_seid = downlink_seid;
10894                 pf->main_vsi_seid = seid;
10895                 if (printconfig)
10896                         dev_info(&pf->pdev->dev,
10897                                  "pf_seid=%d main_vsi_seid=%d\n",
10898                                  pf->pf_seid, pf->main_vsi_seid);
10899                 break;
10900         case I40E_SWITCH_ELEMENT_TYPE_PF:
10901         case I40E_SWITCH_ELEMENT_TYPE_VF:
10902         case I40E_SWITCH_ELEMENT_TYPE_EMP:
10903         case I40E_SWITCH_ELEMENT_TYPE_BMC:
10904         case I40E_SWITCH_ELEMENT_TYPE_PE:
10905         case I40E_SWITCH_ELEMENT_TYPE_PA:
10906                 /* ignore these for now */
10907                 break;
10908         default:
10909                 dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
10910                          element_type, seid);
10911                 break;
10912         }
10913 }
10914
10915 /**
10916  * i40e_fetch_switch_configuration - Get switch config from firmware
10917  * @pf: board private structure
10918  * @printconfig: should we print the contents
10919  *
10920  * Get the current switch configuration from the device and
10921  * extract a few useful SEID values.
10922  **/
10923 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
10924 {
10925         struct i40e_aqc_get_switch_config_resp *sw_config;
10926         u16 next_seid = 0;
10927         int ret = 0;
10928         u8 *aq_buf;
10929         int i;
10930
10931         aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
10932         if (!aq_buf)
10933                 return -ENOMEM;
10934
10935         sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
10936         do {
10937                 u16 num_reported, num_total;
10938
10939                 ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
10940                                                 I40E_AQ_LARGE_BUF,
10941                                                 &next_seid, NULL);
10942                 if (ret) {
10943                         dev_info(&pf->pdev->dev,
10944                                  "get switch config failed err %s aq_err %s\n",
10945                                  i40e_stat_str(&pf->hw, ret),
10946                                  i40e_aq_str(&pf->hw,
10947                                              pf->hw.aq.asq_last_status));
10948                         kfree(aq_buf);
10949                         return -ENOENT;
10950                 }
10951
10952                 num_reported = le16_to_cpu(sw_config->header.num_reported);
10953                 num_total = le16_to_cpu(sw_config->header.num_total);
10954
10955                 if (printconfig)
10956                         dev_info(&pf->pdev->dev,
10957                                  "header: %d reported %d total\n",
10958                                  num_reported, num_total);
10959
10960                 for (i = 0; i < num_reported; i++) {
10961                         struct i40e_aqc_switch_config_element_resp *ele =
10962                                 &sw_config->element[i];
10963
10964                         i40e_setup_pf_switch_element(pf, ele, num_reported,
10965                                                      printconfig);
10966                 }
10967         } while (next_seid != 0);
10968
10969         kfree(aq_buf);
10970         return ret;
10971 }
10972
10973 /**
10974  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
10975  * @pf: board private structure
10976  * @reinit: if the Main VSI needs to re-initialized.
10977  *
10978  * Returns 0 on success, negative value on failure
10979  **/
10980 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit)
10981 {
10982         u16 flags = 0;
10983         int ret;
10984
10985         /* find out what's out there already */
10986         ret = i40e_fetch_switch_configuration(pf, false);
10987         if (ret) {
10988                 dev_info(&pf->pdev->dev,
10989                          "couldn't fetch switch config, err %s aq_err %s\n",
10990                          i40e_stat_str(&pf->hw, ret),
10991                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10992                 return ret;
10993         }
10994         i40e_pf_reset_stats(pf);
10995
10996         /* set the switch config bit for the whole device to
10997          * support limited promisc or true promisc
10998          * when user requests promisc. The default is limited
10999          * promisc.
11000         */
11001
11002         if ((pf->hw.pf_id == 0) &&
11003             !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT))
11004                 flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
11005
11006         if (pf->hw.pf_id == 0) {
11007                 u16 valid_flags;
11008
11009                 valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
11010                 ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags,
11011                                                 NULL);
11012                 if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
11013                         dev_info(&pf->pdev->dev,
11014                                  "couldn't set switch config bits, err %s aq_err %s\n",
11015                                  i40e_stat_str(&pf->hw, ret),
11016                                  i40e_aq_str(&pf->hw,
11017                                              pf->hw.aq.asq_last_status));
11018                         /* not a fatal problem, just keep going */
11019                 }
11020         }
11021
11022         /* first time setup */
11023         if (pf->lan_vsi == I40E_NO_VSI || reinit) {
11024                 struct i40e_vsi *vsi = NULL;
11025                 u16 uplink_seid;
11026
11027                 /* Set up the PF VSI associated with the PF's main VSI
11028                  * that is already in the HW switch
11029                  */
11030                 if (pf->lan_veb != I40E_NO_VEB && pf->veb[pf->lan_veb])
11031                         uplink_seid = pf->veb[pf->lan_veb]->seid;
11032                 else
11033                         uplink_seid = pf->mac_seid;
11034                 if (pf->lan_vsi == I40E_NO_VSI)
11035                         vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
11036                 else if (reinit)
11037                         vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
11038                 if (!vsi) {
11039                         dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
11040                         i40e_fdir_teardown(pf);
11041                         return -EAGAIN;
11042                 }
11043         } else {
11044                 /* force a reset of TC and queue layout configurations */
11045                 u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
11046
11047                 pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
11048                 pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
11049                 i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
11050         }
11051         i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
11052
11053         i40e_fdir_sb_setup(pf);
11054
11055         /* Setup static PF queue filter control settings */
11056         ret = i40e_setup_pf_filter_control(pf);
11057         if (ret) {
11058                 dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
11059                          ret);
11060                 /* Failure here should not stop continuing other steps */
11061         }
11062
11063         /* enable RSS in the HW, even for only one queue, as the stack can use
11064          * the hash
11065          */
11066         if ((pf->flags & I40E_FLAG_RSS_ENABLED))
11067                 i40e_pf_config_rss(pf);
11068
11069         /* fill in link information and enable LSE reporting */
11070         i40e_link_event(pf);
11071
11072         /* Initialize user-specific link properties */
11073         pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
11074                                   I40E_AQ_AN_COMPLETED) ? true : false);
11075
11076         i40e_ptp_init(pf);
11077
11078         /* repopulate tunnel port filters */
11079         i40e_sync_udp_filters(pf);
11080
11081         return ret;
11082 }
11083
11084 /**
11085  * i40e_determine_queue_usage - Work out queue distribution
11086  * @pf: board private structure
11087  **/
11088 static void i40e_determine_queue_usage(struct i40e_pf *pf)
11089 {
11090         int queues_left;
11091
11092         pf->num_lan_qps = 0;
11093
11094         /* Find the max queues to be put into basic use.  We'll always be
11095          * using TC0, whether or not DCB is running, and TC0 will get the
11096          * big RSS set.
11097          */
11098         queues_left = pf->hw.func_caps.num_tx_qp;
11099
11100         if ((queues_left == 1) ||
11101             !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
11102                 /* one qp for PF, no queues for anything else */
11103                 queues_left = 0;
11104                 pf->alloc_rss_size = pf->num_lan_qps = 1;
11105
11106                 /* make sure all the fancies are disabled */
11107                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
11108                                I40E_FLAG_IWARP_ENABLED  |
11109                                I40E_FLAG_FD_SB_ENABLED  |
11110                                I40E_FLAG_FD_ATR_ENABLED |
11111                                I40E_FLAG_DCB_CAPABLE    |
11112                                I40E_FLAG_DCB_ENABLED    |
11113                                I40E_FLAG_SRIOV_ENABLED  |
11114                                I40E_FLAG_VMDQ_ENABLED);
11115         } else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
11116                                   I40E_FLAG_FD_SB_ENABLED |
11117                                   I40E_FLAG_FD_ATR_ENABLED |
11118                                   I40E_FLAG_DCB_CAPABLE))) {
11119                 /* one qp for PF */
11120                 pf->alloc_rss_size = pf->num_lan_qps = 1;
11121                 queues_left -= pf->num_lan_qps;
11122
11123                 pf->flags &= ~(I40E_FLAG_RSS_ENABLED    |
11124                                I40E_FLAG_IWARP_ENABLED  |
11125                                I40E_FLAG_FD_SB_ENABLED  |
11126                                I40E_FLAG_FD_ATR_ENABLED |
11127                                I40E_FLAG_DCB_ENABLED    |
11128                                I40E_FLAG_VMDQ_ENABLED);
11129         } else {
11130                 /* Not enough queues for all TCs */
11131                 if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
11132                     (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
11133                         pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
11134                                         I40E_FLAG_DCB_ENABLED);
11135                         dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
11136                 }
11137                 pf->num_lan_qps = max_t(int, pf->rss_size_max,
11138                                         num_online_cpus());
11139                 pf->num_lan_qps = min_t(int, pf->num_lan_qps,
11140                                         pf->hw.func_caps.num_tx_qp);
11141
11142                 queues_left -= pf->num_lan_qps;
11143         }
11144
11145         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11146                 if (queues_left > 1) {
11147                         queues_left -= 1; /* save 1 queue for FD */
11148                 } else {
11149                         pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11150                         dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
11151                 }
11152         }
11153
11154         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
11155             pf->num_vf_qps && pf->num_req_vfs && queues_left) {
11156                 pf->num_req_vfs = min_t(int, pf->num_req_vfs,
11157                                         (queues_left / pf->num_vf_qps));
11158                 queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
11159         }
11160
11161         if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11162             pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
11163                 pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
11164                                           (queues_left / pf->num_vmdq_qps));
11165                 queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
11166         }
11167
11168         pf->queues_left = queues_left;
11169         dev_dbg(&pf->pdev->dev,
11170                 "qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
11171                 pf->hw.func_caps.num_tx_qp,
11172                 !!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
11173                 pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
11174                 pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
11175                 queues_left);
11176 }
11177
11178 /**
11179  * i40e_setup_pf_filter_control - Setup PF static filter control
11180  * @pf: PF to be setup
11181  *
11182  * i40e_setup_pf_filter_control sets up a PF's initial filter control
11183  * settings. If PE/FCoE are enabled then it will also set the per PF
11184  * based filter sizes required for them. It also enables Flow director,
11185  * ethertype and macvlan type filter settings for the pf.
11186  *
11187  * Returns 0 on success, negative on failure
11188  **/
11189 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
11190 {
11191         struct i40e_filter_control_settings *settings = &pf->filter_settings;
11192
11193         settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
11194
11195         /* Flow Director is enabled */
11196         if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
11197                 settings->enable_fdir = true;
11198
11199         /* Ethtype and MACVLAN filters enabled for PF */
11200         settings->enable_ethtype = true;
11201         settings->enable_macvlan = true;
11202
11203         if (i40e_set_filter_control(&pf->hw, settings))
11204                 return -ENOENT;
11205
11206         return 0;
11207 }
11208
11209 #define INFO_STRING_LEN 255
11210 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
11211 static void i40e_print_features(struct i40e_pf *pf)
11212 {
11213         struct i40e_hw *hw = &pf->hw;
11214         char *buf;
11215         int i;
11216
11217         buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
11218         if (!buf)
11219                 return;
11220
11221         i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
11222 #ifdef CONFIG_PCI_IOV
11223         i += snprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
11224 #endif
11225         i += snprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
11226                       pf->hw.func_caps.num_vsis,
11227                       pf->vsi[pf->lan_vsi]->num_queue_pairs);
11228         if (pf->flags & I40E_FLAG_RSS_ENABLED)
11229                 i += snprintf(&buf[i], REMAIN(i), " RSS");
11230         if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
11231                 i += snprintf(&buf[i], REMAIN(i), " FD_ATR");
11232         if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11233                 i += snprintf(&buf[i], REMAIN(i), " FD_SB");
11234                 i += snprintf(&buf[i], REMAIN(i), " NTUPLE");
11235         }
11236         if (pf->flags & I40E_FLAG_DCB_CAPABLE)
11237                 i += snprintf(&buf[i], REMAIN(i), " DCB");
11238         i += snprintf(&buf[i], REMAIN(i), " VxLAN");
11239         i += snprintf(&buf[i], REMAIN(i), " Geneve");
11240         if (pf->flags & I40E_FLAG_PTP)
11241                 i += snprintf(&buf[i], REMAIN(i), " PTP");
11242         if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
11243                 i += snprintf(&buf[i], REMAIN(i), " VEB");
11244         else
11245                 i += snprintf(&buf[i], REMAIN(i), " VEPA");
11246
11247         dev_info(&pf->pdev->dev, "%s\n", buf);
11248         kfree(buf);
11249         WARN_ON(i > INFO_STRING_LEN);
11250 }
11251
11252 /**
11253  * i40e_get_platform_mac_addr - get platform-specific MAC address
11254  * @pdev: PCI device information struct
11255  * @pf: board private structure
11256  *
11257  * Look up the MAC address for the device. First we'll try
11258  * eth_platform_get_mac_address, which will check Open Firmware, or arch
11259  * specific fallback. Otherwise, we'll default to the stored value in
11260  * firmware.
11261  **/
11262 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
11263 {
11264         if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
11265                 i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
11266 }
11267
11268 /**
11269  * i40e_probe - Device initialization routine
11270  * @pdev: PCI device information struct
11271  * @ent: entry in i40e_pci_tbl
11272  *
11273  * i40e_probe initializes a PF identified by a pci_dev structure.
11274  * The OS initialization, configuring of the PF private structure,
11275  * and a hardware reset occur.
11276  *
11277  * Returns 0 on success, negative on failure
11278  **/
11279 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
11280 {
11281         struct i40e_aq_get_phy_abilities_resp abilities;
11282         struct i40e_pf *pf;
11283         struct i40e_hw *hw;
11284         static u16 pfs_found;
11285         u16 wol_nvm_bits;
11286         u16 link_status;
11287         int err;
11288         u32 val;
11289         u32 i;
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         /* if FDIR VSI was set up, start it now */
11559         for (i = 0; i < pf->num_alloc_vsi; i++) {
11560                 if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
11561                         i40e_vsi_open(pf->vsi[i]);
11562                         break;
11563                 }
11564         }
11565
11566         /* The driver only wants link up/down and module qualification
11567          * reports from firmware.  Note the negative logic.
11568          */
11569         err = i40e_aq_set_phy_int_mask(&pf->hw,
11570                                        ~(I40E_AQ_EVENT_LINK_UPDOWN |
11571                                          I40E_AQ_EVENT_MEDIA_NA |
11572                                          I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
11573         if (err)
11574                 dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
11575                          i40e_stat_str(&pf->hw, err),
11576                          i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11577
11578         /* Reconfigure hardware for allowing smaller MSS in the case
11579          * of TSO, so that we avoid the MDD being fired and causing
11580          * a reset in the case of small MSS+TSO.
11581          */
11582         val = rd32(hw, I40E_REG_MSS);
11583         if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
11584                 val &= ~I40E_REG_MSS_MIN_MASK;
11585                 val |= I40E_64BYTE_MSS;
11586                 wr32(hw, I40E_REG_MSS, val);
11587         }
11588
11589         if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
11590                 msleep(75);
11591                 err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
11592                 if (err)
11593                         dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
11594                                  i40e_stat_str(&pf->hw, err),
11595                                  i40e_aq_str(&pf->hw,
11596                                              pf->hw.aq.asq_last_status));
11597         }
11598         /* The main driver is (mostly) up and happy. We need to set this state
11599          * before setting up the misc vector or we get a race and the vector
11600          * ends up disabled forever.
11601          */
11602         clear_bit(__I40E_DOWN, pf->state);
11603
11604         /* In case of MSIX we are going to setup the misc vector right here
11605          * to handle admin queue events etc. In case of legacy and MSI
11606          * the misc functionality and queue processing is combined in
11607          * the same vector and that gets setup at open.
11608          */
11609         if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11610                 err = i40e_setup_misc_vector(pf);
11611                 if (err) {
11612                         dev_info(&pdev->dev,
11613                                  "setup of misc vector failed: %d\n", err);
11614                         goto err_vsis;
11615                 }
11616         }
11617
11618 #ifdef CONFIG_PCI_IOV
11619         /* prep for VF support */
11620         if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
11621             (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11622             !test_bit(__I40E_BAD_EEPROM, pf->state)) {
11623                 /* disable link interrupts for VFs */
11624                 val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
11625                 val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
11626                 wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
11627                 i40e_flush(hw);
11628
11629                 if (pci_num_vf(pdev)) {
11630                         dev_info(&pdev->dev,
11631                                  "Active VFs found, allocating resources.\n");
11632                         err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
11633                         if (err)
11634                                 dev_info(&pdev->dev,
11635                                          "Error %d allocating resources for existing VFs\n",
11636                                          err);
11637                 }
11638         }
11639 #endif /* CONFIG_PCI_IOV */
11640
11641         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11642                 pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
11643                                                       pf->num_iwarp_msix,
11644                                                       I40E_IWARP_IRQ_PILE_ID);
11645                 if (pf->iwarp_base_vector < 0) {
11646                         dev_info(&pdev->dev,
11647                                  "failed to get tracking for %d vectors for IWARP err=%d\n",
11648                                  pf->num_iwarp_msix, pf->iwarp_base_vector);
11649                         pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11650                 }
11651         }
11652
11653         i40e_dbg_pf_init(pf);
11654
11655         /* tell the firmware that we're starting */
11656         i40e_send_version(pf);
11657
11658         /* since everything's happy, start the service_task timer */
11659         mod_timer(&pf->service_timer,
11660                   round_jiffies(jiffies + pf->service_timer_period));
11661
11662         /* add this PF to client device list and launch a client service task */
11663         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11664                 err = i40e_lan_add_device(pf);
11665                 if (err)
11666                         dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
11667                                  err);
11668         }
11669
11670 #define PCI_SPEED_SIZE 8
11671 #define PCI_WIDTH_SIZE 8
11672         /* Devices on the IOSF bus do not have this information
11673          * and will report PCI Gen 1 x 1 by default so don't bother
11674          * checking them.
11675          */
11676         if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
11677                 char speed[PCI_SPEED_SIZE] = "Unknown";
11678                 char width[PCI_WIDTH_SIZE] = "Unknown";
11679
11680                 /* Get the negotiated link width and speed from PCI config
11681                  * space
11682                  */
11683                 pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
11684                                           &link_status);
11685
11686                 i40e_set_pci_config_data(hw, link_status);
11687
11688                 switch (hw->bus.speed) {
11689                 case i40e_bus_speed_8000:
11690                         strncpy(speed, "8.0", PCI_SPEED_SIZE); break;
11691                 case i40e_bus_speed_5000:
11692                         strncpy(speed, "5.0", PCI_SPEED_SIZE); break;
11693                 case i40e_bus_speed_2500:
11694                         strncpy(speed, "2.5", PCI_SPEED_SIZE); break;
11695                 default:
11696                         break;
11697                 }
11698                 switch (hw->bus.width) {
11699                 case i40e_bus_width_pcie_x8:
11700                         strncpy(width, "8", PCI_WIDTH_SIZE); break;
11701                 case i40e_bus_width_pcie_x4:
11702                         strncpy(width, "4", PCI_WIDTH_SIZE); break;
11703                 case i40e_bus_width_pcie_x2:
11704                         strncpy(width, "2", PCI_WIDTH_SIZE); break;
11705                 case i40e_bus_width_pcie_x1:
11706                         strncpy(width, "1", PCI_WIDTH_SIZE); break;
11707                 default:
11708                         break;
11709                 }
11710
11711                 dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
11712                          speed, width);
11713
11714                 if (hw->bus.width < i40e_bus_width_pcie_x8 ||
11715                     hw->bus.speed < i40e_bus_speed_8000) {
11716                         dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
11717                         dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
11718                 }
11719         }
11720
11721         /* get the requested speeds from the fw */
11722         err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
11723         if (err)
11724                 dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
11725                         i40e_stat_str(&pf->hw, err),
11726                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11727         pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
11728
11729         /* get the supported phy types from the fw */
11730         err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
11731         if (err)
11732                 dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
11733                         i40e_stat_str(&pf->hw, err),
11734                         i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
11735
11736         /* Add a filter to drop all Flow control frames from any VSI from being
11737          * transmitted. By doing so we stop a malicious VF from sending out
11738          * PAUSE or PFC frames and potentially controlling traffic for other
11739          * PF/VF VSIs.
11740          * The FW can still send Flow control frames if enabled.
11741          */
11742         i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
11743                                                        pf->main_vsi_seid);
11744
11745         if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
11746                 (pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
11747                 pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
11748         if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
11749                 pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
11750         /* print a string summarizing features */
11751         i40e_print_features(pf);
11752
11753         return 0;
11754
11755         /* Unwind what we've done if something failed in the setup */
11756 err_vsis:
11757         set_bit(__I40E_DOWN, pf->state);
11758         i40e_clear_interrupt_scheme(pf);
11759         kfree(pf->vsi);
11760 err_switch_setup:
11761         i40e_reset_interrupt_capability(pf);
11762         del_timer_sync(&pf->service_timer);
11763 err_mac_addr:
11764 err_configure_lan_hmc:
11765         (void)i40e_shutdown_lan_hmc(hw);
11766 err_init_lan_hmc:
11767         kfree(pf->qp_pile);
11768 err_sw_init:
11769 err_adminq_setup:
11770 err_pf_reset:
11771         iounmap(hw->hw_addr);
11772 err_ioremap:
11773         kfree(pf);
11774 err_pf_alloc:
11775         pci_disable_pcie_error_reporting(pdev);
11776         pci_release_mem_regions(pdev);
11777 err_pci_reg:
11778 err_dma:
11779         pci_disable_device(pdev);
11780         return err;
11781 }
11782
11783 /**
11784  * i40e_remove - Device removal routine
11785  * @pdev: PCI device information struct
11786  *
11787  * i40e_remove is called by the PCI subsystem to alert the driver
11788  * that is should release a PCI device.  This could be caused by a
11789  * Hot-Plug event, or because the driver is going to be removed from
11790  * memory.
11791  **/
11792 static void i40e_remove(struct pci_dev *pdev)
11793 {
11794         struct i40e_pf *pf = pci_get_drvdata(pdev);
11795         struct i40e_hw *hw = &pf->hw;
11796         i40e_status ret_code;
11797         int i;
11798
11799         i40e_dbg_pf_exit(pf);
11800
11801         i40e_ptp_stop(pf);
11802
11803         /* Disable RSS in hw */
11804         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
11805         i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
11806
11807         while (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
11808                 usleep_range(1000, 2000);
11809
11810         /* no more scheduling of any task */
11811         set_bit(__I40E_SUSPENDED, pf->state);
11812         set_bit(__I40E_DOWN, pf->state);
11813         if (pf->service_timer.data)
11814                 del_timer_sync(&pf->service_timer);
11815         if (pf->service_task.func)
11816                 cancel_work_sync(&pf->service_task);
11817
11818         /* Client close must be called explicitly here because the timer
11819          * has been stopped.
11820          */
11821         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
11822
11823         if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
11824                 i40e_free_vfs(pf);
11825                 pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
11826         }
11827
11828         i40e_fdir_teardown(pf);
11829
11830         /* If there is a switch structure or any orphans, remove them.
11831          * This will leave only the PF's VSI remaining.
11832          */
11833         for (i = 0; i < I40E_MAX_VEB; i++) {
11834                 if (!pf->veb[i])
11835                         continue;
11836
11837                 if (pf->veb[i]->uplink_seid == pf->mac_seid ||
11838                     pf->veb[i]->uplink_seid == 0)
11839                         i40e_switch_branch_release(pf->veb[i]);
11840         }
11841
11842         /* Now we can shutdown the PF's VSI, just before we kill
11843          * adminq and hmc.
11844          */
11845         if (pf->vsi[pf->lan_vsi])
11846                 i40e_vsi_release(pf->vsi[pf->lan_vsi]);
11847
11848         /* remove attached clients */
11849         if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11850                 ret_code = i40e_lan_del_device(pf);
11851                 if (ret_code)
11852                         dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
11853                                  ret_code);
11854         }
11855
11856         /* shutdown and destroy the HMC */
11857         if (hw->hmc.hmc_obj) {
11858                 ret_code = i40e_shutdown_lan_hmc(hw);
11859                 if (ret_code)
11860                         dev_warn(&pdev->dev,
11861                                  "Failed to destroy the HMC resources: %d\n",
11862                                  ret_code);
11863         }
11864
11865         /* shutdown the adminq */
11866         i40e_shutdown_adminq(hw);
11867
11868         /* destroy the locks only once, here */
11869         mutex_destroy(&hw->aq.arq_mutex);
11870         mutex_destroy(&hw->aq.asq_mutex);
11871
11872         /* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
11873         rtnl_lock();
11874         i40e_clear_interrupt_scheme(pf);
11875         for (i = 0; i < pf->num_alloc_vsi; i++) {
11876                 if (pf->vsi[i]) {
11877                         i40e_vsi_clear_rings(pf->vsi[i]);
11878                         i40e_vsi_clear(pf->vsi[i]);
11879                         pf->vsi[i] = NULL;
11880                 }
11881         }
11882         rtnl_unlock();
11883
11884         for (i = 0; i < I40E_MAX_VEB; i++) {
11885                 kfree(pf->veb[i]);
11886                 pf->veb[i] = NULL;
11887         }
11888
11889         kfree(pf->qp_pile);
11890         kfree(pf->vsi);
11891
11892         iounmap(hw->hw_addr);
11893         kfree(pf);
11894         pci_release_mem_regions(pdev);
11895
11896         pci_disable_pcie_error_reporting(pdev);
11897         pci_disable_device(pdev);
11898 }
11899
11900 /**
11901  * i40e_pci_error_detected - warning that something funky happened in PCI land
11902  * @pdev: PCI device information struct
11903  *
11904  * Called to warn that something happened and the error handling steps
11905  * are in progress.  Allows the driver to quiesce things, be ready for
11906  * remediation.
11907  **/
11908 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
11909                                                 enum pci_channel_state error)
11910 {
11911         struct i40e_pf *pf = pci_get_drvdata(pdev);
11912
11913         dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
11914
11915         if (!pf) {
11916                 dev_info(&pdev->dev,
11917                          "Cannot recover - error happened during device probe\n");
11918                 return PCI_ERS_RESULT_DISCONNECT;
11919         }
11920
11921         /* shutdown all operations */
11922         if (!test_bit(__I40E_SUSPENDED, pf->state))
11923                 i40e_prep_for_reset(pf, false);
11924
11925         /* Request a slot reset */
11926         return PCI_ERS_RESULT_NEED_RESET;
11927 }
11928
11929 /**
11930  * i40e_pci_error_slot_reset - a PCI slot reset just happened
11931  * @pdev: PCI device information struct
11932  *
11933  * Called to find if the driver can work with the device now that
11934  * the pci slot has been reset.  If a basic connection seems good
11935  * (registers are readable and have sane content) then return a
11936  * happy little PCI_ERS_RESULT_xxx.
11937  **/
11938 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
11939 {
11940         struct i40e_pf *pf = pci_get_drvdata(pdev);
11941         pci_ers_result_t result;
11942         int err;
11943         u32 reg;
11944
11945         dev_dbg(&pdev->dev, "%s\n", __func__);
11946         if (pci_enable_device_mem(pdev)) {
11947                 dev_info(&pdev->dev,
11948                          "Cannot re-enable PCI device after reset.\n");
11949                 result = PCI_ERS_RESULT_DISCONNECT;
11950         } else {
11951                 pci_set_master(pdev);
11952                 pci_restore_state(pdev);
11953                 pci_save_state(pdev);
11954                 pci_wake_from_d3(pdev, false);
11955
11956                 reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
11957                 if (reg == 0)
11958                         result = PCI_ERS_RESULT_RECOVERED;
11959                 else
11960                         result = PCI_ERS_RESULT_DISCONNECT;
11961         }
11962
11963         err = pci_cleanup_aer_uncorrect_error_status(pdev);
11964         if (err) {
11965                 dev_info(&pdev->dev,
11966                          "pci_cleanup_aer_uncorrect_error_status failed 0x%0x\n",
11967                          err);
11968                 /* non-fatal, continue */
11969         }
11970
11971         return result;
11972 }
11973
11974 /**
11975  * i40e_pci_error_resume - restart operations after PCI error recovery
11976  * @pdev: PCI device information struct
11977  *
11978  * Called to allow the driver to bring things back up after PCI error
11979  * and/or reset recovery has finished.
11980  **/
11981 static void i40e_pci_error_resume(struct pci_dev *pdev)
11982 {
11983         struct i40e_pf *pf = pci_get_drvdata(pdev);
11984
11985         dev_dbg(&pdev->dev, "%s\n", __func__);
11986         if (test_bit(__I40E_SUSPENDED, pf->state))
11987                 return;
11988
11989         i40e_handle_reset_warning(pf, false);
11990 }
11991
11992 /**
11993  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
11994  * using the mac_address_write admin q function
11995  * @pf: pointer to i40e_pf struct
11996  **/
11997 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
11998 {
11999         struct i40e_hw *hw = &pf->hw;
12000         i40e_status ret;
12001         u8 mac_addr[6];
12002         u16 flags = 0;
12003
12004         /* Get current MAC address in case it's an LAA */
12005         if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
12006                 ether_addr_copy(mac_addr,
12007                                 pf->vsi[pf->lan_vsi]->netdev->dev_addr);
12008         } else {
12009                 dev_err(&pf->pdev->dev,
12010                         "Failed to retrieve MAC address; using default\n");
12011                 ether_addr_copy(mac_addr, hw->mac.addr);
12012         }
12013
12014         /* The FW expects the mac address write cmd to first be called with
12015          * one of these flags before calling it again with the multicast
12016          * enable flags.
12017          */
12018         flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
12019
12020         if (hw->func_caps.flex10_enable && hw->partition_id != 1)
12021                 flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
12022
12023         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
12024         if (ret) {
12025                 dev_err(&pf->pdev->dev,
12026                         "Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
12027                 return;
12028         }
12029
12030         flags = I40E_AQC_MC_MAG_EN
12031                         | I40E_AQC_WOL_PRESERVE_ON_PFR
12032                         | I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
12033         ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
12034         if (ret)
12035                 dev_err(&pf->pdev->dev,
12036                         "Failed to enable Multicast Magic Packet wake up\n");
12037 }
12038
12039 /**
12040  * i40e_shutdown - PCI callback for shutting down
12041  * @pdev: PCI device information struct
12042  **/
12043 static void i40e_shutdown(struct pci_dev *pdev)
12044 {
12045         struct i40e_pf *pf = pci_get_drvdata(pdev);
12046         struct i40e_hw *hw = &pf->hw;
12047
12048         set_bit(__I40E_SUSPENDED, pf->state);
12049         set_bit(__I40E_DOWN, pf->state);
12050         rtnl_lock();
12051         i40e_prep_for_reset(pf, true);
12052         rtnl_unlock();
12053
12054         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
12055         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
12056
12057         del_timer_sync(&pf->service_timer);
12058         cancel_work_sync(&pf->service_task);
12059         i40e_fdir_teardown(pf);
12060
12061         /* Client close must be called explicitly here because the timer
12062          * has been stopped.
12063          */
12064         i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
12065
12066         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
12067                 i40e_enable_mc_magic_wake(pf);
12068
12069         i40e_prep_for_reset(pf, false);
12070
12071         wr32(hw, I40E_PFPM_APM,
12072              (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
12073         wr32(hw, I40E_PFPM_WUFC,
12074              (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
12075
12076         /* Since we're going to destroy queues during the
12077          * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
12078          * whole section
12079          */
12080         rtnl_lock();
12081         i40e_clear_interrupt_scheme(pf);
12082         rtnl_unlock();
12083
12084         if (system_state == SYSTEM_POWER_OFF) {
12085                 pci_wake_from_d3(pdev, pf->wol_en);
12086                 pci_set_power_state(pdev, PCI_D3hot);
12087         }
12088 }
12089
12090 #ifdef CONFIG_PM
12091 /**
12092  * i40e_suspend - PCI callback for moving to D3
12093  * @pdev: PCI device information struct
12094  **/
12095 static int i40e_suspend(struct pci_dev *pdev, pm_message_t state)
12096 {
12097         struct i40e_pf *pf = pci_get_drvdata(pdev);
12098         struct i40e_hw *hw = &pf->hw;
12099         int retval = 0;
12100
12101         set_bit(__I40E_SUSPENDED, pf->state);
12102         set_bit(__I40E_DOWN, pf->state);
12103
12104         if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
12105                 i40e_enable_mc_magic_wake(pf);
12106
12107         i40e_prep_for_reset(pf, false);
12108
12109         wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
12110         wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
12111
12112         i40e_stop_misc_vector(pf);
12113         if (pf->msix_entries) {
12114                 synchronize_irq(pf->msix_entries[0].vector);
12115                 free_irq(pf->msix_entries[0].vector, pf);
12116         }
12117         retval = pci_save_state(pdev);
12118         if (retval)
12119                 return retval;
12120
12121         pci_wake_from_d3(pdev, pf->wol_en);
12122         pci_set_power_state(pdev, PCI_D3hot);
12123
12124         return retval;
12125 }
12126
12127 /**
12128  * i40e_resume - PCI callback for waking up from D3
12129  * @pdev: PCI device information struct
12130  **/
12131 static int i40e_resume(struct pci_dev *pdev)
12132 {
12133         struct i40e_pf *pf = pci_get_drvdata(pdev);
12134         u32 err;
12135
12136         pci_set_power_state(pdev, PCI_D0);
12137         pci_restore_state(pdev);
12138         /* pci_restore_state() clears dev->state_saves, so
12139          * call pci_save_state() again to restore it.
12140          */
12141         pci_save_state(pdev);
12142
12143         err = pci_enable_device_mem(pdev);
12144         if (err) {
12145                 dev_err(&pdev->dev, "Cannot enable PCI device from suspend\n");
12146                 return err;
12147         }
12148         pci_set_master(pdev);
12149
12150         /* no wakeup events while running */
12151         pci_wake_from_d3(pdev, false);
12152
12153         /* handling the reset will rebuild the device state */
12154         if (test_and_clear_bit(__I40E_SUSPENDED, pf->state)) {
12155                 clear_bit(__I40E_DOWN, pf->state);
12156                 if (pf->msix_entries) {
12157                         err = request_irq(pf->msix_entries[0].vector,
12158                                           i40e_intr, 0, pf->int_name, pf);
12159                         if (err) {
12160                                 dev_err(&pf->pdev->dev,
12161                                         "request_irq for %s failed: %d\n",
12162                                         pf->int_name, err);
12163                         }
12164                 }
12165                 i40e_reset_and_rebuild(pf, false, false);
12166         }
12167
12168         return 0;
12169 }
12170
12171 #endif
12172 static const struct pci_error_handlers i40e_err_handler = {
12173         .error_detected = i40e_pci_error_detected,
12174         .slot_reset = i40e_pci_error_slot_reset,
12175         .resume = i40e_pci_error_resume,
12176 };
12177
12178 static struct pci_driver i40e_driver = {
12179         .name     = i40e_driver_name,
12180         .id_table = i40e_pci_tbl,
12181         .probe    = i40e_probe,
12182         .remove   = i40e_remove,
12183 #ifdef CONFIG_PM
12184         .suspend  = i40e_suspend,
12185         .resume   = i40e_resume,
12186 #endif
12187         .shutdown = i40e_shutdown,
12188         .err_handler = &i40e_err_handler,
12189         .sriov_configure = i40e_pci_sriov_configure,
12190 };
12191
12192 /**
12193  * i40e_init_module - Driver registration routine
12194  *
12195  * i40e_init_module is the first routine called when the driver is
12196  * loaded. All it does is register with the PCI subsystem.
12197  **/
12198 static int __init i40e_init_module(void)
12199 {
12200         pr_info("%s: %s - version %s\n", i40e_driver_name,
12201                 i40e_driver_string, i40e_driver_version_str);
12202         pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
12203
12204         /* There is no need to throttle the number of active tasks because
12205          * each device limits its own task using a state bit for scheduling
12206          * the service task, and the device tasks do not interfere with each
12207          * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
12208          * since we need to be able to guarantee forward progress even under
12209          * memory pressure.
12210          */
12211         i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
12212         if (!i40e_wq) {
12213                 pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
12214                 return -ENOMEM;
12215         }
12216
12217         i40e_dbg_init();
12218         return pci_register_driver(&i40e_driver);
12219 }
12220 module_init(i40e_init_module);
12221
12222 /**
12223  * i40e_exit_module - Driver exit cleanup routine
12224  *
12225  * i40e_exit_module is called just before the driver is removed
12226  * from memory.
12227  **/
12228 static void __exit i40e_exit_module(void)
12229 {
12230         pci_unregister_driver(&i40e_driver);
12231         destroy_workqueue(i40e_wq);
12232         i40e_dbg_exit();
12233 }
12234 module_exit(i40e_exit_module);