xref: /openbmc/linux/drivers/net/ethernet/intel/i40e/i40e_main.c (revision 8bf3cbe32b180836720f735e6de5dee700052317)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright(c) 2013 - 2018 Intel Corporation. */
3 
4 #include <linux/etherdevice.h>
5 #include <linux/of_net.h>
6 #include <linux/pci.h>
7 #include <linux/bpf.h>
8 
9 /* Local includes */
10 #include "i40e.h"
11 #include "i40e_diag.h"
12 #include "i40e_xsk.h"
13 #include <net/udp_tunnel.h>
14 #include <net/xdp_sock.h>
15 /* All i40e tracepoints are defined by the include below, which
16  * must be included exactly once across the whole kernel with
17  * CREATE_TRACE_POINTS defined
18  */
19 #define CREATE_TRACE_POINTS
20 #include "i40e_trace.h"
21 
22 const char i40e_driver_name[] = "i40e";
23 static const char i40e_driver_string[] =
24 			"Intel(R) Ethernet Connection XL710 Network Driver";
25 
26 #define DRV_KERN "-k"
27 
28 #define DRV_VERSION_MAJOR 2
29 #define DRV_VERSION_MINOR 8
30 #define DRV_VERSION_BUILD 20
31 #define DRV_VERSION __stringify(DRV_VERSION_MAJOR) "." \
32 	     __stringify(DRV_VERSION_MINOR) "." \
33 	     __stringify(DRV_VERSION_BUILD)    DRV_KERN
34 const char i40e_driver_version_str[] = DRV_VERSION;
35 static const char i40e_copyright[] = "Copyright (c) 2013 - 2019 Intel Corporation.";
36 
37 /* a bit of forward declarations */
38 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi);
39 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired);
40 static int i40e_add_vsi(struct i40e_vsi *vsi);
41 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi);
42 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit);
43 static int i40e_setup_misc_vector(struct i40e_pf *pf);
44 static void i40e_determine_queue_usage(struct i40e_pf *pf);
45 static int i40e_setup_pf_filter_control(struct i40e_pf *pf);
46 static void i40e_prep_for_reset(struct i40e_pf *pf, bool lock_acquired);
47 static int i40e_reset(struct i40e_pf *pf);
48 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired);
49 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf);
50 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf);
51 static bool i40e_check_recovery_mode(struct i40e_pf *pf);
52 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw);
53 static void i40e_fdir_sb_setup(struct i40e_pf *pf);
54 static int i40e_veb_get_bw_info(struct i40e_veb *veb);
55 static int i40e_get_capabilities(struct i40e_pf *pf,
56 				 enum i40e_admin_queue_opc list_type);
57 
58 
59 /* i40e_pci_tbl - PCI Device ID Table
60  *
61  * Last entry must be all 0s
62  *
63  * { Vendor ID, Device ID, SubVendor ID, SubDevice ID,
64  *   Class, Class Mask, private data (not used) }
65  */
66 static const struct pci_device_id i40e_pci_tbl[] = {
67 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_XL710), 0},
68 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QEMU), 0},
69 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_B), 0},
70 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_C), 0},
71 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_A), 0},
72 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_B), 0},
73 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_C), 0},
74 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T), 0},
75 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T4), 0},
76 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_SFP), 0},
77 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_B), 0},
78 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_KX_X722), 0},
79 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_QSFP_X722), 0},
80 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_X722), 0},
81 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_1G_BASE_T_X722), 0},
82 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_10G_BASE_T_X722), 0},
83 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_SFP_I_X722), 0},
84 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2), 0},
85 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_20G_KR2_A), 0},
86 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_X710_N3000), 0},
87 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_XXV710_N3000), 0},
88 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_B), 0},
89 	{PCI_VDEVICE(INTEL, I40E_DEV_ID_25G_SFP28), 0},
90 	/* required last entry */
91 	{0, }
92 };
93 MODULE_DEVICE_TABLE(pci, i40e_pci_tbl);
94 
95 #define I40E_MAX_VF_COUNT 128
96 static int debug = -1;
97 module_param(debug, uint, 0);
98 MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all), Debug mask (0x8XXXXXXX)");
99 
100 MODULE_AUTHOR("Intel Corporation, <e1000-devel@lists.sourceforge.net>");
101 MODULE_DESCRIPTION("Intel(R) Ethernet Connection XL710 Network Driver");
102 MODULE_LICENSE("GPL v2");
103 MODULE_VERSION(DRV_VERSION);
104 
105 static struct workqueue_struct *i40e_wq;
106 
107 /**
108  * i40e_allocate_dma_mem_d - OS specific memory alloc for shared code
109  * @hw:   pointer to the HW structure
110  * @mem:  ptr to mem struct to fill out
111  * @size: size of memory requested
112  * @alignment: what to align the allocation to
113  **/
114 int i40e_allocate_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem,
115 			    u64 size, u32 alignment)
116 {
117 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
118 
119 	mem->size = ALIGN(size, alignment);
120 	mem->va = dma_alloc_coherent(&pf->pdev->dev, mem->size, &mem->pa,
121 				     GFP_KERNEL);
122 	if (!mem->va)
123 		return -ENOMEM;
124 
125 	return 0;
126 }
127 
128 /**
129  * i40e_free_dma_mem_d - OS specific memory free for shared code
130  * @hw:   pointer to the HW structure
131  * @mem:  ptr to mem struct to free
132  **/
133 int i40e_free_dma_mem_d(struct i40e_hw *hw, struct i40e_dma_mem *mem)
134 {
135 	struct i40e_pf *pf = (struct i40e_pf *)hw->back;
136 
137 	dma_free_coherent(&pf->pdev->dev, mem->size, mem->va, mem->pa);
138 	mem->va = NULL;
139 	mem->pa = 0;
140 	mem->size = 0;
141 
142 	return 0;
143 }
144 
145 /**
146  * i40e_allocate_virt_mem_d - OS specific memory alloc for shared code
147  * @hw:   pointer to the HW structure
148  * @mem:  ptr to mem struct to fill out
149  * @size: size of memory requested
150  **/
151 int i40e_allocate_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem,
152 			     u32 size)
153 {
154 	mem->size = size;
155 	mem->va = kzalloc(size, GFP_KERNEL);
156 
157 	if (!mem->va)
158 		return -ENOMEM;
159 
160 	return 0;
161 }
162 
163 /**
164  * i40e_free_virt_mem_d - OS specific memory free for shared code
165  * @hw:   pointer to the HW structure
166  * @mem:  ptr to mem struct to free
167  **/
168 int i40e_free_virt_mem_d(struct i40e_hw *hw, struct i40e_virt_mem *mem)
169 {
170 	/* it's ok to kfree a NULL pointer */
171 	kfree(mem->va);
172 	mem->va = NULL;
173 	mem->size = 0;
174 
175 	return 0;
176 }
177 
178 /**
179  * i40e_get_lump - find a lump of free generic resource
180  * @pf: board private structure
181  * @pile: the pile of resource to search
182  * @needed: the number of items needed
183  * @id: an owner id to stick on the items assigned
184  *
185  * Returns the base item index of the lump, or negative for error
186  *
187  * The search_hint trick and lack of advanced fit-finding only work
188  * because we're highly likely to have all the same size lump requests.
189  * Linear search time and any fragmentation should be minimal.
190  **/
191 static int i40e_get_lump(struct i40e_pf *pf, struct i40e_lump_tracking *pile,
192 			 u16 needed, u16 id)
193 {
194 	int ret = -ENOMEM;
195 	int i, j;
196 
197 	if (!pile || needed == 0 || id >= I40E_PILE_VALID_BIT) {
198 		dev_info(&pf->pdev->dev,
199 			 "param err: pile=%s needed=%d id=0x%04x\n",
200 			 pile ? "<valid>" : "<null>", needed, id);
201 		return -EINVAL;
202 	}
203 
204 	/* start the linear search with an imperfect hint */
205 	i = pile->search_hint;
206 	while (i < pile->num_entries) {
207 		/* skip already allocated entries */
208 		if (pile->list[i] & I40E_PILE_VALID_BIT) {
209 			i++;
210 			continue;
211 		}
212 
213 		/* do we have enough in this lump? */
214 		for (j = 0; (j < needed) && ((i+j) < pile->num_entries); j++) {
215 			if (pile->list[i+j] & I40E_PILE_VALID_BIT)
216 				break;
217 		}
218 
219 		if (j == needed) {
220 			/* there was enough, so assign it to the requestor */
221 			for (j = 0; j < needed; j++)
222 				pile->list[i+j] = id | I40E_PILE_VALID_BIT;
223 			ret = i;
224 			pile->search_hint = i + j;
225 			break;
226 		}
227 
228 		/* not enough, so skip over it and continue looking */
229 		i += j;
230 	}
231 
232 	return ret;
233 }
234 
235 /**
236  * i40e_put_lump - return a lump of generic resource
237  * @pile: the pile of resource to search
238  * @index: the base item index
239  * @id: the owner id of the items assigned
240  *
241  * Returns the count of items in the lump
242  **/
243 static int i40e_put_lump(struct i40e_lump_tracking *pile, u16 index, u16 id)
244 {
245 	int valid_id = (id | I40E_PILE_VALID_BIT);
246 	int count = 0;
247 	int i;
248 
249 	if (!pile || index >= pile->num_entries)
250 		return -EINVAL;
251 
252 	for (i = index;
253 	     i < pile->num_entries && pile->list[i] == valid_id;
254 	     i++) {
255 		pile->list[i] = 0;
256 		count++;
257 	}
258 
259 	if (count && index < pile->search_hint)
260 		pile->search_hint = index;
261 
262 	return count;
263 }
264 
265 /**
266  * i40e_find_vsi_from_id - searches for the vsi with the given id
267  * @pf: the pf structure to search for the vsi
268  * @id: id of the vsi it is searching for
269  **/
270 struct i40e_vsi *i40e_find_vsi_from_id(struct i40e_pf *pf, u16 id)
271 {
272 	int i;
273 
274 	for (i = 0; i < pf->num_alloc_vsi; i++)
275 		if (pf->vsi[i] && (pf->vsi[i]->id == id))
276 			return pf->vsi[i];
277 
278 	return NULL;
279 }
280 
281 /**
282  * i40e_service_event_schedule - Schedule the service task to wake up
283  * @pf: board private structure
284  *
285  * If not already scheduled, this puts the task into the work queue
286  **/
287 void i40e_service_event_schedule(struct i40e_pf *pf)
288 {
289 	if ((!test_bit(__I40E_DOWN, pf->state) &&
290 	     !test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state)) ||
291 	      test_bit(__I40E_RECOVERY_MODE, pf->state))
292 		queue_work(i40e_wq, &pf->service_task);
293 }
294 
295 /**
296  * i40e_tx_timeout - Respond to a Tx Hang
297  * @netdev: network interface device structure
298  *
299  * If any port has noticed a Tx timeout, it is likely that the whole
300  * device is munged, not just the one netdev port, so go for the full
301  * reset.
302  **/
303 static void i40e_tx_timeout(struct net_device *netdev)
304 {
305 	struct i40e_netdev_priv *np = netdev_priv(netdev);
306 	struct i40e_vsi *vsi = np->vsi;
307 	struct i40e_pf *pf = vsi->back;
308 	struct i40e_ring *tx_ring = NULL;
309 	unsigned int i, hung_queue = 0;
310 	u32 head, val;
311 
312 	pf->tx_timeout_count++;
313 
314 	/* find the stopped queue the same way the stack does */
315 	for (i = 0; i < netdev->num_tx_queues; i++) {
316 		struct netdev_queue *q;
317 		unsigned long trans_start;
318 
319 		q = netdev_get_tx_queue(netdev, i);
320 		trans_start = q->trans_start;
321 		if (netif_xmit_stopped(q) &&
322 		    time_after(jiffies,
323 			       (trans_start + netdev->watchdog_timeo))) {
324 			hung_queue = i;
325 			break;
326 		}
327 	}
328 
329 	if (i == netdev->num_tx_queues) {
330 		netdev_info(netdev, "tx_timeout: no netdev hung queue found\n");
331 	} else {
332 		/* now that we have an index, find the tx_ring struct */
333 		for (i = 0; i < vsi->num_queue_pairs; i++) {
334 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc) {
335 				if (hung_queue ==
336 				    vsi->tx_rings[i]->queue_index) {
337 					tx_ring = vsi->tx_rings[i];
338 					break;
339 				}
340 			}
341 		}
342 	}
343 
344 	if (time_after(jiffies, (pf->tx_timeout_last_recovery + HZ*20)))
345 		pf->tx_timeout_recovery_level = 1;  /* reset after some time */
346 	else if (time_before(jiffies,
347 		      (pf->tx_timeout_last_recovery + netdev->watchdog_timeo)))
348 		return;   /* don't do any new action before the next timeout */
349 
350 	/* don't kick off another recovery if one is already pending */
351 	if (test_and_set_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state))
352 		return;
353 
354 	if (tx_ring) {
355 		head = i40e_get_head(tx_ring);
356 		/* Read interrupt register */
357 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
358 			val = rd32(&pf->hw,
359 			     I40E_PFINT_DYN_CTLN(tx_ring->q_vector->v_idx +
360 						tx_ring->vsi->base_vector - 1));
361 		else
362 			val = rd32(&pf->hw, I40E_PFINT_DYN_CTL0);
363 
364 		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",
365 			    vsi->seid, hung_queue, tx_ring->next_to_clean,
366 			    head, tx_ring->next_to_use,
367 			    readl(tx_ring->tail), val);
368 	}
369 
370 	pf->tx_timeout_last_recovery = jiffies;
371 	netdev_info(netdev, "tx_timeout recovery level %d, hung_queue %d\n",
372 		    pf->tx_timeout_recovery_level, hung_queue);
373 
374 	switch (pf->tx_timeout_recovery_level) {
375 	case 1:
376 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
377 		break;
378 	case 2:
379 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
380 		break;
381 	case 3:
382 		set_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
383 		break;
384 	default:
385 		netdev_err(netdev, "tx_timeout recovery unsuccessful\n");
386 		break;
387 	}
388 
389 	i40e_service_event_schedule(pf);
390 	pf->tx_timeout_recovery_level++;
391 }
392 
393 /**
394  * i40e_get_vsi_stats_struct - Get System Network Statistics
395  * @vsi: the VSI we care about
396  *
397  * Returns the address of the device statistics structure.
398  * The statistics are actually updated from the service task.
399  **/
400 struct rtnl_link_stats64 *i40e_get_vsi_stats_struct(struct i40e_vsi *vsi)
401 {
402 	return &vsi->net_stats;
403 }
404 
405 /**
406  * i40e_get_netdev_stats_struct_tx - populate stats from a Tx ring
407  * @ring: Tx ring to get statistics from
408  * @stats: statistics entry to be updated
409  **/
410 static void i40e_get_netdev_stats_struct_tx(struct i40e_ring *ring,
411 					    struct rtnl_link_stats64 *stats)
412 {
413 	u64 bytes, packets;
414 	unsigned int start;
415 
416 	do {
417 		start = u64_stats_fetch_begin_irq(&ring->syncp);
418 		packets = ring->stats.packets;
419 		bytes   = ring->stats.bytes;
420 	} while (u64_stats_fetch_retry_irq(&ring->syncp, start));
421 
422 	stats->tx_packets += packets;
423 	stats->tx_bytes   += bytes;
424 }
425 
426 /**
427  * i40e_get_netdev_stats_struct - Get statistics for netdev interface
428  * @netdev: network interface device structure
429  * @stats: data structure to store statistics
430  *
431  * Returns the address of the device statistics structure.
432  * The statistics are actually updated from the service task.
433  **/
434 static void i40e_get_netdev_stats_struct(struct net_device *netdev,
435 				  struct rtnl_link_stats64 *stats)
436 {
437 	struct i40e_netdev_priv *np = netdev_priv(netdev);
438 	struct i40e_vsi *vsi = np->vsi;
439 	struct rtnl_link_stats64 *vsi_stats = i40e_get_vsi_stats_struct(vsi);
440 	struct i40e_ring *ring;
441 	int i;
442 
443 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
444 		return;
445 
446 	if (!vsi->tx_rings)
447 		return;
448 
449 	rcu_read_lock();
450 	for (i = 0; i < vsi->num_queue_pairs; i++) {
451 		u64 bytes, packets;
452 		unsigned int start;
453 
454 		ring = READ_ONCE(vsi->tx_rings[i]);
455 		if (!ring)
456 			continue;
457 		i40e_get_netdev_stats_struct_tx(ring, stats);
458 
459 		if (i40e_enabled_xdp_vsi(vsi)) {
460 			ring++;
461 			i40e_get_netdev_stats_struct_tx(ring, stats);
462 		}
463 
464 		ring++;
465 		do {
466 			start   = u64_stats_fetch_begin_irq(&ring->syncp);
467 			packets = ring->stats.packets;
468 			bytes   = ring->stats.bytes;
469 		} while (u64_stats_fetch_retry_irq(&ring->syncp, start));
470 
471 		stats->rx_packets += packets;
472 		stats->rx_bytes   += bytes;
473 
474 	}
475 	rcu_read_unlock();
476 
477 	/* following stats updated by i40e_watchdog_subtask() */
478 	stats->multicast	= vsi_stats->multicast;
479 	stats->tx_errors	= vsi_stats->tx_errors;
480 	stats->tx_dropped	= vsi_stats->tx_dropped;
481 	stats->rx_errors	= vsi_stats->rx_errors;
482 	stats->rx_dropped	= vsi_stats->rx_dropped;
483 	stats->rx_crc_errors	= vsi_stats->rx_crc_errors;
484 	stats->rx_length_errors	= vsi_stats->rx_length_errors;
485 }
486 
487 /**
488  * i40e_vsi_reset_stats - Resets all stats of the given vsi
489  * @vsi: the VSI to have its stats reset
490  **/
491 void i40e_vsi_reset_stats(struct i40e_vsi *vsi)
492 {
493 	struct rtnl_link_stats64 *ns;
494 	int i;
495 
496 	if (!vsi)
497 		return;
498 
499 	ns = i40e_get_vsi_stats_struct(vsi);
500 	memset(ns, 0, sizeof(*ns));
501 	memset(&vsi->net_stats_offsets, 0, sizeof(vsi->net_stats_offsets));
502 	memset(&vsi->eth_stats, 0, sizeof(vsi->eth_stats));
503 	memset(&vsi->eth_stats_offsets, 0, sizeof(vsi->eth_stats_offsets));
504 	if (vsi->rx_rings && vsi->rx_rings[0]) {
505 		for (i = 0; i < vsi->num_queue_pairs; i++) {
506 			memset(&vsi->rx_rings[i]->stats, 0,
507 			       sizeof(vsi->rx_rings[i]->stats));
508 			memset(&vsi->rx_rings[i]->rx_stats, 0,
509 			       sizeof(vsi->rx_rings[i]->rx_stats));
510 			memset(&vsi->tx_rings[i]->stats, 0,
511 			       sizeof(vsi->tx_rings[i]->stats));
512 			memset(&vsi->tx_rings[i]->tx_stats, 0,
513 			       sizeof(vsi->tx_rings[i]->tx_stats));
514 		}
515 	}
516 	vsi->stat_offsets_loaded = false;
517 }
518 
519 /**
520  * i40e_pf_reset_stats - Reset all of the stats for the given PF
521  * @pf: the PF to be reset
522  **/
523 void i40e_pf_reset_stats(struct i40e_pf *pf)
524 {
525 	int i;
526 
527 	memset(&pf->stats, 0, sizeof(pf->stats));
528 	memset(&pf->stats_offsets, 0, sizeof(pf->stats_offsets));
529 	pf->stat_offsets_loaded = false;
530 
531 	for (i = 0; i < I40E_MAX_VEB; i++) {
532 		if (pf->veb[i]) {
533 			memset(&pf->veb[i]->stats, 0,
534 			       sizeof(pf->veb[i]->stats));
535 			memset(&pf->veb[i]->stats_offsets, 0,
536 			       sizeof(pf->veb[i]->stats_offsets));
537 			memset(&pf->veb[i]->tc_stats, 0,
538 			       sizeof(pf->veb[i]->tc_stats));
539 			memset(&pf->veb[i]->tc_stats_offsets, 0,
540 			       sizeof(pf->veb[i]->tc_stats_offsets));
541 			pf->veb[i]->stat_offsets_loaded = false;
542 		}
543 	}
544 	pf->hw_csum_rx_error = 0;
545 }
546 
547 /**
548  * i40e_stat_update48 - read and update a 48 bit stat from the chip
549  * @hw: ptr to the hardware info
550  * @hireg: the high 32 bit reg to read
551  * @loreg: the low 32 bit reg to read
552  * @offset_loaded: has the initial offset been loaded yet
553  * @offset: ptr to current offset value
554  * @stat: ptr to the stat
555  *
556  * Since the device stats are not reset at PFReset, they likely will not
557  * be zeroed when the driver starts.  We'll save the first values read
558  * and use them as offsets to be subtracted from the raw values in order
559  * to report stats that count from zero.  In the process, we also manage
560  * the potential roll-over.
561  **/
562 static void i40e_stat_update48(struct i40e_hw *hw, u32 hireg, u32 loreg,
563 			       bool offset_loaded, u64 *offset, u64 *stat)
564 {
565 	u64 new_data;
566 
567 	if (hw->device_id == I40E_DEV_ID_QEMU) {
568 		new_data = rd32(hw, loreg);
569 		new_data |= ((u64)(rd32(hw, hireg) & 0xFFFF)) << 32;
570 	} else {
571 		new_data = rd64(hw, loreg);
572 	}
573 	if (!offset_loaded)
574 		*offset = new_data;
575 	if (likely(new_data >= *offset))
576 		*stat = new_data - *offset;
577 	else
578 		*stat = (new_data + BIT_ULL(48)) - *offset;
579 	*stat &= 0xFFFFFFFFFFFFULL;
580 }
581 
582 /**
583  * i40e_stat_update32 - read and update a 32 bit stat from the chip
584  * @hw: ptr to the hardware info
585  * @reg: the hw reg to read
586  * @offset_loaded: has the initial offset been loaded yet
587  * @offset: ptr to current offset value
588  * @stat: ptr to the stat
589  **/
590 static void i40e_stat_update32(struct i40e_hw *hw, u32 reg,
591 			       bool offset_loaded, u64 *offset, u64 *stat)
592 {
593 	u32 new_data;
594 
595 	new_data = rd32(hw, reg);
596 	if (!offset_loaded)
597 		*offset = new_data;
598 	if (likely(new_data >= *offset))
599 		*stat = (u32)(new_data - *offset);
600 	else
601 		*stat = (u32)((new_data + BIT_ULL(32)) - *offset);
602 }
603 
604 /**
605  * i40e_stat_update_and_clear32 - read and clear hw reg, update a 32 bit stat
606  * @hw: ptr to the hardware info
607  * @reg: the hw reg to read and clear
608  * @stat: ptr to the stat
609  **/
610 static void i40e_stat_update_and_clear32(struct i40e_hw *hw, u32 reg, u64 *stat)
611 {
612 	u32 new_data = rd32(hw, reg);
613 
614 	wr32(hw, reg, 1); /* must write a nonzero value to clear register */
615 	*stat += new_data;
616 }
617 
618 /**
619  * i40e_update_eth_stats - Update VSI-specific ethernet statistics counters.
620  * @vsi: the VSI to be updated
621  **/
622 void i40e_update_eth_stats(struct i40e_vsi *vsi)
623 {
624 	int stat_idx = le16_to_cpu(vsi->info.stat_counter_idx);
625 	struct i40e_pf *pf = vsi->back;
626 	struct i40e_hw *hw = &pf->hw;
627 	struct i40e_eth_stats *oes;
628 	struct i40e_eth_stats *es;     /* device's eth stats */
629 
630 	es = &vsi->eth_stats;
631 	oes = &vsi->eth_stats_offsets;
632 
633 	/* Gather up the stats that the hw collects */
634 	i40e_stat_update32(hw, I40E_GLV_TEPC(stat_idx),
635 			   vsi->stat_offsets_loaded,
636 			   &oes->tx_errors, &es->tx_errors);
637 	i40e_stat_update32(hw, I40E_GLV_RDPC(stat_idx),
638 			   vsi->stat_offsets_loaded,
639 			   &oes->rx_discards, &es->rx_discards);
640 	i40e_stat_update32(hw, I40E_GLV_RUPP(stat_idx),
641 			   vsi->stat_offsets_loaded,
642 			   &oes->rx_unknown_protocol, &es->rx_unknown_protocol);
643 
644 	i40e_stat_update48(hw, I40E_GLV_GORCH(stat_idx),
645 			   I40E_GLV_GORCL(stat_idx),
646 			   vsi->stat_offsets_loaded,
647 			   &oes->rx_bytes, &es->rx_bytes);
648 	i40e_stat_update48(hw, I40E_GLV_UPRCH(stat_idx),
649 			   I40E_GLV_UPRCL(stat_idx),
650 			   vsi->stat_offsets_loaded,
651 			   &oes->rx_unicast, &es->rx_unicast);
652 	i40e_stat_update48(hw, I40E_GLV_MPRCH(stat_idx),
653 			   I40E_GLV_MPRCL(stat_idx),
654 			   vsi->stat_offsets_loaded,
655 			   &oes->rx_multicast, &es->rx_multicast);
656 	i40e_stat_update48(hw, I40E_GLV_BPRCH(stat_idx),
657 			   I40E_GLV_BPRCL(stat_idx),
658 			   vsi->stat_offsets_loaded,
659 			   &oes->rx_broadcast, &es->rx_broadcast);
660 
661 	i40e_stat_update48(hw, I40E_GLV_GOTCH(stat_idx),
662 			   I40E_GLV_GOTCL(stat_idx),
663 			   vsi->stat_offsets_loaded,
664 			   &oes->tx_bytes, &es->tx_bytes);
665 	i40e_stat_update48(hw, I40E_GLV_UPTCH(stat_idx),
666 			   I40E_GLV_UPTCL(stat_idx),
667 			   vsi->stat_offsets_loaded,
668 			   &oes->tx_unicast, &es->tx_unicast);
669 	i40e_stat_update48(hw, I40E_GLV_MPTCH(stat_idx),
670 			   I40E_GLV_MPTCL(stat_idx),
671 			   vsi->stat_offsets_loaded,
672 			   &oes->tx_multicast, &es->tx_multicast);
673 	i40e_stat_update48(hw, I40E_GLV_BPTCH(stat_idx),
674 			   I40E_GLV_BPTCL(stat_idx),
675 			   vsi->stat_offsets_loaded,
676 			   &oes->tx_broadcast, &es->tx_broadcast);
677 	vsi->stat_offsets_loaded = true;
678 }
679 
680 /**
681  * i40e_update_veb_stats - Update Switch component statistics
682  * @veb: the VEB being updated
683  **/
684 void i40e_update_veb_stats(struct i40e_veb *veb)
685 {
686 	struct i40e_pf *pf = veb->pf;
687 	struct i40e_hw *hw = &pf->hw;
688 	struct i40e_eth_stats *oes;
689 	struct i40e_eth_stats *es;     /* device's eth stats */
690 	struct i40e_veb_tc_stats *veb_oes;
691 	struct i40e_veb_tc_stats *veb_es;
692 	int i, idx = 0;
693 
694 	idx = veb->stats_idx;
695 	es = &veb->stats;
696 	oes = &veb->stats_offsets;
697 	veb_es = &veb->tc_stats;
698 	veb_oes = &veb->tc_stats_offsets;
699 
700 	/* Gather up the stats that the hw collects */
701 	i40e_stat_update32(hw, I40E_GLSW_TDPC(idx),
702 			   veb->stat_offsets_loaded,
703 			   &oes->tx_discards, &es->tx_discards);
704 	if (hw->revision_id > 0)
705 		i40e_stat_update32(hw, I40E_GLSW_RUPP(idx),
706 				   veb->stat_offsets_loaded,
707 				   &oes->rx_unknown_protocol,
708 				   &es->rx_unknown_protocol);
709 	i40e_stat_update48(hw, I40E_GLSW_GORCH(idx), I40E_GLSW_GORCL(idx),
710 			   veb->stat_offsets_loaded,
711 			   &oes->rx_bytes, &es->rx_bytes);
712 	i40e_stat_update48(hw, I40E_GLSW_UPRCH(idx), I40E_GLSW_UPRCL(idx),
713 			   veb->stat_offsets_loaded,
714 			   &oes->rx_unicast, &es->rx_unicast);
715 	i40e_stat_update48(hw, I40E_GLSW_MPRCH(idx), I40E_GLSW_MPRCL(idx),
716 			   veb->stat_offsets_loaded,
717 			   &oes->rx_multicast, &es->rx_multicast);
718 	i40e_stat_update48(hw, I40E_GLSW_BPRCH(idx), I40E_GLSW_BPRCL(idx),
719 			   veb->stat_offsets_loaded,
720 			   &oes->rx_broadcast, &es->rx_broadcast);
721 
722 	i40e_stat_update48(hw, I40E_GLSW_GOTCH(idx), I40E_GLSW_GOTCL(idx),
723 			   veb->stat_offsets_loaded,
724 			   &oes->tx_bytes, &es->tx_bytes);
725 	i40e_stat_update48(hw, I40E_GLSW_UPTCH(idx), I40E_GLSW_UPTCL(idx),
726 			   veb->stat_offsets_loaded,
727 			   &oes->tx_unicast, &es->tx_unicast);
728 	i40e_stat_update48(hw, I40E_GLSW_MPTCH(idx), I40E_GLSW_MPTCL(idx),
729 			   veb->stat_offsets_loaded,
730 			   &oes->tx_multicast, &es->tx_multicast);
731 	i40e_stat_update48(hw, I40E_GLSW_BPTCH(idx), I40E_GLSW_BPTCL(idx),
732 			   veb->stat_offsets_loaded,
733 			   &oes->tx_broadcast, &es->tx_broadcast);
734 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
735 		i40e_stat_update48(hw, I40E_GLVEBTC_RPCH(i, idx),
736 				   I40E_GLVEBTC_RPCL(i, idx),
737 				   veb->stat_offsets_loaded,
738 				   &veb_oes->tc_rx_packets[i],
739 				   &veb_es->tc_rx_packets[i]);
740 		i40e_stat_update48(hw, I40E_GLVEBTC_RBCH(i, idx),
741 				   I40E_GLVEBTC_RBCL(i, idx),
742 				   veb->stat_offsets_loaded,
743 				   &veb_oes->tc_rx_bytes[i],
744 				   &veb_es->tc_rx_bytes[i]);
745 		i40e_stat_update48(hw, I40E_GLVEBTC_TPCH(i, idx),
746 				   I40E_GLVEBTC_TPCL(i, idx),
747 				   veb->stat_offsets_loaded,
748 				   &veb_oes->tc_tx_packets[i],
749 				   &veb_es->tc_tx_packets[i]);
750 		i40e_stat_update48(hw, I40E_GLVEBTC_TBCH(i, idx),
751 				   I40E_GLVEBTC_TBCL(i, idx),
752 				   veb->stat_offsets_loaded,
753 				   &veb_oes->tc_tx_bytes[i],
754 				   &veb_es->tc_tx_bytes[i]);
755 	}
756 	veb->stat_offsets_loaded = true;
757 }
758 
759 /**
760  * i40e_update_vsi_stats - Update the vsi statistics counters.
761  * @vsi: the VSI to be updated
762  *
763  * There are a few instances where we store the same stat in a
764  * couple of different structs.  This is partly because we have
765  * the netdev stats that need to be filled out, which is slightly
766  * different from the "eth_stats" defined by the chip and used in
767  * VF communications.  We sort it out here.
768  **/
769 static void i40e_update_vsi_stats(struct i40e_vsi *vsi)
770 {
771 	struct i40e_pf *pf = vsi->back;
772 	struct rtnl_link_stats64 *ons;
773 	struct rtnl_link_stats64 *ns;   /* netdev stats */
774 	struct i40e_eth_stats *oes;
775 	struct i40e_eth_stats *es;     /* device's eth stats */
776 	u32 tx_restart, tx_busy;
777 	struct i40e_ring *p;
778 	u32 rx_page, rx_buf;
779 	u64 bytes, packets;
780 	unsigned int start;
781 	u64 tx_linearize;
782 	u64 tx_force_wb;
783 	u64 rx_p, rx_b;
784 	u64 tx_p, tx_b;
785 	u16 q;
786 
787 	if (test_bit(__I40E_VSI_DOWN, vsi->state) ||
788 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
789 		return;
790 
791 	ns = i40e_get_vsi_stats_struct(vsi);
792 	ons = &vsi->net_stats_offsets;
793 	es = &vsi->eth_stats;
794 	oes = &vsi->eth_stats_offsets;
795 
796 	/* Gather up the netdev and vsi stats that the driver collects
797 	 * on the fly during packet processing
798 	 */
799 	rx_b = rx_p = 0;
800 	tx_b = tx_p = 0;
801 	tx_restart = tx_busy = tx_linearize = tx_force_wb = 0;
802 	rx_page = 0;
803 	rx_buf = 0;
804 	rcu_read_lock();
805 	for (q = 0; q < vsi->num_queue_pairs; q++) {
806 		/* locate Tx ring */
807 		p = READ_ONCE(vsi->tx_rings[q]);
808 
809 		do {
810 			start = u64_stats_fetch_begin_irq(&p->syncp);
811 			packets = p->stats.packets;
812 			bytes = p->stats.bytes;
813 		} while (u64_stats_fetch_retry_irq(&p->syncp, start));
814 		tx_b += bytes;
815 		tx_p += packets;
816 		tx_restart += p->tx_stats.restart_queue;
817 		tx_busy += p->tx_stats.tx_busy;
818 		tx_linearize += p->tx_stats.tx_linearize;
819 		tx_force_wb += p->tx_stats.tx_force_wb;
820 
821 		/* Rx queue is part of the same block as Tx queue */
822 		p = &p[1];
823 		do {
824 			start = u64_stats_fetch_begin_irq(&p->syncp);
825 			packets = p->stats.packets;
826 			bytes = p->stats.bytes;
827 		} while (u64_stats_fetch_retry_irq(&p->syncp, start));
828 		rx_b += bytes;
829 		rx_p += packets;
830 		rx_buf += p->rx_stats.alloc_buff_failed;
831 		rx_page += p->rx_stats.alloc_page_failed;
832 	}
833 	rcu_read_unlock();
834 	vsi->tx_restart = tx_restart;
835 	vsi->tx_busy = tx_busy;
836 	vsi->tx_linearize = tx_linearize;
837 	vsi->tx_force_wb = tx_force_wb;
838 	vsi->rx_page_failed = rx_page;
839 	vsi->rx_buf_failed = rx_buf;
840 
841 	ns->rx_packets = rx_p;
842 	ns->rx_bytes = rx_b;
843 	ns->tx_packets = tx_p;
844 	ns->tx_bytes = tx_b;
845 
846 	/* update netdev stats from eth stats */
847 	i40e_update_eth_stats(vsi);
848 	ons->tx_errors = oes->tx_errors;
849 	ns->tx_errors = es->tx_errors;
850 	ons->multicast = oes->rx_multicast;
851 	ns->multicast = es->rx_multicast;
852 	ons->rx_dropped = oes->rx_discards;
853 	ns->rx_dropped = es->rx_discards;
854 	ons->tx_dropped = oes->tx_discards;
855 	ns->tx_dropped = es->tx_discards;
856 
857 	/* pull in a couple PF stats if this is the main vsi */
858 	if (vsi == pf->vsi[pf->lan_vsi]) {
859 		ns->rx_crc_errors = pf->stats.crc_errors;
860 		ns->rx_errors = pf->stats.crc_errors + pf->stats.illegal_bytes;
861 		ns->rx_length_errors = pf->stats.rx_length_errors;
862 	}
863 }
864 
865 /**
866  * i40e_update_pf_stats - Update the PF statistics counters.
867  * @pf: the PF to be updated
868  **/
869 static void i40e_update_pf_stats(struct i40e_pf *pf)
870 {
871 	struct i40e_hw_port_stats *osd = &pf->stats_offsets;
872 	struct i40e_hw_port_stats *nsd = &pf->stats;
873 	struct i40e_hw *hw = &pf->hw;
874 	u32 val;
875 	int i;
876 
877 	i40e_stat_update48(hw, I40E_GLPRT_GORCH(hw->port),
878 			   I40E_GLPRT_GORCL(hw->port),
879 			   pf->stat_offsets_loaded,
880 			   &osd->eth.rx_bytes, &nsd->eth.rx_bytes);
881 	i40e_stat_update48(hw, I40E_GLPRT_GOTCH(hw->port),
882 			   I40E_GLPRT_GOTCL(hw->port),
883 			   pf->stat_offsets_loaded,
884 			   &osd->eth.tx_bytes, &nsd->eth.tx_bytes);
885 	i40e_stat_update32(hw, I40E_GLPRT_RDPC(hw->port),
886 			   pf->stat_offsets_loaded,
887 			   &osd->eth.rx_discards,
888 			   &nsd->eth.rx_discards);
889 	i40e_stat_update48(hw, I40E_GLPRT_UPRCH(hw->port),
890 			   I40E_GLPRT_UPRCL(hw->port),
891 			   pf->stat_offsets_loaded,
892 			   &osd->eth.rx_unicast,
893 			   &nsd->eth.rx_unicast);
894 	i40e_stat_update48(hw, I40E_GLPRT_MPRCH(hw->port),
895 			   I40E_GLPRT_MPRCL(hw->port),
896 			   pf->stat_offsets_loaded,
897 			   &osd->eth.rx_multicast,
898 			   &nsd->eth.rx_multicast);
899 	i40e_stat_update48(hw, I40E_GLPRT_BPRCH(hw->port),
900 			   I40E_GLPRT_BPRCL(hw->port),
901 			   pf->stat_offsets_loaded,
902 			   &osd->eth.rx_broadcast,
903 			   &nsd->eth.rx_broadcast);
904 	i40e_stat_update48(hw, I40E_GLPRT_UPTCH(hw->port),
905 			   I40E_GLPRT_UPTCL(hw->port),
906 			   pf->stat_offsets_loaded,
907 			   &osd->eth.tx_unicast,
908 			   &nsd->eth.tx_unicast);
909 	i40e_stat_update48(hw, I40E_GLPRT_MPTCH(hw->port),
910 			   I40E_GLPRT_MPTCL(hw->port),
911 			   pf->stat_offsets_loaded,
912 			   &osd->eth.tx_multicast,
913 			   &nsd->eth.tx_multicast);
914 	i40e_stat_update48(hw, I40E_GLPRT_BPTCH(hw->port),
915 			   I40E_GLPRT_BPTCL(hw->port),
916 			   pf->stat_offsets_loaded,
917 			   &osd->eth.tx_broadcast,
918 			   &nsd->eth.tx_broadcast);
919 
920 	i40e_stat_update32(hw, I40E_GLPRT_TDOLD(hw->port),
921 			   pf->stat_offsets_loaded,
922 			   &osd->tx_dropped_link_down,
923 			   &nsd->tx_dropped_link_down);
924 
925 	i40e_stat_update32(hw, I40E_GLPRT_CRCERRS(hw->port),
926 			   pf->stat_offsets_loaded,
927 			   &osd->crc_errors, &nsd->crc_errors);
928 
929 	i40e_stat_update32(hw, I40E_GLPRT_ILLERRC(hw->port),
930 			   pf->stat_offsets_loaded,
931 			   &osd->illegal_bytes, &nsd->illegal_bytes);
932 
933 	i40e_stat_update32(hw, I40E_GLPRT_MLFC(hw->port),
934 			   pf->stat_offsets_loaded,
935 			   &osd->mac_local_faults,
936 			   &nsd->mac_local_faults);
937 	i40e_stat_update32(hw, I40E_GLPRT_MRFC(hw->port),
938 			   pf->stat_offsets_loaded,
939 			   &osd->mac_remote_faults,
940 			   &nsd->mac_remote_faults);
941 
942 	i40e_stat_update32(hw, I40E_GLPRT_RLEC(hw->port),
943 			   pf->stat_offsets_loaded,
944 			   &osd->rx_length_errors,
945 			   &nsd->rx_length_errors);
946 
947 	i40e_stat_update32(hw, I40E_GLPRT_LXONRXC(hw->port),
948 			   pf->stat_offsets_loaded,
949 			   &osd->link_xon_rx, &nsd->link_xon_rx);
950 	i40e_stat_update32(hw, I40E_GLPRT_LXONTXC(hw->port),
951 			   pf->stat_offsets_loaded,
952 			   &osd->link_xon_tx, &nsd->link_xon_tx);
953 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFRXC(hw->port),
954 			   pf->stat_offsets_loaded,
955 			   &osd->link_xoff_rx, &nsd->link_xoff_rx);
956 	i40e_stat_update32(hw, I40E_GLPRT_LXOFFTXC(hw->port),
957 			   pf->stat_offsets_loaded,
958 			   &osd->link_xoff_tx, &nsd->link_xoff_tx);
959 
960 	for (i = 0; i < 8; i++) {
961 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFRXC(hw->port, i),
962 				   pf->stat_offsets_loaded,
963 				   &osd->priority_xoff_rx[i],
964 				   &nsd->priority_xoff_rx[i]);
965 		i40e_stat_update32(hw, I40E_GLPRT_PXONRXC(hw->port, i),
966 				   pf->stat_offsets_loaded,
967 				   &osd->priority_xon_rx[i],
968 				   &nsd->priority_xon_rx[i]);
969 		i40e_stat_update32(hw, I40E_GLPRT_PXONTXC(hw->port, i),
970 				   pf->stat_offsets_loaded,
971 				   &osd->priority_xon_tx[i],
972 				   &nsd->priority_xon_tx[i]);
973 		i40e_stat_update32(hw, I40E_GLPRT_PXOFFTXC(hw->port, i),
974 				   pf->stat_offsets_loaded,
975 				   &osd->priority_xoff_tx[i],
976 				   &nsd->priority_xoff_tx[i]);
977 		i40e_stat_update32(hw,
978 				   I40E_GLPRT_RXON2OFFCNT(hw->port, i),
979 				   pf->stat_offsets_loaded,
980 				   &osd->priority_xon_2_xoff[i],
981 				   &nsd->priority_xon_2_xoff[i]);
982 	}
983 
984 	i40e_stat_update48(hw, I40E_GLPRT_PRC64H(hw->port),
985 			   I40E_GLPRT_PRC64L(hw->port),
986 			   pf->stat_offsets_loaded,
987 			   &osd->rx_size_64, &nsd->rx_size_64);
988 	i40e_stat_update48(hw, I40E_GLPRT_PRC127H(hw->port),
989 			   I40E_GLPRT_PRC127L(hw->port),
990 			   pf->stat_offsets_loaded,
991 			   &osd->rx_size_127, &nsd->rx_size_127);
992 	i40e_stat_update48(hw, I40E_GLPRT_PRC255H(hw->port),
993 			   I40E_GLPRT_PRC255L(hw->port),
994 			   pf->stat_offsets_loaded,
995 			   &osd->rx_size_255, &nsd->rx_size_255);
996 	i40e_stat_update48(hw, I40E_GLPRT_PRC511H(hw->port),
997 			   I40E_GLPRT_PRC511L(hw->port),
998 			   pf->stat_offsets_loaded,
999 			   &osd->rx_size_511, &nsd->rx_size_511);
1000 	i40e_stat_update48(hw, I40E_GLPRT_PRC1023H(hw->port),
1001 			   I40E_GLPRT_PRC1023L(hw->port),
1002 			   pf->stat_offsets_loaded,
1003 			   &osd->rx_size_1023, &nsd->rx_size_1023);
1004 	i40e_stat_update48(hw, I40E_GLPRT_PRC1522H(hw->port),
1005 			   I40E_GLPRT_PRC1522L(hw->port),
1006 			   pf->stat_offsets_loaded,
1007 			   &osd->rx_size_1522, &nsd->rx_size_1522);
1008 	i40e_stat_update48(hw, I40E_GLPRT_PRC9522H(hw->port),
1009 			   I40E_GLPRT_PRC9522L(hw->port),
1010 			   pf->stat_offsets_loaded,
1011 			   &osd->rx_size_big, &nsd->rx_size_big);
1012 
1013 	i40e_stat_update48(hw, I40E_GLPRT_PTC64H(hw->port),
1014 			   I40E_GLPRT_PTC64L(hw->port),
1015 			   pf->stat_offsets_loaded,
1016 			   &osd->tx_size_64, &nsd->tx_size_64);
1017 	i40e_stat_update48(hw, I40E_GLPRT_PTC127H(hw->port),
1018 			   I40E_GLPRT_PTC127L(hw->port),
1019 			   pf->stat_offsets_loaded,
1020 			   &osd->tx_size_127, &nsd->tx_size_127);
1021 	i40e_stat_update48(hw, I40E_GLPRT_PTC255H(hw->port),
1022 			   I40E_GLPRT_PTC255L(hw->port),
1023 			   pf->stat_offsets_loaded,
1024 			   &osd->tx_size_255, &nsd->tx_size_255);
1025 	i40e_stat_update48(hw, I40E_GLPRT_PTC511H(hw->port),
1026 			   I40E_GLPRT_PTC511L(hw->port),
1027 			   pf->stat_offsets_loaded,
1028 			   &osd->tx_size_511, &nsd->tx_size_511);
1029 	i40e_stat_update48(hw, I40E_GLPRT_PTC1023H(hw->port),
1030 			   I40E_GLPRT_PTC1023L(hw->port),
1031 			   pf->stat_offsets_loaded,
1032 			   &osd->tx_size_1023, &nsd->tx_size_1023);
1033 	i40e_stat_update48(hw, I40E_GLPRT_PTC1522H(hw->port),
1034 			   I40E_GLPRT_PTC1522L(hw->port),
1035 			   pf->stat_offsets_loaded,
1036 			   &osd->tx_size_1522, &nsd->tx_size_1522);
1037 	i40e_stat_update48(hw, I40E_GLPRT_PTC9522H(hw->port),
1038 			   I40E_GLPRT_PTC9522L(hw->port),
1039 			   pf->stat_offsets_loaded,
1040 			   &osd->tx_size_big, &nsd->tx_size_big);
1041 
1042 	i40e_stat_update32(hw, I40E_GLPRT_RUC(hw->port),
1043 			   pf->stat_offsets_loaded,
1044 			   &osd->rx_undersize, &nsd->rx_undersize);
1045 	i40e_stat_update32(hw, I40E_GLPRT_RFC(hw->port),
1046 			   pf->stat_offsets_loaded,
1047 			   &osd->rx_fragments, &nsd->rx_fragments);
1048 	i40e_stat_update32(hw, I40E_GLPRT_ROC(hw->port),
1049 			   pf->stat_offsets_loaded,
1050 			   &osd->rx_oversize, &nsd->rx_oversize);
1051 	i40e_stat_update32(hw, I40E_GLPRT_RJC(hw->port),
1052 			   pf->stat_offsets_loaded,
1053 			   &osd->rx_jabber, &nsd->rx_jabber);
1054 
1055 	/* FDIR stats */
1056 	i40e_stat_update_and_clear32(hw,
1057 			I40E_GLQF_PCNT(I40E_FD_ATR_STAT_IDX(hw->pf_id)),
1058 			&nsd->fd_atr_match);
1059 	i40e_stat_update_and_clear32(hw,
1060 			I40E_GLQF_PCNT(I40E_FD_SB_STAT_IDX(hw->pf_id)),
1061 			&nsd->fd_sb_match);
1062 	i40e_stat_update_and_clear32(hw,
1063 			I40E_GLQF_PCNT(I40E_FD_ATR_TUNNEL_STAT_IDX(hw->pf_id)),
1064 			&nsd->fd_atr_tunnel_match);
1065 
1066 	val = rd32(hw, I40E_PRTPM_EEE_STAT);
1067 	nsd->tx_lpi_status =
1068 		       (val & I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_MASK) >>
1069 			I40E_PRTPM_EEE_STAT_TX_LPI_STATUS_SHIFT;
1070 	nsd->rx_lpi_status =
1071 		       (val & I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_MASK) >>
1072 			I40E_PRTPM_EEE_STAT_RX_LPI_STATUS_SHIFT;
1073 	i40e_stat_update32(hw, I40E_PRTPM_TLPIC,
1074 			   pf->stat_offsets_loaded,
1075 			   &osd->tx_lpi_count, &nsd->tx_lpi_count);
1076 	i40e_stat_update32(hw, I40E_PRTPM_RLPIC,
1077 			   pf->stat_offsets_loaded,
1078 			   &osd->rx_lpi_count, &nsd->rx_lpi_count);
1079 
1080 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED &&
1081 	    !test_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
1082 		nsd->fd_sb_status = true;
1083 	else
1084 		nsd->fd_sb_status = false;
1085 
1086 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED &&
1087 	    !test_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
1088 		nsd->fd_atr_status = true;
1089 	else
1090 		nsd->fd_atr_status = false;
1091 
1092 	pf->stat_offsets_loaded = true;
1093 }
1094 
1095 /**
1096  * i40e_update_stats - Update the various statistics counters.
1097  * @vsi: the VSI to be updated
1098  *
1099  * Update the various stats for this VSI and its related entities.
1100  **/
1101 void i40e_update_stats(struct i40e_vsi *vsi)
1102 {
1103 	struct i40e_pf *pf = vsi->back;
1104 
1105 	if (vsi == pf->vsi[pf->lan_vsi])
1106 		i40e_update_pf_stats(pf);
1107 
1108 	i40e_update_vsi_stats(vsi);
1109 }
1110 
1111 /**
1112  * i40e_find_filter - Search VSI filter list for specific mac/vlan filter
1113  * @vsi: the VSI to be searched
1114  * @macaddr: the MAC address
1115  * @vlan: the vlan
1116  *
1117  * Returns ptr to the filter object or NULL
1118  **/
1119 static struct i40e_mac_filter *i40e_find_filter(struct i40e_vsi *vsi,
1120 						const u8 *macaddr, s16 vlan)
1121 {
1122 	struct i40e_mac_filter *f;
1123 	u64 key;
1124 
1125 	if (!vsi || !macaddr)
1126 		return NULL;
1127 
1128 	key = i40e_addr_to_hkey(macaddr);
1129 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1130 		if ((ether_addr_equal(macaddr, f->macaddr)) &&
1131 		    (vlan == f->vlan))
1132 			return f;
1133 	}
1134 	return NULL;
1135 }
1136 
1137 /**
1138  * i40e_find_mac - Find a mac addr in the macvlan filters list
1139  * @vsi: the VSI to be searched
1140  * @macaddr: the MAC address we are searching for
1141  *
1142  * Returns the first filter with the provided MAC address or NULL if
1143  * MAC address was not found
1144  **/
1145 struct i40e_mac_filter *i40e_find_mac(struct i40e_vsi *vsi, const u8 *macaddr)
1146 {
1147 	struct i40e_mac_filter *f;
1148 	u64 key;
1149 
1150 	if (!vsi || !macaddr)
1151 		return NULL;
1152 
1153 	key = i40e_addr_to_hkey(macaddr);
1154 	hash_for_each_possible(vsi->mac_filter_hash, f, hlist, key) {
1155 		if ((ether_addr_equal(macaddr, f->macaddr)))
1156 			return f;
1157 	}
1158 	return NULL;
1159 }
1160 
1161 /**
1162  * i40e_is_vsi_in_vlan - Check if VSI is in vlan mode
1163  * @vsi: the VSI to be searched
1164  *
1165  * Returns true if VSI is in vlan mode or false otherwise
1166  **/
1167 bool i40e_is_vsi_in_vlan(struct i40e_vsi *vsi)
1168 {
1169 	/* If we have a PVID, always operate in VLAN mode */
1170 	if (vsi->info.pvid)
1171 		return true;
1172 
1173 	/* We need to operate in VLAN mode whenever we have any filters with
1174 	 * a VLAN other than I40E_VLAN_ALL. We could check the table each
1175 	 * time, incurring search cost repeatedly. However, we can notice two
1176 	 * things:
1177 	 *
1178 	 * 1) the only place where we can gain a VLAN filter is in
1179 	 *    i40e_add_filter.
1180 	 *
1181 	 * 2) the only place where filters are actually removed is in
1182 	 *    i40e_sync_filters_subtask.
1183 	 *
1184 	 * Thus, we can simply use a boolean value, has_vlan_filters which we
1185 	 * will set to true when we add a VLAN filter in i40e_add_filter. Then
1186 	 * we have to perform the full search after deleting filters in
1187 	 * i40e_sync_filters_subtask, but we already have to search
1188 	 * filters here and can perform the check at the same time. This
1189 	 * results in avoiding embedding a loop for VLAN mode inside another
1190 	 * loop over all the filters, and should maintain correctness as noted
1191 	 * above.
1192 	 */
1193 	return vsi->has_vlan_filter;
1194 }
1195 
1196 /**
1197  * i40e_correct_mac_vlan_filters - Correct non-VLAN filters if necessary
1198  * @vsi: the VSI to configure
1199  * @tmp_add_list: list of filters ready to be added
1200  * @tmp_del_list: list of filters ready to be deleted
1201  * @vlan_filters: the number of active VLAN filters
1202  *
1203  * Update VLAN=0 and VLAN=-1 (I40E_VLAN_ANY) filters properly so that they
1204  * behave as expected. If we have any active VLAN filters remaining or about
1205  * to be added then we need to update non-VLAN filters to be marked as VLAN=0
1206  * so that they only match against untagged traffic. If we no longer have any
1207  * active VLAN filters, we need to make all non-VLAN filters marked as VLAN=-1
1208  * so that they match against both tagged and untagged traffic. In this way,
1209  * we ensure that we correctly receive the desired traffic. This ensures that
1210  * when we have an active VLAN we will receive only untagged traffic and
1211  * traffic matching active VLANs. If we have no active VLANs then we will
1212  * operate in non-VLAN mode and receive all traffic, tagged or untagged.
1213  *
1214  * Finally, in a similar fashion, this function also corrects filters when
1215  * there is an active PVID assigned to this VSI.
1216  *
1217  * In case of memory allocation failure return -ENOMEM. Otherwise, return 0.
1218  *
1219  * This function is only expected to be called from within
1220  * i40e_sync_vsi_filters.
1221  *
1222  * NOTE: This function expects to be called while under the
1223  * mac_filter_hash_lock
1224  */
1225 static int i40e_correct_mac_vlan_filters(struct i40e_vsi *vsi,
1226 					 struct hlist_head *tmp_add_list,
1227 					 struct hlist_head *tmp_del_list,
1228 					 int vlan_filters)
1229 {
1230 	s16 pvid = le16_to_cpu(vsi->info.pvid);
1231 	struct i40e_mac_filter *f, *add_head;
1232 	struct i40e_new_mac_filter *new;
1233 	struct hlist_node *h;
1234 	int bkt, new_vlan;
1235 
1236 	/* To determine if a particular filter needs to be replaced we
1237 	 * have the three following conditions:
1238 	 *
1239 	 * a) if we have a PVID assigned, then all filters which are
1240 	 *    not marked as VLAN=PVID must be replaced with filters that
1241 	 *    are.
1242 	 * b) otherwise, if we have any active VLANS, all filters
1243 	 *    which are marked as VLAN=-1 must be replaced with
1244 	 *    filters marked as VLAN=0
1245 	 * c) finally, if we do not have any active VLANS, all filters
1246 	 *    which are marked as VLAN=0 must be replaced with filters
1247 	 *    marked as VLAN=-1
1248 	 */
1249 
1250 	/* Update the filters about to be added in place */
1251 	hlist_for_each_entry(new, tmp_add_list, hlist) {
1252 		if (pvid && new->f->vlan != pvid)
1253 			new->f->vlan = pvid;
1254 		else if (vlan_filters && new->f->vlan == I40E_VLAN_ANY)
1255 			new->f->vlan = 0;
1256 		else if (!vlan_filters && new->f->vlan == 0)
1257 			new->f->vlan = I40E_VLAN_ANY;
1258 	}
1259 
1260 	/* Update the remaining active filters */
1261 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1262 		/* Combine the checks for whether a filter needs to be changed
1263 		 * and then determine the new VLAN inside the if block, in
1264 		 * order to avoid duplicating code for adding the new filter
1265 		 * then deleting the old filter.
1266 		 */
1267 		if ((pvid && f->vlan != pvid) ||
1268 		    (vlan_filters && f->vlan == I40E_VLAN_ANY) ||
1269 		    (!vlan_filters && f->vlan == 0)) {
1270 			/* Determine the new vlan we will be adding */
1271 			if (pvid)
1272 				new_vlan = pvid;
1273 			else if (vlan_filters)
1274 				new_vlan = 0;
1275 			else
1276 				new_vlan = I40E_VLAN_ANY;
1277 
1278 			/* Create the new filter */
1279 			add_head = i40e_add_filter(vsi, f->macaddr, new_vlan);
1280 			if (!add_head)
1281 				return -ENOMEM;
1282 
1283 			/* Create a temporary i40e_new_mac_filter */
1284 			new = kzalloc(sizeof(*new), GFP_ATOMIC);
1285 			if (!new)
1286 				return -ENOMEM;
1287 
1288 			new->f = add_head;
1289 			new->state = add_head->state;
1290 
1291 			/* Add the new filter to the tmp list */
1292 			hlist_add_head(&new->hlist, tmp_add_list);
1293 
1294 			/* Put the original filter into the delete list */
1295 			f->state = I40E_FILTER_REMOVE;
1296 			hash_del(&f->hlist);
1297 			hlist_add_head(&f->hlist, tmp_del_list);
1298 		}
1299 	}
1300 
1301 	vsi->has_vlan_filter = !!vlan_filters;
1302 
1303 	return 0;
1304 }
1305 
1306 /**
1307  * i40e_rm_default_mac_filter - Remove the default MAC filter set by NVM
1308  * @vsi: the PF Main VSI - inappropriate for any other VSI
1309  * @macaddr: the MAC address
1310  *
1311  * Remove whatever filter the firmware set up so the driver can manage
1312  * its own filtering intelligently.
1313  **/
1314 static void i40e_rm_default_mac_filter(struct i40e_vsi *vsi, u8 *macaddr)
1315 {
1316 	struct i40e_aqc_remove_macvlan_element_data element;
1317 	struct i40e_pf *pf = vsi->back;
1318 
1319 	/* Only appropriate for the PF main VSI */
1320 	if (vsi->type != I40E_VSI_MAIN)
1321 		return;
1322 
1323 	memset(&element, 0, sizeof(element));
1324 	ether_addr_copy(element.mac_addr, macaddr);
1325 	element.vlan_tag = 0;
1326 	/* Ignore error returns, some firmware does it this way... */
1327 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
1328 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1329 
1330 	memset(&element, 0, sizeof(element));
1331 	ether_addr_copy(element.mac_addr, macaddr);
1332 	element.vlan_tag = 0;
1333 	/* ...and some firmware does it this way. */
1334 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH |
1335 			I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
1336 	i40e_aq_remove_macvlan(&pf->hw, vsi->seid, &element, 1, NULL);
1337 }
1338 
1339 /**
1340  * i40e_add_filter - Add a mac/vlan filter to the VSI
1341  * @vsi: the VSI to be searched
1342  * @macaddr: the MAC address
1343  * @vlan: the vlan
1344  *
1345  * Returns ptr to the filter object or NULL when no memory available.
1346  *
1347  * NOTE: This function is expected to be called with mac_filter_hash_lock
1348  * being held.
1349  **/
1350 struct i40e_mac_filter *i40e_add_filter(struct i40e_vsi *vsi,
1351 					const u8 *macaddr, s16 vlan)
1352 {
1353 	struct i40e_mac_filter *f;
1354 	u64 key;
1355 
1356 	if (!vsi || !macaddr)
1357 		return NULL;
1358 
1359 	f = i40e_find_filter(vsi, macaddr, vlan);
1360 	if (!f) {
1361 		f = kzalloc(sizeof(*f), GFP_ATOMIC);
1362 		if (!f)
1363 			return NULL;
1364 
1365 		/* Update the boolean indicating if we need to function in
1366 		 * VLAN mode.
1367 		 */
1368 		if (vlan >= 0)
1369 			vsi->has_vlan_filter = true;
1370 
1371 		ether_addr_copy(f->macaddr, macaddr);
1372 		f->vlan = vlan;
1373 		f->state = I40E_FILTER_NEW;
1374 		INIT_HLIST_NODE(&f->hlist);
1375 
1376 		key = i40e_addr_to_hkey(macaddr);
1377 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1378 
1379 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1380 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1381 	}
1382 
1383 	/* If we're asked to add a filter that has been marked for removal, it
1384 	 * is safe to simply restore it to active state. __i40e_del_filter
1385 	 * will have simply deleted any filters which were previously marked
1386 	 * NEW or FAILED, so if it is currently marked REMOVE it must have
1387 	 * previously been ACTIVE. Since we haven't yet run the sync filters
1388 	 * task, just restore this filter to the ACTIVE state so that the
1389 	 * sync task leaves it in place
1390 	 */
1391 	if (f->state == I40E_FILTER_REMOVE)
1392 		f->state = I40E_FILTER_ACTIVE;
1393 
1394 	return f;
1395 }
1396 
1397 /**
1398  * __i40e_del_filter - Remove a specific filter from the VSI
1399  * @vsi: VSI to remove from
1400  * @f: the filter to remove from the list
1401  *
1402  * This function should be called instead of i40e_del_filter only if you know
1403  * the exact filter you will remove already, such as via i40e_find_filter or
1404  * i40e_find_mac.
1405  *
1406  * NOTE: This function is expected to be called with mac_filter_hash_lock
1407  * being held.
1408  * ANOTHER NOTE: This function MUST be called from within the context of
1409  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1410  * instead of list_for_each_entry().
1411  **/
1412 void __i40e_del_filter(struct i40e_vsi *vsi, struct i40e_mac_filter *f)
1413 {
1414 	if (!f)
1415 		return;
1416 
1417 	/* If the filter was never added to firmware then we can just delete it
1418 	 * directly and we don't want to set the status to remove or else an
1419 	 * admin queue command will unnecessarily fire.
1420 	 */
1421 	if ((f->state == I40E_FILTER_FAILED) ||
1422 	    (f->state == I40E_FILTER_NEW)) {
1423 		hash_del(&f->hlist);
1424 		kfree(f);
1425 	} else {
1426 		f->state = I40E_FILTER_REMOVE;
1427 	}
1428 
1429 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1430 	set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1431 }
1432 
1433 /**
1434  * i40e_del_filter - Remove a MAC/VLAN filter from the VSI
1435  * @vsi: the VSI to be searched
1436  * @macaddr: the MAC address
1437  * @vlan: the VLAN
1438  *
1439  * NOTE: This function is expected to be called with mac_filter_hash_lock
1440  * being held.
1441  * ANOTHER NOTE: This function MUST be called from within the context of
1442  * the "safe" variants of any list iterators, e.g. list_for_each_entry_safe()
1443  * instead of list_for_each_entry().
1444  **/
1445 void i40e_del_filter(struct i40e_vsi *vsi, const u8 *macaddr, s16 vlan)
1446 {
1447 	struct i40e_mac_filter *f;
1448 
1449 	if (!vsi || !macaddr)
1450 		return;
1451 
1452 	f = i40e_find_filter(vsi, macaddr, vlan);
1453 	__i40e_del_filter(vsi, f);
1454 }
1455 
1456 /**
1457  * i40e_add_mac_filter - Add a MAC filter for all active VLANs
1458  * @vsi: the VSI to be searched
1459  * @macaddr: the mac address to be filtered
1460  *
1461  * If we're not in VLAN mode, just add the filter to I40E_VLAN_ANY. Otherwise,
1462  * go through all the macvlan filters and add a macvlan filter for each
1463  * unique vlan that already exists. If a PVID has been assigned, instead only
1464  * add the macaddr to that VLAN.
1465  *
1466  * Returns last filter added on success, else NULL
1467  **/
1468 struct i40e_mac_filter *i40e_add_mac_filter(struct i40e_vsi *vsi,
1469 					    const u8 *macaddr)
1470 {
1471 	struct i40e_mac_filter *f, *add = NULL;
1472 	struct hlist_node *h;
1473 	int bkt;
1474 
1475 	if (vsi->info.pvid)
1476 		return i40e_add_filter(vsi, macaddr,
1477 				       le16_to_cpu(vsi->info.pvid));
1478 
1479 	if (!i40e_is_vsi_in_vlan(vsi))
1480 		return i40e_add_filter(vsi, macaddr, I40E_VLAN_ANY);
1481 
1482 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1483 		if (f->state == I40E_FILTER_REMOVE)
1484 			continue;
1485 		add = i40e_add_filter(vsi, macaddr, f->vlan);
1486 		if (!add)
1487 			return NULL;
1488 	}
1489 
1490 	return add;
1491 }
1492 
1493 /**
1494  * i40e_del_mac_filter - Remove a MAC filter from all VLANs
1495  * @vsi: the VSI to be searched
1496  * @macaddr: the mac address to be removed
1497  *
1498  * Removes a given MAC address from a VSI regardless of what VLAN it has been
1499  * associated with.
1500  *
1501  * Returns 0 for success, or error
1502  **/
1503 int i40e_del_mac_filter(struct i40e_vsi *vsi, const u8 *macaddr)
1504 {
1505 	struct i40e_mac_filter *f;
1506 	struct hlist_node *h;
1507 	bool found = false;
1508 	int bkt;
1509 
1510 	lockdep_assert_held(&vsi->mac_filter_hash_lock);
1511 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
1512 		if (ether_addr_equal(macaddr, f->macaddr)) {
1513 			__i40e_del_filter(vsi, f);
1514 			found = true;
1515 		}
1516 	}
1517 
1518 	if (found)
1519 		return 0;
1520 	else
1521 		return -ENOENT;
1522 }
1523 
1524 /**
1525  * i40e_set_mac - NDO callback to set mac address
1526  * @netdev: network interface device structure
1527  * @p: pointer to an address structure
1528  *
1529  * Returns 0 on success, negative on failure
1530  **/
1531 static int i40e_set_mac(struct net_device *netdev, void *p)
1532 {
1533 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1534 	struct i40e_vsi *vsi = np->vsi;
1535 	struct i40e_pf *pf = vsi->back;
1536 	struct i40e_hw *hw = &pf->hw;
1537 	struct sockaddr *addr = p;
1538 
1539 	if (!is_valid_ether_addr(addr->sa_data))
1540 		return -EADDRNOTAVAIL;
1541 
1542 	if (ether_addr_equal(netdev->dev_addr, addr->sa_data)) {
1543 		netdev_info(netdev, "already using mac address %pM\n",
1544 			    addr->sa_data);
1545 		return 0;
1546 	}
1547 
1548 	if (test_bit(__I40E_DOWN, pf->state) ||
1549 	    test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
1550 		return -EADDRNOTAVAIL;
1551 
1552 	if (ether_addr_equal(hw->mac.addr, addr->sa_data))
1553 		netdev_info(netdev, "returning to hw mac address %pM\n",
1554 			    hw->mac.addr);
1555 	else
1556 		netdev_info(netdev, "set new mac address %pM\n", addr->sa_data);
1557 
1558 	/* Copy the address first, so that we avoid a possible race with
1559 	 * .set_rx_mode().
1560 	 * - Remove old address from MAC filter
1561 	 * - Copy new address
1562 	 * - Add new address to MAC filter
1563 	 */
1564 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1565 	i40e_del_mac_filter(vsi, netdev->dev_addr);
1566 	ether_addr_copy(netdev->dev_addr, addr->sa_data);
1567 	i40e_add_mac_filter(vsi, netdev->dev_addr);
1568 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1569 
1570 	if (vsi->type == I40E_VSI_MAIN) {
1571 		i40e_status ret;
1572 
1573 		ret = i40e_aq_mac_address_write(hw, I40E_AQC_WRITE_TYPE_LAA_WOL,
1574 						addr->sa_data, NULL);
1575 		if (ret)
1576 			netdev_info(netdev, "Ignoring error from firmware on LAA update, status %s, AQ ret %s\n",
1577 				    i40e_stat_str(hw, ret),
1578 				    i40e_aq_str(hw, hw->aq.asq_last_status));
1579 	}
1580 
1581 	/* schedule our worker thread which will take care of
1582 	 * applying the new filter changes
1583 	 */
1584 	i40e_service_event_schedule(pf);
1585 	return 0;
1586 }
1587 
1588 /**
1589  * i40e_config_rss_aq - Prepare for RSS using AQ commands
1590  * @vsi: vsi structure
1591  * @seed: RSS hash seed
1592  **/
1593 static int i40e_config_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
1594 			      u8 *lut, u16 lut_size)
1595 {
1596 	struct i40e_pf *pf = vsi->back;
1597 	struct i40e_hw *hw = &pf->hw;
1598 	int ret = 0;
1599 
1600 	if (seed) {
1601 		struct i40e_aqc_get_set_rss_key_data *seed_dw =
1602 			(struct i40e_aqc_get_set_rss_key_data *)seed;
1603 		ret = i40e_aq_set_rss_key(hw, vsi->id, seed_dw);
1604 		if (ret) {
1605 			dev_info(&pf->pdev->dev,
1606 				 "Cannot set RSS key, err %s aq_err %s\n",
1607 				 i40e_stat_str(hw, ret),
1608 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1609 			return ret;
1610 		}
1611 	}
1612 	if (lut) {
1613 		bool pf_lut = vsi->type == I40E_VSI_MAIN ? true : false;
1614 
1615 		ret = i40e_aq_set_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
1616 		if (ret) {
1617 			dev_info(&pf->pdev->dev,
1618 				 "Cannot set RSS lut, err %s aq_err %s\n",
1619 				 i40e_stat_str(hw, ret),
1620 				 i40e_aq_str(hw, hw->aq.asq_last_status));
1621 			return ret;
1622 		}
1623 	}
1624 	return ret;
1625 }
1626 
1627 /**
1628  * i40e_vsi_config_rss - Prepare for VSI(VMDq) RSS if used
1629  * @vsi: VSI structure
1630  **/
1631 static int i40e_vsi_config_rss(struct i40e_vsi *vsi)
1632 {
1633 	struct i40e_pf *pf = vsi->back;
1634 	u8 seed[I40E_HKEY_ARRAY_SIZE];
1635 	u8 *lut;
1636 	int ret;
1637 
1638 	if (!(pf->hw_features & I40E_HW_RSS_AQ_CAPABLE))
1639 		return 0;
1640 	if (!vsi->rss_size)
1641 		vsi->rss_size = min_t(int, pf->alloc_rss_size,
1642 				      vsi->num_queue_pairs);
1643 	if (!vsi->rss_size)
1644 		return -EINVAL;
1645 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
1646 	if (!lut)
1647 		return -ENOMEM;
1648 
1649 	/* Use the user configured hash keys and lookup table if there is one,
1650 	 * otherwise use default
1651 	 */
1652 	if (vsi->rss_lut_user)
1653 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
1654 	else
1655 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
1656 	if (vsi->rss_hkey_user)
1657 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
1658 	else
1659 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
1660 	ret = i40e_config_rss_aq(vsi, seed, lut, vsi->rss_table_size);
1661 	kfree(lut);
1662 	return ret;
1663 }
1664 
1665 /**
1666  * i40e_vsi_setup_queue_map_mqprio - Prepares mqprio based tc_config
1667  * @vsi: the VSI being configured,
1668  * @ctxt: VSI context structure
1669  * @enabled_tc: number of traffic classes to enable
1670  *
1671  * Prepares VSI tc_config to have queue configurations based on MQPRIO options.
1672  **/
1673 static int i40e_vsi_setup_queue_map_mqprio(struct i40e_vsi *vsi,
1674 					   struct i40e_vsi_context *ctxt,
1675 					   u8 enabled_tc)
1676 {
1677 	u16 qcount = 0, max_qcount, qmap, sections = 0;
1678 	int i, override_q, pow, num_qps, ret;
1679 	u8 netdev_tc = 0, offset = 0;
1680 
1681 	if (vsi->type != I40E_VSI_MAIN)
1682 		return -EINVAL;
1683 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1684 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1685 	vsi->tc_config.numtc = vsi->mqprio_qopt.qopt.num_tc;
1686 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1687 	num_qps = vsi->mqprio_qopt.qopt.count[0];
1688 
1689 	/* find the next higher power-of-2 of num queue pairs */
1690 	pow = ilog2(num_qps);
1691 	if (!is_power_of_2(num_qps))
1692 		pow++;
1693 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1694 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1695 
1696 	/* Setup queue offset/count for all TCs for given VSI */
1697 	max_qcount = vsi->mqprio_qopt.qopt.count[0];
1698 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1699 		/* See if the given TC is enabled for the given VSI */
1700 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1701 			offset = vsi->mqprio_qopt.qopt.offset[i];
1702 			qcount = vsi->mqprio_qopt.qopt.count[i];
1703 			if (qcount > max_qcount)
1704 				max_qcount = qcount;
1705 			vsi->tc_config.tc_info[i].qoffset = offset;
1706 			vsi->tc_config.tc_info[i].qcount = qcount;
1707 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1708 		} else {
1709 			/* TC is not enabled so set the offset to
1710 			 * default queue and allocate one queue
1711 			 * for the given TC.
1712 			 */
1713 			vsi->tc_config.tc_info[i].qoffset = 0;
1714 			vsi->tc_config.tc_info[i].qcount = 1;
1715 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1716 		}
1717 	}
1718 
1719 	/* Set actual Tx/Rx queue pairs */
1720 	vsi->num_queue_pairs = offset + qcount;
1721 
1722 	/* Setup queue TC[0].qmap for given VSI context */
1723 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
1724 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1725 	ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1726 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1727 
1728 	/* Reconfigure RSS for main VSI with max queue count */
1729 	vsi->rss_size = max_qcount;
1730 	ret = i40e_vsi_config_rss(vsi);
1731 	if (ret) {
1732 		dev_info(&vsi->back->pdev->dev,
1733 			 "Failed to reconfig rss for num_queues (%u)\n",
1734 			 max_qcount);
1735 		return ret;
1736 	}
1737 	vsi->reconfig_rss = true;
1738 	dev_dbg(&vsi->back->pdev->dev,
1739 		"Reconfigured rss with num_queues (%u)\n", max_qcount);
1740 
1741 	/* Find queue count available for channel VSIs and starting offset
1742 	 * for channel VSIs
1743 	 */
1744 	override_q = vsi->mqprio_qopt.qopt.count[0];
1745 	if (override_q && override_q < vsi->num_queue_pairs) {
1746 		vsi->cnt_q_avail = vsi->num_queue_pairs - override_q;
1747 		vsi->next_base_queue = override_q;
1748 	}
1749 	return 0;
1750 }
1751 
1752 /**
1753  * i40e_vsi_setup_queue_map - Setup a VSI queue map based on enabled_tc
1754  * @vsi: the VSI being setup
1755  * @ctxt: VSI context structure
1756  * @enabled_tc: Enabled TCs bitmap
1757  * @is_add: True if called before Add VSI
1758  *
1759  * Setup VSI queue mapping for enabled traffic classes.
1760  **/
1761 static void i40e_vsi_setup_queue_map(struct i40e_vsi *vsi,
1762 				     struct i40e_vsi_context *ctxt,
1763 				     u8 enabled_tc,
1764 				     bool is_add)
1765 {
1766 	struct i40e_pf *pf = vsi->back;
1767 	u16 sections = 0;
1768 	u8 netdev_tc = 0;
1769 	u16 numtc = 1;
1770 	u16 qcount;
1771 	u8 offset;
1772 	u16 qmap;
1773 	int i;
1774 	u16 num_tc_qps = 0;
1775 
1776 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
1777 	offset = 0;
1778 
1779 	/* Number of queues per enabled TC */
1780 	num_tc_qps = vsi->alloc_queue_pairs;
1781 	if (enabled_tc && (vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
1782 		/* Find numtc from enabled TC bitmap */
1783 		for (i = 0, numtc = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1784 			if (enabled_tc & BIT(i)) /* TC is enabled */
1785 				numtc++;
1786 		}
1787 		if (!numtc) {
1788 			dev_warn(&pf->pdev->dev, "DCB is enabled but no TC enabled, forcing TC0\n");
1789 			numtc = 1;
1790 		}
1791 		num_tc_qps = num_tc_qps / numtc;
1792 		num_tc_qps = min_t(int, num_tc_qps,
1793 				   i40e_pf_get_max_q_per_tc(pf));
1794 	}
1795 
1796 	vsi->tc_config.numtc = numtc;
1797 	vsi->tc_config.enabled_tc = enabled_tc ? enabled_tc : 1;
1798 
1799 	/* Do not allow use more TC queue pairs than MSI-X vectors exist */
1800 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1801 		num_tc_qps = min_t(int, num_tc_qps, pf->num_lan_msix);
1802 
1803 	/* Setup queue offset/count for all TCs for given VSI */
1804 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
1805 		/* See if the given TC is enabled for the given VSI */
1806 		if (vsi->tc_config.enabled_tc & BIT(i)) {
1807 			/* TC is enabled */
1808 			int pow, num_qps;
1809 
1810 			switch (vsi->type) {
1811 			case I40E_VSI_MAIN:
1812 				if (!(pf->flags & (I40E_FLAG_FD_SB_ENABLED |
1813 				    I40E_FLAG_FD_ATR_ENABLED)) ||
1814 				    vsi->tc_config.enabled_tc != 1) {
1815 					qcount = min_t(int, pf->alloc_rss_size,
1816 						       num_tc_qps);
1817 					break;
1818 				}
1819 				/* fall through */
1820 			case I40E_VSI_FDIR:
1821 			case I40E_VSI_SRIOV:
1822 			case I40E_VSI_VMDQ2:
1823 			default:
1824 				qcount = num_tc_qps;
1825 				WARN_ON(i != 0);
1826 				break;
1827 			}
1828 			vsi->tc_config.tc_info[i].qoffset = offset;
1829 			vsi->tc_config.tc_info[i].qcount = qcount;
1830 
1831 			/* find the next higher power-of-2 of num queue pairs */
1832 			num_qps = qcount;
1833 			pow = 0;
1834 			while (num_qps && (BIT_ULL(pow) < qcount)) {
1835 				pow++;
1836 				num_qps >>= 1;
1837 			}
1838 
1839 			vsi->tc_config.tc_info[i].netdev_tc = netdev_tc++;
1840 			qmap =
1841 			    (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
1842 			    (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
1843 
1844 			offset += qcount;
1845 		} else {
1846 			/* TC is not enabled so set the offset to
1847 			 * default queue and allocate one queue
1848 			 * for the given TC.
1849 			 */
1850 			vsi->tc_config.tc_info[i].qoffset = 0;
1851 			vsi->tc_config.tc_info[i].qcount = 1;
1852 			vsi->tc_config.tc_info[i].netdev_tc = 0;
1853 
1854 			qmap = 0;
1855 		}
1856 		ctxt->info.tc_mapping[i] = cpu_to_le16(qmap);
1857 	}
1858 
1859 	/* Set actual Tx/Rx queue pairs */
1860 	vsi->num_queue_pairs = offset;
1861 	if ((vsi->type == I40E_VSI_MAIN) && (numtc == 1)) {
1862 		if (vsi->req_queue_pairs > 0)
1863 			vsi->num_queue_pairs = vsi->req_queue_pairs;
1864 		else if (pf->flags & I40E_FLAG_MSIX_ENABLED)
1865 			vsi->num_queue_pairs = pf->num_lan_msix;
1866 	}
1867 
1868 	/* Scheduler section valid can only be set for ADD VSI */
1869 	if (is_add) {
1870 		sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
1871 
1872 		ctxt->info.up_enable_bits = enabled_tc;
1873 	}
1874 	if (vsi->type == I40E_VSI_SRIOV) {
1875 		ctxt->info.mapping_flags |=
1876 				     cpu_to_le16(I40E_AQ_VSI_QUE_MAP_NONCONTIG);
1877 		for (i = 0; i < vsi->num_queue_pairs; i++)
1878 			ctxt->info.queue_mapping[i] =
1879 					       cpu_to_le16(vsi->base_queue + i);
1880 	} else {
1881 		ctxt->info.mapping_flags |=
1882 					cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
1883 		ctxt->info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
1884 	}
1885 	ctxt->info.valid_sections |= cpu_to_le16(sections);
1886 }
1887 
1888 /**
1889  * i40e_addr_sync - Callback for dev_(mc|uc)_sync to add address
1890  * @netdev: the netdevice
1891  * @addr: address to add
1892  *
1893  * Called by __dev_(mc|uc)_sync when an address needs to be added. We call
1894  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
1895  */
1896 static int i40e_addr_sync(struct net_device *netdev, const u8 *addr)
1897 {
1898 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1899 	struct i40e_vsi *vsi = np->vsi;
1900 
1901 	if (i40e_add_mac_filter(vsi, addr))
1902 		return 0;
1903 	else
1904 		return -ENOMEM;
1905 }
1906 
1907 /**
1908  * i40e_addr_unsync - Callback for dev_(mc|uc)_sync to remove address
1909  * @netdev: the netdevice
1910  * @addr: address to add
1911  *
1912  * Called by __dev_(mc|uc)_sync when an address needs to be removed. We call
1913  * __dev_(uc|mc)_sync from .set_rx_mode and guarantee to hold the hash lock.
1914  */
1915 static int i40e_addr_unsync(struct net_device *netdev, const u8 *addr)
1916 {
1917 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1918 	struct i40e_vsi *vsi = np->vsi;
1919 
1920 	/* Under some circumstances, we might receive a request to delete
1921 	 * our own device address from our uc list. Because we store the
1922 	 * device address in the VSI's MAC/VLAN filter list, we need to ignore
1923 	 * such requests and not delete our device address from this list.
1924 	 */
1925 	if (ether_addr_equal(addr, netdev->dev_addr))
1926 		return 0;
1927 
1928 	i40e_del_mac_filter(vsi, addr);
1929 
1930 	return 0;
1931 }
1932 
1933 /**
1934  * i40e_set_rx_mode - NDO callback to set the netdev filters
1935  * @netdev: network interface device structure
1936  **/
1937 static void i40e_set_rx_mode(struct net_device *netdev)
1938 {
1939 	struct i40e_netdev_priv *np = netdev_priv(netdev);
1940 	struct i40e_vsi *vsi = np->vsi;
1941 
1942 	spin_lock_bh(&vsi->mac_filter_hash_lock);
1943 
1944 	__dev_uc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
1945 	__dev_mc_sync(netdev, i40e_addr_sync, i40e_addr_unsync);
1946 
1947 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
1948 
1949 	/* check for other flag changes */
1950 	if (vsi->current_netdev_flags != vsi->netdev->flags) {
1951 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
1952 		set_bit(__I40E_MACVLAN_SYNC_PENDING, vsi->back->state);
1953 	}
1954 }
1955 
1956 /**
1957  * i40e_undo_del_filter_entries - Undo the changes made to MAC filter entries
1958  * @vsi: Pointer to VSI struct
1959  * @from: Pointer to list which contains MAC filter entries - changes to
1960  *        those entries needs to be undone.
1961  *
1962  * MAC filter entries from this list were slated for deletion.
1963  **/
1964 static void i40e_undo_del_filter_entries(struct i40e_vsi *vsi,
1965 					 struct hlist_head *from)
1966 {
1967 	struct i40e_mac_filter *f;
1968 	struct hlist_node *h;
1969 
1970 	hlist_for_each_entry_safe(f, h, from, hlist) {
1971 		u64 key = i40e_addr_to_hkey(f->macaddr);
1972 
1973 		/* Move the element back into MAC filter list*/
1974 		hlist_del(&f->hlist);
1975 		hash_add(vsi->mac_filter_hash, &f->hlist, key);
1976 	}
1977 }
1978 
1979 /**
1980  * i40e_undo_add_filter_entries - Undo the changes made to MAC filter entries
1981  * @vsi: Pointer to vsi struct
1982  * @from: Pointer to list which contains MAC filter entries - changes to
1983  *        those entries needs to be undone.
1984  *
1985  * MAC filter entries from this list were slated for addition.
1986  **/
1987 static void i40e_undo_add_filter_entries(struct i40e_vsi *vsi,
1988 					 struct hlist_head *from)
1989 {
1990 	struct i40e_new_mac_filter *new;
1991 	struct hlist_node *h;
1992 
1993 	hlist_for_each_entry_safe(new, h, from, hlist) {
1994 		/* We can simply free the wrapper structure */
1995 		hlist_del(&new->hlist);
1996 		kfree(new);
1997 	}
1998 }
1999 
2000 /**
2001  * i40e_next_entry - Get the next non-broadcast filter from a list
2002  * @next: pointer to filter in list
2003  *
2004  * Returns the next non-broadcast filter in the list. Required so that we
2005  * ignore broadcast filters within the list, since these are not handled via
2006  * the normal firmware update path.
2007  */
2008 static
2009 struct i40e_new_mac_filter *i40e_next_filter(struct i40e_new_mac_filter *next)
2010 {
2011 	hlist_for_each_entry_continue(next, hlist) {
2012 		if (!is_broadcast_ether_addr(next->f->macaddr))
2013 			return next;
2014 	}
2015 
2016 	return NULL;
2017 }
2018 
2019 /**
2020  * i40e_update_filter_state - Update filter state based on return data
2021  * from firmware
2022  * @count: Number of filters added
2023  * @add_list: return data from fw
2024  * @add_head: pointer to first filter in current batch
2025  *
2026  * MAC filter entries from list were slated to be added to device. Returns
2027  * number of successful filters. Note that 0 does NOT mean success!
2028  **/
2029 static int
2030 i40e_update_filter_state(int count,
2031 			 struct i40e_aqc_add_macvlan_element_data *add_list,
2032 			 struct i40e_new_mac_filter *add_head)
2033 {
2034 	int retval = 0;
2035 	int i;
2036 
2037 	for (i = 0; i < count; i++) {
2038 		/* Always check status of each filter. We don't need to check
2039 		 * the firmware return status because we pre-set the filter
2040 		 * status to I40E_AQC_MM_ERR_NO_RES when sending the filter
2041 		 * request to the adminq. Thus, if it no longer matches then
2042 		 * we know the filter is active.
2043 		 */
2044 		if (add_list[i].match_method == I40E_AQC_MM_ERR_NO_RES) {
2045 			add_head->state = I40E_FILTER_FAILED;
2046 		} else {
2047 			add_head->state = I40E_FILTER_ACTIVE;
2048 			retval++;
2049 		}
2050 
2051 		add_head = i40e_next_filter(add_head);
2052 		if (!add_head)
2053 			break;
2054 	}
2055 
2056 	return retval;
2057 }
2058 
2059 /**
2060  * i40e_aqc_del_filters - Request firmware to delete a set of filters
2061  * @vsi: ptr to the VSI
2062  * @vsi_name: name to display in messages
2063  * @list: the list of filters to send to firmware
2064  * @num_del: the number of filters to delete
2065  * @retval: Set to -EIO on failure to delete
2066  *
2067  * Send a request to firmware via AdminQ to delete a set of filters. Uses
2068  * *retval instead of a return value so that success does not force ret_val to
2069  * be set to 0. This ensures that a sequence of calls to this function
2070  * preserve the previous value of *retval on successful delete.
2071  */
2072 static
2073 void i40e_aqc_del_filters(struct i40e_vsi *vsi, const char *vsi_name,
2074 			  struct i40e_aqc_remove_macvlan_element_data *list,
2075 			  int num_del, int *retval)
2076 {
2077 	struct i40e_hw *hw = &vsi->back->hw;
2078 	i40e_status aq_ret;
2079 	int aq_err;
2080 
2081 	aq_ret = i40e_aq_remove_macvlan(hw, vsi->seid, list, num_del, NULL);
2082 	aq_err = hw->aq.asq_last_status;
2083 
2084 	/* Explicitly ignore and do not report when firmware returns ENOENT */
2085 	if (aq_ret && !(aq_err == I40E_AQ_RC_ENOENT)) {
2086 		*retval = -EIO;
2087 		dev_info(&vsi->back->pdev->dev,
2088 			 "ignoring delete macvlan error on %s, err %s, aq_err %s\n",
2089 			 vsi_name, i40e_stat_str(hw, aq_ret),
2090 			 i40e_aq_str(hw, aq_err));
2091 	}
2092 }
2093 
2094 /**
2095  * i40e_aqc_add_filters - Request firmware to add a set of filters
2096  * @vsi: ptr to the VSI
2097  * @vsi_name: name to display in messages
2098  * @list: the list of filters to send to firmware
2099  * @add_head: Position in the add hlist
2100  * @num_add: the number of filters to add
2101  *
2102  * Send a request to firmware via AdminQ to add a chunk of filters. Will set
2103  * __I40E_VSI_OVERFLOW_PROMISC bit in vsi->state if the firmware has run out of
2104  * space for more filters.
2105  */
2106 static
2107 void i40e_aqc_add_filters(struct i40e_vsi *vsi, const char *vsi_name,
2108 			  struct i40e_aqc_add_macvlan_element_data *list,
2109 			  struct i40e_new_mac_filter *add_head,
2110 			  int num_add)
2111 {
2112 	struct i40e_hw *hw = &vsi->back->hw;
2113 	int aq_err, fcnt;
2114 
2115 	i40e_aq_add_macvlan(hw, vsi->seid, list, num_add, NULL);
2116 	aq_err = hw->aq.asq_last_status;
2117 	fcnt = i40e_update_filter_state(num_add, list, add_head);
2118 
2119 	if (fcnt != num_add) {
2120 		if (vsi->type == I40E_VSI_MAIN) {
2121 			set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2122 			dev_warn(&vsi->back->pdev->dev,
2123 				 "Error %s adding RX filters on %s, promiscuous mode forced on\n",
2124 				 i40e_aq_str(hw, aq_err), vsi_name);
2125 		} else if (vsi->type == I40E_VSI_SRIOV ||
2126 			   vsi->type == I40E_VSI_VMDQ1 ||
2127 			   vsi->type == I40E_VSI_VMDQ2) {
2128 			dev_warn(&vsi->back->pdev->dev,
2129 				 "Error %s adding RX filters on %s, please set promiscuous on manually for %s\n",
2130 				 i40e_aq_str(hw, aq_err), vsi_name, vsi_name);
2131 		} else {
2132 			dev_warn(&vsi->back->pdev->dev,
2133 				 "Error %s adding RX filters on %s, incorrect VSI type: %i.\n",
2134 				 i40e_aq_str(hw, aq_err), vsi_name, vsi->type);
2135 		}
2136 	}
2137 }
2138 
2139 /**
2140  * i40e_aqc_broadcast_filter - Set promiscuous broadcast flags
2141  * @vsi: pointer to the VSI
2142  * @vsi_name: the VSI name
2143  * @f: filter data
2144  *
2145  * This function sets or clears the promiscuous broadcast flags for VLAN
2146  * filters in order to properly receive broadcast frames. Assumes that only
2147  * broadcast filters are passed.
2148  *
2149  * Returns status indicating success or failure;
2150  **/
2151 static i40e_status
2152 i40e_aqc_broadcast_filter(struct i40e_vsi *vsi, const char *vsi_name,
2153 			  struct i40e_mac_filter *f)
2154 {
2155 	bool enable = f->state == I40E_FILTER_NEW;
2156 	struct i40e_hw *hw = &vsi->back->hw;
2157 	i40e_status aq_ret;
2158 
2159 	if (f->vlan == I40E_VLAN_ANY) {
2160 		aq_ret = i40e_aq_set_vsi_broadcast(hw,
2161 						   vsi->seid,
2162 						   enable,
2163 						   NULL);
2164 	} else {
2165 		aq_ret = i40e_aq_set_vsi_bc_promisc_on_vlan(hw,
2166 							    vsi->seid,
2167 							    enable,
2168 							    f->vlan,
2169 							    NULL);
2170 	}
2171 
2172 	if (aq_ret) {
2173 		set_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2174 		dev_warn(&vsi->back->pdev->dev,
2175 			 "Error %s, forcing overflow promiscuous on %s\n",
2176 			 i40e_aq_str(hw, hw->aq.asq_last_status),
2177 			 vsi_name);
2178 	}
2179 
2180 	return aq_ret;
2181 }
2182 
2183 /**
2184  * i40e_set_promiscuous - set promiscuous mode
2185  * @pf: board private structure
2186  * @promisc: promisc on or off
2187  *
2188  * There are different ways of setting promiscuous mode on a PF depending on
2189  * what state/environment we're in.  This identifies and sets it appropriately.
2190  * Returns 0 on success.
2191  **/
2192 static int i40e_set_promiscuous(struct i40e_pf *pf, bool promisc)
2193 {
2194 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
2195 	struct i40e_hw *hw = &pf->hw;
2196 	i40e_status aq_ret;
2197 
2198 	if (vsi->type == I40E_VSI_MAIN &&
2199 	    pf->lan_veb != I40E_NO_VEB &&
2200 	    !(pf->flags & I40E_FLAG_MFP_ENABLED)) {
2201 		/* set defport ON for Main VSI instead of true promisc
2202 		 * this way we will get all unicast/multicast and VLAN
2203 		 * promisc behavior but will not get VF or VMDq traffic
2204 		 * replicated on the Main VSI.
2205 		 */
2206 		if (promisc)
2207 			aq_ret = i40e_aq_set_default_vsi(hw,
2208 							 vsi->seid,
2209 							 NULL);
2210 		else
2211 			aq_ret = i40e_aq_clear_default_vsi(hw,
2212 							   vsi->seid,
2213 							   NULL);
2214 		if (aq_ret) {
2215 			dev_info(&pf->pdev->dev,
2216 				 "Set default VSI failed, err %s, aq_err %s\n",
2217 				 i40e_stat_str(hw, aq_ret),
2218 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2219 		}
2220 	} else {
2221 		aq_ret = i40e_aq_set_vsi_unicast_promiscuous(
2222 						  hw,
2223 						  vsi->seid,
2224 						  promisc, NULL,
2225 						  true);
2226 		if (aq_ret) {
2227 			dev_info(&pf->pdev->dev,
2228 				 "set unicast promisc failed, err %s, aq_err %s\n",
2229 				 i40e_stat_str(hw, aq_ret),
2230 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2231 		}
2232 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(
2233 						  hw,
2234 						  vsi->seid,
2235 						  promisc, NULL);
2236 		if (aq_ret) {
2237 			dev_info(&pf->pdev->dev,
2238 				 "set multicast promisc failed, err %s, aq_err %s\n",
2239 				 i40e_stat_str(hw, aq_ret),
2240 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2241 		}
2242 	}
2243 
2244 	if (!aq_ret)
2245 		pf->cur_promisc = promisc;
2246 
2247 	return aq_ret;
2248 }
2249 
2250 /**
2251  * i40e_sync_vsi_filters - Update the VSI filter list to the HW
2252  * @vsi: ptr to the VSI
2253  *
2254  * Push any outstanding VSI filter changes through the AdminQ.
2255  *
2256  * Returns 0 or error value
2257  **/
2258 int i40e_sync_vsi_filters(struct i40e_vsi *vsi)
2259 {
2260 	struct hlist_head tmp_add_list, tmp_del_list;
2261 	struct i40e_mac_filter *f;
2262 	struct i40e_new_mac_filter *new, *add_head = NULL;
2263 	struct i40e_hw *hw = &vsi->back->hw;
2264 	bool old_overflow, new_overflow;
2265 	unsigned int failed_filters = 0;
2266 	unsigned int vlan_filters = 0;
2267 	char vsi_name[16] = "PF";
2268 	int filter_list_len = 0;
2269 	i40e_status aq_ret = 0;
2270 	u32 changed_flags = 0;
2271 	struct hlist_node *h;
2272 	struct i40e_pf *pf;
2273 	int num_add = 0;
2274 	int num_del = 0;
2275 	int retval = 0;
2276 	u16 cmd_flags;
2277 	int list_size;
2278 	int bkt;
2279 
2280 	/* empty array typed pointers, kcalloc later */
2281 	struct i40e_aqc_add_macvlan_element_data *add_list;
2282 	struct i40e_aqc_remove_macvlan_element_data *del_list;
2283 
2284 	while (test_and_set_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state))
2285 		usleep_range(1000, 2000);
2286 	pf = vsi->back;
2287 
2288 	old_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2289 
2290 	if (vsi->netdev) {
2291 		changed_flags = vsi->current_netdev_flags ^ vsi->netdev->flags;
2292 		vsi->current_netdev_flags = vsi->netdev->flags;
2293 	}
2294 
2295 	INIT_HLIST_HEAD(&tmp_add_list);
2296 	INIT_HLIST_HEAD(&tmp_del_list);
2297 
2298 	if (vsi->type == I40E_VSI_SRIOV)
2299 		snprintf(vsi_name, sizeof(vsi_name) - 1, "VF %d", vsi->vf_id);
2300 	else if (vsi->type != I40E_VSI_MAIN)
2301 		snprintf(vsi_name, sizeof(vsi_name) - 1, "vsi %d", vsi->seid);
2302 
2303 	if (vsi->flags & I40E_VSI_FLAG_FILTER_CHANGED) {
2304 		vsi->flags &= ~I40E_VSI_FLAG_FILTER_CHANGED;
2305 
2306 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2307 		/* Create a list of filters to delete. */
2308 		hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2309 			if (f->state == I40E_FILTER_REMOVE) {
2310 				/* Move the element into temporary del_list */
2311 				hash_del(&f->hlist);
2312 				hlist_add_head(&f->hlist, &tmp_del_list);
2313 
2314 				/* Avoid counting removed filters */
2315 				continue;
2316 			}
2317 			if (f->state == I40E_FILTER_NEW) {
2318 				/* Create a temporary i40e_new_mac_filter */
2319 				new = kzalloc(sizeof(*new), GFP_ATOMIC);
2320 				if (!new)
2321 					goto err_no_memory_locked;
2322 
2323 				/* Store pointer to the real filter */
2324 				new->f = f;
2325 				new->state = f->state;
2326 
2327 				/* Add it to the hash list */
2328 				hlist_add_head(&new->hlist, &tmp_add_list);
2329 			}
2330 
2331 			/* Count the number of active (current and new) VLAN
2332 			 * filters we have now. Does not count filters which
2333 			 * are marked for deletion.
2334 			 */
2335 			if (f->vlan > 0)
2336 				vlan_filters++;
2337 		}
2338 
2339 		retval = i40e_correct_mac_vlan_filters(vsi,
2340 						       &tmp_add_list,
2341 						       &tmp_del_list,
2342 						       vlan_filters);
2343 		if (retval)
2344 			goto err_no_memory_locked;
2345 
2346 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2347 	}
2348 
2349 	/* Now process 'del_list' outside the lock */
2350 	if (!hlist_empty(&tmp_del_list)) {
2351 		filter_list_len = hw->aq.asq_buf_size /
2352 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2353 		list_size = filter_list_len *
2354 			    sizeof(struct i40e_aqc_remove_macvlan_element_data);
2355 		del_list = kzalloc(list_size, GFP_ATOMIC);
2356 		if (!del_list)
2357 			goto err_no_memory;
2358 
2359 		hlist_for_each_entry_safe(f, h, &tmp_del_list, hlist) {
2360 			cmd_flags = 0;
2361 
2362 			/* handle broadcast filters by updating the broadcast
2363 			 * promiscuous flag and release filter list.
2364 			 */
2365 			if (is_broadcast_ether_addr(f->macaddr)) {
2366 				i40e_aqc_broadcast_filter(vsi, vsi_name, f);
2367 
2368 				hlist_del(&f->hlist);
2369 				kfree(f);
2370 				continue;
2371 			}
2372 
2373 			/* add to delete list */
2374 			ether_addr_copy(del_list[num_del].mac_addr, f->macaddr);
2375 			if (f->vlan == I40E_VLAN_ANY) {
2376 				del_list[num_del].vlan_tag = 0;
2377 				cmd_flags |= I40E_AQC_MACVLAN_DEL_IGNORE_VLAN;
2378 			} else {
2379 				del_list[num_del].vlan_tag =
2380 					cpu_to_le16((u16)(f->vlan));
2381 			}
2382 
2383 			cmd_flags |= I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
2384 			del_list[num_del].flags = cmd_flags;
2385 			num_del++;
2386 
2387 			/* flush a full buffer */
2388 			if (num_del == filter_list_len) {
2389 				i40e_aqc_del_filters(vsi, vsi_name, del_list,
2390 						     num_del, &retval);
2391 				memset(del_list, 0, list_size);
2392 				num_del = 0;
2393 			}
2394 			/* Release memory for MAC filter entries which were
2395 			 * synced up with HW.
2396 			 */
2397 			hlist_del(&f->hlist);
2398 			kfree(f);
2399 		}
2400 
2401 		if (num_del) {
2402 			i40e_aqc_del_filters(vsi, vsi_name, del_list,
2403 					     num_del, &retval);
2404 		}
2405 
2406 		kfree(del_list);
2407 		del_list = NULL;
2408 	}
2409 
2410 	if (!hlist_empty(&tmp_add_list)) {
2411 		/* Do all the adds now. */
2412 		filter_list_len = hw->aq.asq_buf_size /
2413 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2414 		list_size = filter_list_len *
2415 			       sizeof(struct i40e_aqc_add_macvlan_element_data);
2416 		add_list = kzalloc(list_size, GFP_ATOMIC);
2417 		if (!add_list)
2418 			goto err_no_memory;
2419 
2420 		num_add = 0;
2421 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2422 			/* handle broadcast filters by updating the broadcast
2423 			 * promiscuous flag instead of adding a MAC filter.
2424 			 */
2425 			if (is_broadcast_ether_addr(new->f->macaddr)) {
2426 				if (i40e_aqc_broadcast_filter(vsi, vsi_name,
2427 							      new->f))
2428 					new->state = I40E_FILTER_FAILED;
2429 				else
2430 					new->state = I40E_FILTER_ACTIVE;
2431 				continue;
2432 			}
2433 
2434 			/* add to add array */
2435 			if (num_add == 0)
2436 				add_head = new;
2437 			cmd_flags = 0;
2438 			ether_addr_copy(add_list[num_add].mac_addr,
2439 					new->f->macaddr);
2440 			if (new->f->vlan == I40E_VLAN_ANY) {
2441 				add_list[num_add].vlan_tag = 0;
2442 				cmd_flags |= I40E_AQC_MACVLAN_ADD_IGNORE_VLAN;
2443 			} else {
2444 				add_list[num_add].vlan_tag =
2445 					cpu_to_le16((u16)(new->f->vlan));
2446 			}
2447 			add_list[num_add].queue_number = 0;
2448 			/* set invalid match method for later detection */
2449 			add_list[num_add].match_method = I40E_AQC_MM_ERR_NO_RES;
2450 			cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
2451 			add_list[num_add].flags = cpu_to_le16(cmd_flags);
2452 			num_add++;
2453 
2454 			/* flush a full buffer */
2455 			if (num_add == filter_list_len) {
2456 				i40e_aqc_add_filters(vsi, vsi_name, add_list,
2457 						     add_head, num_add);
2458 				memset(add_list, 0, list_size);
2459 				num_add = 0;
2460 			}
2461 		}
2462 		if (num_add) {
2463 			i40e_aqc_add_filters(vsi, vsi_name, add_list, add_head,
2464 					     num_add);
2465 		}
2466 		/* Now move all of the filters from the temp add list back to
2467 		 * the VSI's list.
2468 		 */
2469 		spin_lock_bh(&vsi->mac_filter_hash_lock);
2470 		hlist_for_each_entry_safe(new, h, &tmp_add_list, hlist) {
2471 			/* Only update the state if we're still NEW */
2472 			if (new->f->state == I40E_FILTER_NEW)
2473 				new->f->state = new->state;
2474 			hlist_del(&new->hlist);
2475 			kfree(new);
2476 		}
2477 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
2478 		kfree(add_list);
2479 		add_list = NULL;
2480 	}
2481 
2482 	/* Determine the number of active and failed filters. */
2483 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2484 	vsi->active_filters = 0;
2485 	hash_for_each(vsi->mac_filter_hash, bkt, f, hlist) {
2486 		if (f->state == I40E_FILTER_ACTIVE)
2487 			vsi->active_filters++;
2488 		else if (f->state == I40E_FILTER_FAILED)
2489 			failed_filters++;
2490 	}
2491 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2492 
2493 	/* Check if we are able to exit overflow promiscuous mode. We can
2494 	 * safely exit if we didn't just enter, we no longer have any failed
2495 	 * filters, and we have reduced filters below the threshold value.
2496 	 */
2497 	if (old_overflow && !failed_filters &&
2498 	    vsi->active_filters < vsi->promisc_threshold) {
2499 		dev_info(&pf->pdev->dev,
2500 			 "filter logjam cleared on %s, leaving overflow promiscuous mode\n",
2501 			 vsi_name);
2502 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2503 		vsi->promisc_threshold = 0;
2504 	}
2505 
2506 	/* if the VF is not trusted do not do promisc */
2507 	if ((vsi->type == I40E_VSI_SRIOV) && !pf->vf[vsi->vf_id].trusted) {
2508 		clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2509 		goto out;
2510 	}
2511 
2512 	new_overflow = test_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
2513 
2514 	/* If we are entering overflow promiscuous, we need to calculate a new
2515 	 * threshold for when we are safe to exit
2516 	 */
2517 	if (!old_overflow && new_overflow)
2518 		vsi->promisc_threshold = (vsi->active_filters * 3) / 4;
2519 
2520 	/* check for changes in promiscuous modes */
2521 	if (changed_flags & IFF_ALLMULTI) {
2522 		bool cur_multipromisc;
2523 
2524 		cur_multipromisc = !!(vsi->current_netdev_flags & IFF_ALLMULTI);
2525 		aq_ret = i40e_aq_set_vsi_multicast_promiscuous(&vsi->back->hw,
2526 							       vsi->seid,
2527 							       cur_multipromisc,
2528 							       NULL);
2529 		if (aq_ret) {
2530 			retval = i40e_aq_rc_to_posix(aq_ret,
2531 						     hw->aq.asq_last_status);
2532 			dev_info(&pf->pdev->dev,
2533 				 "set multi promisc failed on %s, err %s aq_err %s\n",
2534 				 vsi_name,
2535 				 i40e_stat_str(hw, aq_ret),
2536 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2537 		} else {
2538 			dev_info(&pf->pdev->dev, "%s is %s allmulti mode.\n",
2539 				 vsi->netdev->name,
2540 				 cur_multipromisc ? "entering" : "leaving");
2541 		}
2542 	}
2543 
2544 	if ((changed_flags & IFF_PROMISC) || old_overflow != new_overflow) {
2545 		bool cur_promisc;
2546 
2547 		cur_promisc = (!!(vsi->current_netdev_flags & IFF_PROMISC) ||
2548 			       new_overflow);
2549 		aq_ret = i40e_set_promiscuous(pf, cur_promisc);
2550 		if (aq_ret) {
2551 			retval = i40e_aq_rc_to_posix(aq_ret,
2552 						     hw->aq.asq_last_status);
2553 			dev_info(&pf->pdev->dev,
2554 				 "Setting promiscuous %s failed on %s, err %s aq_err %s\n",
2555 				 cur_promisc ? "on" : "off",
2556 				 vsi_name,
2557 				 i40e_stat_str(hw, aq_ret),
2558 				 i40e_aq_str(hw, hw->aq.asq_last_status));
2559 		}
2560 	}
2561 out:
2562 	/* if something went wrong then set the changed flag so we try again */
2563 	if (retval)
2564 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2565 
2566 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2567 	return retval;
2568 
2569 err_no_memory:
2570 	/* Restore elements on the temporary add and delete lists */
2571 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2572 err_no_memory_locked:
2573 	i40e_undo_del_filter_entries(vsi, &tmp_del_list);
2574 	i40e_undo_add_filter_entries(vsi, &tmp_add_list);
2575 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2576 
2577 	vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
2578 	clear_bit(__I40E_VSI_SYNCING_FILTERS, vsi->state);
2579 	return -ENOMEM;
2580 }
2581 
2582 /**
2583  * i40e_sync_filters_subtask - Sync the VSI filter list with HW
2584  * @pf: board private structure
2585  **/
2586 static void i40e_sync_filters_subtask(struct i40e_pf *pf)
2587 {
2588 	int v;
2589 
2590 	if (!pf)
2591 		return;
2592 	if (!test_and_clear_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state))
2593 		return;
2594 
2595 	for (v = 0; v < pf->num_alloc_vsi; v++) {
2596 		if (pf->vsi[v] &&
2597 		    (pf->vsi[v]->flags & I40E_VSI_FLAG_FILTER_CHANGED)) {
2598 			int ret = i40e_sync_vsi_filters(pf->vsi[v]);
2599 
2600 			if (ret) {
2601 				/* come back and try again later */
2602 				set_bit(__I40E_MACVLAN_SYNC_PENDING,
2603 					pf->state);
2604 				break;
2605 			}
2606 		}
2607 	}
2608 }
2609 
2610 /**
2611  * i40e_max_xdp_frame_size - returns the maximum allowed frame size for XDP
2612  * @vsi: the vsi
2613  **/
2614 static int i40e_max_xdp_frame_size(struct i40e_vsi *vsi)
2615 {
2616 	if (PAGE_SIZE >= 8192 || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
2617 		return I40E_RXBUFFER_2048;
2618 	else
2619 		return I40E_RXBUFFER_3072;
2620 }
2621 
2622 /**
2623  * i40e_change_mtu - NDO callback to change the Maximum Transfer Unit
2624  * @netdev: network interface device structure
2625  * @new_mtu: new value for maximum frame size
2626  *
2627  * Returns 0 on success, negative on failure
2628  **/
2629 static int i40e_change_mtu(struct net_device *netdev, int new_mtu)
2630 {
2631 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2632 	struct i40e_vsi *vsi = np->vsi;
2633 	struct i40e_pf *pf = vsi->back;
2634 
2635 	if (i40e_enabled_xdp_vsi(vsi)) {
2636 		int frame_size = new_mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
2637 
2638 		if (frame_size > i40e_max_xdp_frame_size(vsi))
2639 			return -EINVAL;
2640 	}
2641 
2642 	netdev_info(netdev, "changing MTU from %d to %d\n",
2643 		    netdev->mtu, new_mtu);
2644 	netdev->mtu = new_mtu;
2645 	if (netif_running(netdev))
2646 		i40e_vsi_reinit_locked(vsi);
2647 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
2648 	set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
2649 	return 0;
2650 }
2651 
2652 /**
2653  * i40e_ioctl - Access the hwtstamp interface
2654  * @netdev: network interface device structure
2655  * @ifr: interface request data
2656  * @cmd: ioctl command
2657  **/
2658 int i40e_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
2659 {
2660 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2661 	struct i40e_pf *pf = np->vsi->back;
2662 
2663 	switch (cmd) {
2664 	case SIOCGHWTSTAMP:
2665 		return i40e_ptp_get_ts_config(pf, ifr);
2666 	case SIOCSHWTSTAMP:
2667 		return i40e_ptp_set_ts_config(pf, ifr);
2668 	default:
2669 		return -EOPNOTSUPP;
2670 	}
2671 }
2672 
2673 /**
2674  * i40e_vlan_stripping_enable - Turn on vlan stripping for the VSI
2675  * @vsi: the vsi being adjusted
2676  **/
2677 void i40e_vlan_stripping_enable(struct i40e_vsi *vsi)
2678 {
2679 	struct i40e_vsi_context ctxt;
2680 	i40e_status ret;
2681 
2682 	/* Don't modify stripping options if a port VLAN is active */
2683 	if (vsi->info.pvid)
2684 		return;
2685 
2686 	if ((vsi->info.valid_sections &
2687 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2688 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_MODE_MASK) == 0))
2689 		return;  /* already enabled */
2690 
2691 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2692 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2693 				    I40E_AQ_VSI_PVLAN_EMOD_STR_BOTH;
2694 
2695 	ctxt.seid = vsi->seid;
2696 	ctxt.info = vsi->info;
2697 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2698 	if (ret) {
2699 		dev_info(&vsi->back->pdev->dev,
2700 			 "update vlan stripping failed, err %s aq_err %s\n",
2701 			 i40e_stat_str(&vsi->back->hw, ret),
2702 			 i40e_aq_str(&vsi->back->hw,
2703 				     vsi->back->hw.aq.asq_last_status));
2704 	}
2705 }
2706 
2707 /**
2708  * i40e_vlan_stripping_disable - Turn off vlan stripping for the VSI
2709  * @vsi: the vsi being adjusted
2710  **/
2711 void i40e_vlan_stripping_disable(struct i40e_vsi *vsi)
2712 {
2713 	struct i40e_vsi_context ctxt;
2714 	i40e_status ret;
2715 
2716 	/* Don't modify stripping options if a port VLAN is active */
2717 	if (vsi->info.pvid)
2718 		return;
2719 
2720 	if ((vsi->info.valid_sections &
2721 	     cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID)) &&
2722 	    ((vsi->info.port_vlan_flags & I40E_AQ_VSI_PVLAN_EMOD_MASK) ==
2723 	     I40E_AQ_VSI_PVLAN_EMOD_MASK))
2724 		return;  /* already disabled */
2725 
2726 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2727 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_ALL |
2728 				    I40E_AQ_VSI_PVLAN_EMOD_NOTHING;
2729 
2730 	ctxt.seid = vsi->seid;
2731 	ctxt.info = vsi->info;
2732 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2733 	if (ret) {
2734 		dev_info(&vsi->back->pdev->dev,
2735 			 "update vlan stripping failed, err %s aq_err %s\n",
2736 			 i40e_stat_str(&vsi->back->hw, ret),
2737 			 i40e_aq_str(&vsi->back->hw,
2738 				     vsi->back->hw.aq.asq_last_status));
2739 	}
2740 }
2741 
2742 /**
2743  * i40e_add_vlan_all_mac - Add a MAC/VLAN filter for each existing MAC address
2744  * @vsi: the vsi being configured
2745  * @vid: vlan id to be added (0 = untagged only , -1 = any)
2746  *
2747  * This is a helper function for adding a new MAC/VLAN filter with the
2748  * specified VLAN for each existing MAC address already in the hash table.
2749  * This function does *not* perform any accounting to update filters based on
2750  * VLAN mode.
2751  *
2752  * NOTE: this function expects to be called while under the
2753  * mac_filter_hash_lock
2754  **/
2755 int i40e_add_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2756 {
2757 	struct i40e_mac_filter *f, *add_f;
2758 	struct hlist_node *h;
2759 	int bkt;
2760 
2761 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2762 		if (f->state == I40E_FILTER_REMOVE)
2763 			continue;
2764 		add_f = i40e_add_filter(vsi, f->macaddr, vid);
2765 		if (!add_f) {
2766 			dev_info(&vsi->back->pdev->dev,
2767 				 "Could not add vlan filter %d for %pM\n",
2768 				 vid, f->macaddr);
2769 			return -ENOMEM;
2770 		}
2771 	}
2772 
2773 	return 0;
2774 }
2775 
2776 /**
2777  * i40e_vsi_add_vlan - Add VSI membership for given VLAN
2778  * @vsi: the VSI being configured
2779  * @vid: VLAN id to be added
2780  **/
2781 int i40e_vsi_add_vlan(struct i40e_vsi *vsi, u16 vid)
2782 {
2783 	int err;
2784 
2785 	if (vsi->info.pvid)
2786 		return -EINVAL;
2787 
2788 	/* The network stack will attempt to add VID=0, with the intention to
2789 	 * receive priority tagged packets with a VLAN of 0. Our HW receives
2790 	 * these packets by default when configured to receive untagged
2791 	 * packets, so we don't need to add a filter for this case.
2792 	 * Additionally, HW interprets adding a VID=0 filter as meaning to
2793 	 * receive *only* tagged traffic and stops receiving untagged traffic.
2794 	 * Thus, we do not want to actually add a filter for VID=0
2795 	 */
2796 	if (!vid)
2797 		return 0;
2798 
2799 	/* Locked once because all functions invoked below iterates list*/
2800 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2801 	err = i40e_add_vlan_all_mac(vsi, vid);
2802 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2803 	if (err)
2804 		return err;
2805 
2806 	/* schedule our worker thread which will take care of
2807 	 * applying the new filter changes
2808 	 */
2809 	i40e_service_event_schedule(vsi->back);
2810 	return 0;
2811 }
2812 
2813 /**
2814  * i40e_rm_vlan_all_mac - Remove MAC/VLAN pair for all MAC with the given VLAN
2815  * @vsi: the vsi being configured
2816  * @vid: vlan id to be removed (0 = untagged only , -1 = any)
2817  *
2818  * This function should be used to remove all VLAN filters which match the
2819  * given VID. It does not schedule the service event and does not take the
2820  * mac_filter_hash_lock so it may be combined with other operations under
2821  * a single invocation of the mac_filter_hash_lock.
2822  *
2823  * NOTE: this function expects to be called while under the
2824  * mac_filter_hash_lock
2825  */
2826 void i40e_rm_vlan_all_mac(struct i40e_vsi *vsi, s16 vid)
2827 {
2828 	struct i40e_mac_filter *f;
2829 	struct hlist_node *h;
2830 	int bkt;
2831 
2832 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
2833 		if (f->vlan == vid)
2834 			__i40e_del_filter(vsi, f);
2835 	}
2836 }
2837 
2838 /**
2839  * i40e_vsi_kill_vlan - Remove VSI membership for given VLAN
2840  * @vsi: the VSI being configured
2841  * @vid: VLAN id to be removed
2842  **/
2843 void i40e_vsi_kill_vlan(struct i40e_vsi *vsi, u16 vid)
2844 {
2845 	if (!vid || vsi->info.pvid)
2846 		return;
2847 
2848 	spin_lock_bh(&vsi->mac_filter_hash_lock);
2849 	i40e_rm_vlan_all_mac(vsi, vid);
2850 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
2851 
2852 	/* schedule our worker thread which will take care of
2853 	 * applying the new filter changes
2854 	 */
2855 	i40e_service_event_schedule(vsi->back);
2856 }
2857 
2858 /**
2859  * i40e_vlan_rx_add_vid - Add a vlan id filter to HW offload
2860  * @netdev: network interface to be adjusted
2861  * @proto: unused protocol value
2862  * @vid: vlan id to be added
2863  *
2864  * net_device_ops implementation for adding vlan ids
2865  **/
2866 static int i40e_vlan_rx_add_vid(struct net_device *netdev,
2867 				__always_unused __be16 proto, u16 vid)
2868 {
2869 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2870 	struct i40e_vsi *vsi = np->vsi;
2871 	int ret = 0;
2872 
2873 	if (vid >= VLAN_N_VID)
2874 		return -EINVAL;
2875 
2876 	ret = i40e_vsi_add_vlan(vsi, vid);
2877 	if (!ret)
2878 		set_bit(vid, vsi->active_vlans);
2879 
2880 	return ret;
2881 }
2882 
2883 /**
2884  * i40e_vlan_rx_add_vid_up - Add a vlan id filter to HW offload in UP path
2885  * @netdev: network interface to be adjusted
2886  * @proto: unused protocol value
2887  * @vid: vlan id to be added
2888  **/
2889 static void i40e_vlan_rx_add_vid_up(struct net_device *netdev,
2890 				    __always_unused __be16 proto, u16 vid)
2891 {
2892 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2893 	struct i40e_vsi *vsi = np->vsi;
2894 
2895 	if (vid >= VLAN_N_VID)
2896 		return;
2897 	set_bit(vid, vsi->active_vlans);
2898 }
2899 
2900 /**
2901  * i40e_vlan_rx_kill_vid - Remove a vlan id filter from HW offload
2902  * @netdev: network interface to be adjusted
2903  * @proto: unused protocol value
2904  * @vid: vlan id to be removed
2905  *
2906  * net_device_ops implementation for removing vlan ids
2907  **/
2908 static int i40e_vlan_rx_kill_vid(struct net_device *netdev,
2909 				 __always_unused __be16 proto, u16 vid)
2910 {
2911 	struct i40e_netdev_priv *np = netdev_priv(netdev);
2912 	struct i40e_vsi *vsi = np->vsi;
2913 
2914 	/* return code is ignored as there is nothing a user
2915 	 * can do about failure to remove and a log message was
2916 	 * already printed from the other function
2917 	 */
2918 	i40e_vsi_kill_vlan(vsi, vid);
2919 
2920 	clear_bit(vid, vsi->active_vlans);
2921 
2922 	return 0;
2923 }
2924 
2925 /**
2926  * i40e_restore_vlan - Reinstate vlans when vsi/netdev comes back up
2927  * @vsi: the vsi being brought back up
2928  **/
2929 static void i40e_restore_vlan(struct i40e_vsi *vsi)
2930 {
2931 	u16 vid;
2932 
2933 	if (!vsi->netdev)
2934 		return;
2935 
2936 	if (vsi->netdev->features & NETIF_F_HW_VLAN_CTAG_RX)
2937 		i40e_vlan_stripping_enable(vsi);
2938 	else
2939 		i40e_vlan_stripping_disable(vsi);
2940 
2941 	for_each_set_bit(vid, vsi->active_vlans, VLAN_N_VID)
2942 		i40e_vlan_rx_add_vid_up(vsi->netdev, htons(ETH_P_8021Q),
2943 					vid);
2944 }
2945 
2946 /**
2947  * i40e_vsi_add_pvid - Add pvid for the VSI
2948  * @vsi: the vsi being adjusted
2949  * @vid: the vlan id to set as a PVID
2950  **/
2951 int i40e_vsi_add_pvid(struct i40e_vsi *vsi, u16 vid)
2952 {
2953 	struct i40e_vsi_context ctxt;
2954 	i40e_status ret;
2955 
2956 	vsi->info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
2957 	vsi->info.pvid = cpu_to_le16(vid);
2958 	vsi->info.port_vlan_flags = I40E_AQ_VSI_PVLAN_MODE_TAGGED |
2959 				    I40E_AQ_VSI_PVLAN_INSERT_PVID |
2960 				    I40E_AQ_VSI_PVLAN_EMOD_STR;
2961 
2962 	ctxt.seid = vsi->seid;
2963 	ctxt.info = vsi->info;
2964 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
2965 	if (ret) {
2966 		dev_info(&vsi->back->pdev->dev,
2967 			 "add pvid failed, err %s aq_err %s\n",
2968 			 i40e_stat_str(&vsi->back->hw, ret),
2969 			 i40e_aq_str(&vsi->back->hw,
2970 				     vsi->back->hw.aq.asq_last_status));
2971 		return -ENOENT;
2972 	}
2973 
2974 	return 0;
2975 }
2976 
2977 /**
2978  * i40e_vsi_remove_pvid - Remove the pvid from the VSI
2979  * @vsi: the vsi being adjusted
2980  *
2981  * Just use the vlan_rx_register() service to put it back to normal
2982  **/
2983 void i40e_vsi_remove_pvid(struct i40e_vsi *vsi)
2984 {
2985 	vsi->info.pvid = 0;
2986 
2987 	i40e_vlan_stripping_disable(vsi);
2988 }
2989 
2990 /**
2991  * i40e_vsi_setup_tx_resources - Allocate VSI Tx queue resources
2992  * @vsi: ptr to the VSI
2993  *
2994  * If this function returns with an error, then it's possible one or
2995  * more of the rings is populated (while the rest are not).  It is the
2996  * callers duty to clean those orphaned rings.
2997  *
2998  * Return 0 on success, negative on failure
2999  **/
3000 static int i40e_vsi_setup_tx_resources(struct i40e_vsi *vsi)
3001 {
3002 	int i, err = 0;
3003 
3004 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3005 		err = i40e_setup_tx_descriptors(vsi->tx_rings[i]);
3006 
3007 	if (!i40e_enabled_xdp_vsi(vsi))
3008 		return err;
3009 
3010 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3011 		err = i40e_setup_tx_descriptors(vsi->xdp_rings[i]);
3012 
3013 	return err;
3014 }
3015 
3016 /**
3017  * i40e_vsi_free_tx_resources - Free Tx resources for VSI queues
3018  * @vsi: ptr to the VSI
3019  *
3020  * Free VSI's transmit software resources
3021  **/
3022 static void i40e_vsi_free_tx_resources(struct i40e_vsi *vsi)
3023 {
3024 	int i;
3025 
3026 	if (vsi->tx_rings) {
3027 		for (i = 0; i < vsi->num_queue_pairs; i++)
3028 			if (vsi->tx_rings[i] && vsi->tx_rings[i]->desc)
3029 				i40e_free_tx_resources(vsi->tx_rings[i]);
3030 	}
3031 
3032 	if (vsi->xdp_rings) {
3033 		for (i = 0; i < vsi->num_queue_pairs; i++)
3034 			if (vsi->xdp_rings[i] && vsi->xdp_rings[i]->desc)
3035 				i40e_free_tx_resources(vsi->xdp_rings[i]);
3036 	}
3037 }
3038 
3039 /**
3040  * i40e_vsi_setup_rx_resources - Allocate VSI queues Rx resources
3041  * @vsi: ptr to the VSI
3042  *
3043  * If this function returns with an error, then it's possible one or
3044  * more of the rings is populated (while the rest are not).  It is the
3045  * callers duty to clean those orphaned rings.
3046  *
3047  * Return 0 on success, negative on failure
3048  **/
3049 static int i40e_vsi_setup_rx_resources(struct i40e_vsi *vsi)
3050 {
3051 	int i, err = 0;
3052 
3053 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3054 		err = i40e_setup_rx_descriptors(vsi->rx_rings[i]);
3055 	return err;
3056 }
3057 
3058 /**
3059  * i40e_vsi_free_rx_resources - Free Rx Resources for VSI queues
3060  * @vsi: ptr to the VSI
3061  *
3062  * Free all receive software resources
3063  **/
3064 static void i40e_vsi_free_rx_resources(struct i40e_vsi *vsi)
3065 {
3066 	int i;
3067 
3068 	if (!vsi->rx_rings)
3069 		return;
3070 
3071 	for (i = 0; i < vsi->num_queue_pairs; i++)
3072 		if (vsi->rx_rings[i] && vsi->rx_rings[i]->desc)
3073 			i40e_free_rx_resources(vsi->rx_rings[i]);
3074 }
3075 
3076 /**
3077  * i40e_config_xps_tx_ring - Configure XPS for a Tx ring
3078  * @ring: The Tx ring to configure
3079  *
3080  * This enables/disables XPS for a given Tx descriptor ring
3081  * based on the TCs enabled for the VSI that ring belongs to.
3082  **/
3083 static void i40e_config_xps_tx_ring(struct i40e_ring *ring)
3084 {
3085 	int cpu;
3086 
3087 	if (!ring->q_vector || !ring->netdev || ring->ch)
3088 		return;
3089 
3090 	/* We only initialize XPS once, so as not to overwrite user settings */
3091 	if (test_and_set_bit(__I40E_TX_XPS_INIT_DONE, ring->state))
3092 		return;
3093 
3094 	cpu = cpumask_local_spread(ring->q_vector->v_idx, -1);
3095 	netif_set_xps_queue(ring->netdev, get_cpu_mask(cpu),
3096 			    ring->queue_index);
3097 }
3098 
3099 /**
3100  * i40e_xsk_umem - Retrieve the AF_XDP ZC if XDP and ZC is enabled
3101  * @ring: The Tx or Rx ring
3102  *
3103  * Returns the UMEM or NULL.
3104  **/
3105 static struct xdp_umem *i40e_xsk_umem(struct i40e_ring *ring)
3106 {
3107 	bool xdp_on = i40e_enabled_xdp_vsi(ring->vsi);
3108 	int qid = ring->queue_index;
3109 
3110 	if (ring_is_xdp(ring))
3111 		qid -= ring->vsi->alloc_queue_pairs;
3112 
3113 	if (!xdp_on || !test_bit(qid, ring->vsi->af_xdp_zc_qps))
3114 		return NULL;
3115 
3116 	return xdp_get_umem_from_qid(ring->vsi->netdev, qid);
3117 }
3118 
3119 /**
3120  * i40e_configure_tx_ring - Configure a transmit ring context and rest
3121  * @ring: The Tx ring to configure
3122  *
3123  * Configure the Tx descriptor ring in the HMC context.
3124  **/
3125 static int i40e_configure_tx_ring(struct i40e_ring *ring)
3126 {
3127 	struct i40e_vsi *vsi = ring->vsi;
3128 	u16 pf_q = vsi->base_queue + ring->queue_index;
3129 	struct i40e_hw *hw = &vsi->back->hw;
3130 	struct i40e_hmc_obj_txq tx_ctx;
3131 	i40e_status err = 0;
3132 	u32 qtx_ctl = 0;
3133 
3134 	if (ring_is_xdp(ring))
3135 		ring->xsk_umem = i40e_xsk_umem(ring);
3136 
3137 	/* some ATR related tx ring init */
3138 	if (vsi->back->flags & I40E_FLAG_FD_ATR_ENABLED) {
3139 		ring->atr_sample_rate = vsi->back->atr_sample_rate;
3140 		ring->atr_count = 0;
3141 	} else {
3142 		ring->atr_sample_rate = 0;
3143 	}
3144 
3145 	/* configure XPS */
3146 	i40e_config_xps_tx_ring(ring);
3147 
3148 	/* clear the context structure first */
3149 	memset(&tx_ctx, 0, sizeof(tx_ctx));
3150 
3151 	tx_ctx.new_context = 1;
3152 	tx_ctx.base = (ring->dma / 128);
3153 	tx_ctx.qlen = ring->count;
3154 	tx_ctx.fd_ena = !!(vsi->back->flags & (I40E_FLAG_FD_SB_ENABLED |
3155 					       I40E_FLAG_FD_ATR_ENABLED));
3156 	tx_ctx.timesync_ena = !!(vsi->back->flags & I40E_FLAG_PTP);
3157 	/* FDIR VSI tx ring can still use RS bit and writebacks */
3158 	if (vsi->type != I40E_VSI_FDIR)
3159 		tx_ctx.head_wb_ena = 1;
3160 	tx_ctx.head_wb_addr = ring->dma +
3161 			      (ring->count * sizeof(struct i40e_tx_desc));
3162 
3163 	/* As part of VSI creation/update, FW allocates certain
3164 	 * Tx arbitration queue sets for each TC enabled for
3165 	 * the VSI. The FW returns the handles to these queue
3166 	 * sets as part of the response buffer to Add VSI,
3167 	 * Update VSI, etc. AQ commands. It is expected that
3168 	 * these queue set handles be associated with the Tx
3169 	 * queues by the driver as part of the TX queue context
3170 	 * initialization. This has to be done regardless of
3171 	 * DCB as by default everything is mapped to TC0.
3172 	 */
3173 
3174 	if (ring->ch)
3175 		tx_ctx.rdylist =
3176 			le16_to_cpu(ring->ch->info.qs_handle[ring->dcb_tc]);
3177 
3178 	else
3179 		tx_ctx.rdylist = le16_to_cpu(vsi->info.qs_handle[ring->dcb_tc]);
3180 
3181 	tx_ctx.rdylist_act = 0;
3182 
3183 	/* clear the context in the HMC */
3184 	err = i40e_clear_lan_tx_queue_context(hw, pf_q);
3185 	if (err) {
3186 		dev_info(&vsi->back->pdev->dev,
3187 			 "Failed to clear LAN Tx queue context on Tx ring %d (pf_q %d), error: %d\n",
3188 			 ring->queue_index, pf_q, err);
3189 		return -ENOMEM;
3190 	}
3191 
3192 	/* set the context in the HMC */
3193 	err = i40e_set_lan_tx_queue_context(hw, pf_q, &tx_ctx);
3194 	if (err) {
3195 		dev_info(&vsi->back->pdev->dev,
3196 			 "Failed to set LAN Tx queue context on Tx ring %d (pf_q %d, error: %d\n",
3197 			 ring->queue_index, pf_q, err);
3198 		return -ENOMEM;
3199 	}
3200 
3201 	/* Now associate this queue with this PCI function */
3202 	if (ring->ch) {
3203 		if (ring->ch->type == I40E_VSI_VMDQ2)
3204 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3205 		else
3206 			return -EINVAL;
3207 
3208 		qtx_ctl |= (ring->ch->vsi_number <<
3209 			    I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3210 			    I40E_QTX_CTL_VFVM_INDX_MASK;
3211 	} else {
3212 		if (vsi->type == I40E_VSI_VMDQ2) {
3213 			qtx_ctl = I40E_QTX_CTL_VM_QUEUE;
3214 			qtx_ctl |= ((vsi->id) << I40E_QTX_CTL_VFVM_INDX_SHIFT) &
3215 				    I40E_QTX_CTL_VFVM_INDX_MASK;
3216 		} else {
3217 			qtx_ctl = I40E_QTX_CTL_PF_QUEUE;
3218 		}
3219 	}
3220 
3221 	qtx_ctl |= ((hw->pf_id << I40E_QTX_CTL_PF_INDX_SHIFT) &
3222 		    I40E_QTX_CTL_PF_INDX_MASK);
3223 	wr32(hw, I40E_QTX_CTL(pf_q), qtx_ctl);
3224 	i40e_flush(hw);
3225 
3226 	/* cache tail off for easier writes later */
3227 	ring->tail = hw->hw_addr + I40E_QTX_TAIL(pf_q);
3228 
3229 	return 0;
3230 }
3231 
3232 /**
3233  * i40e_configure_rx_ring - Configure a receive ring context
3234  * @ring: The Rx ring to configure
3235  *
3236  * Configure the Rx descriptor ring in the HMC context.
3237  **/
3238 static int i40e_configure_rx_ring(struct i40e_ring *ring)
3239 {
3240 	struct i40e_vsi *vsi = ring->vsi;
3241 	u32 chain_len = vsi->back->hw.func_caps.rx_buf_chain_len;
3242 	u16 pf_q = vsi->base_queue + ring->queue_index;
3243 	struct i40e_hw *hw = &vsi->back->hw;
3244 	struct i40e_hmc_obj_rxq rx_ctx;
3245 	i40e_status err = 0;
3246 	bool ok;
3247 	int ret;
3248 
3249 	bitmap_zero(ring->state, __I40E_RING_STATE_NBITS);
3250 
3251 	/* clear the context structure first */
3252 	memset(&rx_ctx, 0, sizeof(rx_ctx));
3253 
3254 	if (ring->vsi->type == I40E_VSI_MAIN)
3255 		xdp_rxq_info_unreg_mem_model(&ring->xdp_rxq);
3256 
3257 	ring->xsk_umem = i40e_xsk_umem(ring);
3258 	if (ring->xsk_umem) {
3259 		ring->rx_buf_len = ring->xsk_umem->chunk_size_nohr -
3260 				   XDP_PACKET_HEADROOM;
3261 		/* For AF_XDP ZC, we disallow packets to span on
3262 		 * multiple buffers, thus letting us skip that
3263 		 * handling in the fast-path.
3264 		 */
3265 		chain_len = 1;
3266 		ring->zca.free = i40e_zca_free;
3267 		ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3268 						 MEM_TYPE_ZERO_COPY,
3269 						 &ring->zca);
3270 		if (ret)
3271 			return ret;
3272 		dev_info(&vsi->back->pdev->dev,
3273 			 "Registered XDP mem model MEM_TYPE_ZERO_COPY on Rx ring %d\n",
3274 			 ring->queue_index);
3275 
3276 	} else {
3277 		ring->rx_buf_len = vsi->rx_buf_len;
3278 		if (ring->vsi->type == I40E_VSI_MAIN) {
3279 			ret = xdp_rxq_info_reg_mem_model(&ring->xdp_rxq,
3280 							 MEM_TYPE_PAGE_SHARED,
3281 							 NULL);
3282 			if (ret)
3283 				return ret;
3284 		}
3285 	}
3286 
3287 	rx_ctx.dbuff = DIV_ROUND_UP(ring->rx_buf_len,
3288 				    BIT_ULL(I40E_RXQ_CTX_DBUFF_SHIFT));
3289 
3290 	rx_ctx.base = (ring->dma / 128);
3291 	rx_ctx.qlen = ring->count;
3292 
3293 	/* use 32 byte descriptors */
3294 	rx_ctx.dsize = 1;
3295 
3296 	/* descriptor type is always zero
3297 	 * rx_ctx.dtype = 0;
3298 	 */
3299 	rx_ctx.hsplit_0 = 0;
3300 
3301 	rx_ctx.rxmax = min_t(u16, vsi->max_frame, chain_len * ring->rx_buf_len);
3302 	if (hw->revision_id == 0)
3303 		rx_ctx.lrxqthresh = 0;
3304 	else
3305 		rx_ctx.lrxqthresh = 1;
3306 	rx_ctx.crcstrip = 1;
3307 	rx_ctx.l2tsel = 1;
3308 	/* this controls whether VLAN is stripped from inner headers */
3309 	rx_ctx.showiv = 0;
3310 	/* set the prefena field to 1 because the manual says to */
3311 	rx_ctx.prefena = 1;
3312 
3313 	/* clear the context in the HMC */
3314 	err = i40e_clear_lan_rx_queue_context(hw, pf_q);
3315 	if (err) {
3316 		dev_info(&vsi->back->pdev->dev,
3317 			 "Failed to clear LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3318 			 ring->queue_index, pf_q, err);
3319 		return -ENOMEM;
3320 	}
3321 
3322 	/* set the context in the HMC */
3323 	err = i40e_set_lan_rx_queue_context(hw, pf_q, &rx_ctx);
3324 	if (err) {
3325 		dev_info(&vsi->back->pdev->dev,
3326 			 "Failed to set LAN Rx queue context on Rx ring %d (pf_q %d), error: %d\n",
3327 			 ring->queue_index, pf_q, err);
3328 		return -ENOMEM;
3329 	}
3330 
3331 	/* configure Rx buffer alignment */
3332 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX))
3333 		clear_ring_build_skb_enabled(ring);
3334 	else
3335 		set_ring_build_skb_enabled(ring);
3336 
3337 	/* cache tail for quicker writes, and clear the reg before use */
3338 	ring->tail = hw->hw_addr + I40E_QRX_TAIL(pf_q);
3339 	writel(0, ring->tail);
3340 
3341 	ok = ring->xsk_umem ?
3342 	     i40e_alloc_rx_buffers_zc(ring, I40E_DESC_UNUSED(ring)) :
3343 	     !i40e_alloc_rx_buffers(ring, I40E_DESC_UNUSED(ring));
3344 	if (!ok) {
3345 		/* Log this in case the user has forgotten to give the kernel
3346 		 * any buffers, even later in the application.
3347 		 */
3348 		dev_info(&vsi->back->pdev->dev,
3349 			 "Failed to allocate some buffers on %sRx ring %d (pf_q %d)\n",
3350 			 ring->xsk_umem ? "UMEM enabled " : "",
3351 			 ring->queue_index, pf_q);
3352 	}
3353 
3354 	return 0;
3355 }
3356 
3357 /**
3358  * i40e_vsi_configure_tx - Configure the VSI for Tx
3359  * @vsi: VSI structure describing this set of rings and resources
3360  *
3361  * Configure the Tx VSI for operation.
3362  **/
3363 static int i40e_vsi_configure_tx(struct i40e_vsi *vsi)
3364 {
3365 	int err = 0;
3366 	u16 i;
3367 
3368 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3369 		err = i40e_configure_tx_ring(vsi->tx_rings[i]);
3370 
3371 	if (err || !i40e_enabled_xdp_vsi(vsi))
3372 		return err;
3373 
3374 	for (i = 0; (i < vsi->num_queue_pairs) && !err; i++)
3375 		err = i40e_configure_tx_ring(vsi->xdp_rings[i]);
3376 
3377 	return err;
3378 }
3379 
3380 /**
3381  * i40e_vsi_configure_rx - Configure the VSI for Rx
3382  * @vsi: the VSI being configured
3383  *
3384  * Configure the Rx VSI for operation.
3385  **/
3386 static int i40e_vsi_configure_rx(struct i40e_vsi *vsi)
3387 {
3388 	int err = 0;
3389 	u16 i;
3390 
3391 	if (!vsi->netdev || (vsi->back->flags & I40E_FLAG_LEGACY_RX)) {
3392 		vsi->max_frame = I40E_MAX_RXBUFFER;
3393 		vsi->rx_buf_len = I40E_RXBUFFER_2048;
3394 #if (PAGE_SIZE < 8192)
3395 	} else if (!I40E_2K_TOO_SMALL_WITH_PADDING &&
3396 		   (vsi->netdev->mtu <= ETH_DATA_LEN)) {
3397 		vsi->max_frame = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3398 		vsi->rx_buf_len = I40E_RXBUFFER_1536 - NET_IP_ALIGN;
3399 #endif
3400 	} else {
3401 		vsi->max_frame = I40E_MAX_RXBUFFER;
3402 		vsi->rx_buf_len = (PAGE_SIZE < 8192) ? I40E_RXBUFFER_3072 :
3403 						       I40E_RXBUFFER_2048;
3404 	}
3405 
3406 	/* set up individual rings */
3407 	for (i = 0; i < vsi->num_queue_pairs && !err; i++)
3408 		err = i40e_configure_rx_ring(vsi->rx_rings[i]);
3409 
3410 	return err;
3411 }
3412 
3413 /**
3414  * i40e_vsi_config_dcb_rings - Update rings to reflect DCB TC
3415  * @vsi: ptr to the VSI
3416  **/
3417 static void i40e_vsi_config_dcb_rings(struct i40e_vsi *vsi)
3418 {
3419 	struct i40e_ring *tx_ring, *rx_ring;
3420 	u16 qoffset, qcount;
3421 	int i, n;
3422 
3423 	if (!(vsi->back->flags & I40E_FLAG_DCB_ENABLED)) {
3424 		/* Reset the TC information */
3425 		for (i = 0; i < vsi->num_queue_pairs; i++) {
3426 			rx_ring = vsi->rx_rings[i];
3427 			tx_ring = vsi->tx_rings[i];
3428 			rx_ring->dcb_tc = 0;
3429 			tx_ring->dcb_tc = 0;
3430 		}
3431 		return;
3432 	}
3433 
3434 	for (n = 0; n < I40E_MAX_TRAFFIC_CLASS; n++) {
3435 		if (!(vsi->tc_config.enabled_tc & BIT_ULL(n)))
3436 			continue;
3437 
3438 		qoffset = vsi->tc_config.tc_info[n].qoffset;
3439 		qcount = vsi->tc_config.tc_info[n].qcount;
3440 		for (i = qoffset; i < (qoffset + qcount); i++) {
3441 			rx_ring = vsi->rx_rings[i];
3442 			tx_ring = vsi->tx_rings[i];
3443 			rx_ring->dcb_tc = n;
3444 			tx_ring->dcb_tc = n;
3445 		}
3446 	}
3447 }
3448 
3449 /**
3450  * i40e_set_vsi_rx_mode - Call set_rx_mode on a VSI
3451  * @vsi: ptr to the VSI
3452  **/
3453 static void i40e_set_vsi_rx_mode(struct i40e_vsi *vsi)
3454 {
3455 	if (vsi->netdev)
3456 		i40e_set_rx_mode(vsi->netdev);
3457 }
3458 
3459 /**
3460  * i40e_fdir_filter_restore - Restore the Sideband Flow Director filters
3461  * @vsi: Pointer to the targeted VSI
3462  *
3463  * This function replays the hlist on the hw where all the SB Flow Director
3464  * filters were saved.
3465  **/
3466 static void i40e_fdir_filter_restore(struct i40e_vsi *vsi)
3467 {
3468 	struct i40e_fdir_filter *filter;
3469 	struct i40e_pf *pf = vsi->back;
3470 	struct hlist_node *node;
3471 
3472 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
3473 		return;
3474 
3475 	/* Reset FDir counters as we're replaying all existing filters */
3476 	pf->fd_tcp4_filter_cnt = 0;
3477 	pf->fd_udp4_filter_cnt = 0;
3478 	pf->fd_sctp4_filter_cnt = 0;
3479 	pf->fd_ip4_filter_cnt = 0;
3480 
3481 	hlist_for_each_entry_safe(filter, node,
3482 				  &pf->fdir_filter_list, fdir_node) {
3483 		i40e_add_del_fdir(vsi, filter, true);
3484 	}
3485 }
3486 
3487 /**
3488  * i40e_vsi_configure - Set up the VSI for action
3489  * @vsi: the VSI being configured
3490  **/
3491 static int i40e_vsi_configure(struct i40e_vsi *vsi)
3492 {
3493 	int err;
3494 
3495 	i40e_set_vsi_rx_mode(vsi);
3496 	i40e_restore_vlan(vsi);
3497 	i40e_vsi_config_dcb_rings(vsi);
3498 	err = i40e_vsi_configure_tx(vsi);
3499 	if (!err)
3500 		err = i40e_vsi_configure_rx(vsi);
3501 
3502 	return err;
3503 }
3504 
3505 /**
3506  * i40e_vsi_configure_msix - MSIX mode Interrupt Config in the HW
3507  * @vsi: the VSI being configured
3508  **/
3509 static void i40e_vsi_configure_msix(struct i40e_vsi *vsi)
3510 {
3511 	bool has_xdp = i40e_enabled_xdp_vsi(vsi);
3512 	struct i40e_pf *pf = vsi->back;
3513 	struct i40e_hw *hw = &pf->hw;
3514 	u16 vector;
3515 	int i, q;
3516 	u32 qp;
3517 
3518 	/* The interrupt indexing is offset by 1 in the PFINT_ITRn
3519 	 * and PFINT_LNKLSTn registers, e.g.:
3520 	 *   PFINT_ITRn[0..n-1] gets msix-1..msix-n  (qpair interrupts)
3521 	 */
3522 	qp = vsi->base_queue;
3523 	vector = vsi->base_vector;
3524 	for (i = 0; i < vsi->num_q_vectors; i++, vector++) {
3525 		struct i40e_q_vector *q_vector = vsi->q_vectors[i];
3526 
3527 		q_vector->rx.next_update = jiffies + 1;
3528 		q_vector->rx.target_itr =
3529 			ITR_TO_REG(vsi->rx_rings[i]->itr_setting);
3530 		wr32(hw, I40E_PFINT_ITRN(I40E_RX_ITR, vector - 1),
3531 		     q_vector->rx.target_itr);
3532 		q_vector->rx.current_itr = q_vector->rx.target_itr;
3533 
3534 		q_vector->tx.next_update = jiffies + 1;
3535 		q_vector->tx.target_itr =
3536 			ITR_TO_REG(vsi->tx_rings[i]->itr_setting);
3537 		wr32(hw, I40E_PFINT_ITRN(I40E_TX_ITR, vector - 1),
3538 		     q_vector->tx.target_itr);
3539 		q_vector->tx.current_itr = q_vector->tx.target_itr;
3540 
3541 		wr32(hw, I40E_PFINT_RATEN(vector - 1),
3542 		     i40e_intrl_usec_to_reg(vsi->int_rate_limit));
3543 
3544 		/* Linked list for the queuepairs assigned to this vector */
3545 		wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), qp);
3546 		for (q = 0; q < q_vector->num_ringpairs; q++) {
3547 			u32 nextqp = has_xdp ? qp + vsi->alloc_queue_pairs : qp;
3548 			u32 val;
3549 
3550 			val = I40E_QINT_RQCTL_CAUSE_ENA_MASK |
3551 			      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT) |
3552 			      (vector << I40E_QINT_RQCTL_MSIX_INDX_SHIFT) |
3553 			      (nextqp << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT) |
3554 			      (I40E_QUEUE_TYPE_TX <<
3555 			       I40E_QINT_RQCTL_NEXTQ_TYPE_SHIFT);
3556 
3557 			wr32(hw, I40E_QINT_RQCTL(qp), val);
3558 
3559 			if (has_xdp) {
3560 				val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3561 				      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3562 				      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3563 				      (qp << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3564 				      (I40E_QUEUE_TYPE_TX <<
3565 				       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3566 
3567 				wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3568 			}
3569 
3570 			val = I40E_QINT_TQCTL_CAUSE_ENA_MASK |
3571 			      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3572 			      (vector << I40E_QINT_TQCTL_MSIX_INDX_SHIFT) |
3573 			      ((qp + 1) << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT) |
3574 			      (I40E_QUEUE_TYPE_RX <<
3575 			       I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3576 
3577 			/* Terminate the linked list */
3578 			if (q == (q_vector->num_ringpairs - 1))
3579 				val |= (I40E_QUEUE_END_OF_LIST <<
3580 					I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3581 
3582 			wr32(hw, I40E_QINT_TQCTL(qp), val);
3583 			qp++;
3584 		}
3585 	}
3586 
3587 	i40e_flush(hw);
3588 }
3589 
3590 /**
3591  * i40e_enable_misc_int_causes - enable the non-queue interrupts
3592  * @pf: pointer to private device data structure
3593  **/
3594 static void i40e_enable_misc_int_causes(struct i40e_pf *pf)
3595 {
3596 	struct i40e_hw *hw = &pf->hw;
3597 	u32 val;
3598 
3599 	/* clear things first */
3600 	wr32(hw, I40E_PFINT_ICR0_ENA, 0);  /* disable all */
3601 	rd32(hw, I40E_PFINT_ICR0);         /* read to clear */
3602 
3603 	val = I40E_PFINT_ICR0_ENA_ECC_ERR_MASK       |
3604 	      I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK    |
3605 	      I40E_PFINT_ICR0_ENA_GRST_MASK          |
3606 	      I40E_PFINT_ICR0_ENA_PCI_EXCEPTION_MASK |
3607 	      I40E_PFINT_ICR0_ENA_GPIO_MASK          |
3608 	      I40E_PFINT_ICR0_ENA_HMC_ERR_MASK       |
3609 	      I40E_PFINT_ICR0_ENA_VFLR_MASK          |
3610 	      I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3611 
3612 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
3613 		val |= I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3614 
3615 	if (pf->flags & I40E_FLAG_PTP)
3616 		val |= I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
3617 
3618 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
3619 
3620 	/* SW_ITR_IDX = 0, but don't change INTENA */
3621 	wr32(hw, I40E_PFINT_DYN_CTL0, I40E_PFINT_DYN_CTL0_SW_ITR_INDX_MASK |
3622 					I40E_PFINT_DYN_CTL0_INTENA_MSK_MASK);
3623 
3624 	/* OTHER_ITR_IDX = 0 */
3625 	wr32(hw, I40E_PFINT_STAT_CTL0, 0);
3626 }
3627 
3628 /**
3629  * i40e_configure_msi_and_legacy - Legacy mode interrupt config in the HW
3630  * @vsi: the VSI being configured
3631  **/
3632 static void i40e_configure_msi_and_legacy(struct i40e_vsi *vsi)
3633 {
3634 	u32 nextqp = i40e_enabled_xdp_vsi(vsi) ? vsi->alloc_queue_pairs : 0;
3635 	struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3636 	struct i40e_pf *pf = vsi->back;
3637 	struct i40e_hw *hw = &pf->hw;
3638 	u32 val;
3639 
3640 	/* set the ITR configuration */
3641 	q_vector->rx.next_update = jiffies + 1;
3642 	q_vector->rx.target_itr = ITR_TO_REG(vsi->rx_rings[0]->itr_setting);
3643 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), q_vector->rx.target_itr);
3644 	q_vector->rx.current_itr = q_vector->rx.target_itr;
3645 	q_vector->tx.next_update = jiffies + 1;
3646 	q_vector->tx.target_itr = ITR_TO_REG(vsi->tx_rings[0]->itr_setting);
3647 	wr32(hw, I40E_PFINT_ITR0(I40E_TX_ITR), q_vector->tx.target_itr);
3648 	q_vector->tx.current_itr = q_vector->tx.target_itr;
3649 
3650 	i40e_enable_misc_int_causes(pf);
3651 
3652 	/* FIRSTQ_INDX = 0, FIRSTQ_TYPE = 0 (rx) */
3653 	wr32(hw, I40E_PFINT_LNKLST0, 0);
3654 
3655 	/* Associate the queue pair to the vector and enable the queue int */
3656 	val = I40E_QINT_RQCTL_CAUSE_ENA_MASK		       |
3657 	      (I40E_RX_ITR << I40E_QINT_RQCTL_ITR_INDX_SHIFT)  |
3658 	      (nextqp	   << I40E_QINT_RQCTL_NEXTQ_INDX_SHIFT)|
3659 	      (I40E_QUEUE_TYPE_TX << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3660 
3661 	wr32(hw, I40E_QINT_RQCTL(0), val);
3662 
3663 	if (i40e_enabled_xdp_vsi(vsi)) {
3664 		val = I40E_QINT_TQCTL_CAUSE_ENA_MASK		     |
3665 		      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT)|
3666 		      (I40E_QUEUE_TYPE_TX
3667 		       << I40E_QINT_TQCTL_NEXTQ_TYPE_SHIFT);
3668 
3669 		wr32(hw, I40E_QINT_TQCTL(nextqp), val);
3670 	}
3671 
3672 	val = I40E_QINT_TQCTL_CAUSE_ENA_MASK		      |
3673 	      (I40E_TX_ITR << I40E_QINT_TQCTL_ITR_INDX_SHIFT) |
3674 	      (I40E_QUEUE_END_OF_LIST << I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT);
3675 
3676 	wr32(hw, I40E_QINT_TQCTL(0), val);
3677 	i40e_flush(hw);
3678 }
3679 
3680 /**
3681  * i40e_irq_dynamic_disable_icr0 - Disable default interrupt generation for icr0
3682  * @pf: board private structure
3683  **/
3684 void i40e_irq_dynamic_disable_icr0(struct i40e_pf *pf)
3685 {
3686 	struct i40e_hw *hw = &pf->hw;
3687 
3688 	wr32(hw, I40E_PFINT_DYN_CTL0,
3689 	     I40E_ITR_NONE << I40E_PFINT_DYN_CTLN_ITR_INDX_SHIFT);
3690 	i40e_flush(hw);
3691 }
3692 
3693 /**
3694  * i40e_irq_dynamic_enable_icr0 - Enable default interrupt generation for icr0
3695  * @pf: board private structure
3696  **/
3697 void i40e_irq_dynamic_enable_icr0(struct i40e_pf *pf)
3698 {
3699 	struct i40e_hw *hw = &pf->hw;
3700 	u32 val;
3701 
3702 	val = I40E_PFINT_DYN_CTL0_INTENA_MASK   |
3703 	      I40E_PFINT_DYN_CTL0_CLEARPBA_MASK |
3704 	      (I40E_ITR_NONE << I40E_PFINT_DYN_CTL0_ITR_INDX_SHIFT);
3705 
3706 	wr32(hw, I40E_PFINT_DYN_CTL0, val);
3707 	i40e_flush(hw);
3708 }
3709 
3710 /**
3711  * i40e_msix_clean_rings - MSIX mode Interrupt Handler
3712  * @irq: interrupt number
3713  * @data: pointer to a q_vector
3714  **/
3715 static irqreturn_t i40e_msix_clean_rings(int irq, void *data)
3716 {
3717 	struct i40e_q_vector *q_vector = data;
3718 
3719 	if (!q_vector->tx.ring && !q_vector->rx.ring)
3720 		return IRQ_HANDLED;
3721 
3722 	napi_schedule_irqoff(&q_vector->napi);
3723 
3724 	return IRQ_HANDLED;
3725 }
3726 
3727 /**
3728  * i40e_irq_affinity_notify - Callback for affinity changes
3729  * @notify: context as to what irq was changed
3730  * @mask: the new affinity mask
3731  *
3732  * This is a callback function used by the irq_set_affinity_notifier function
3733  * so that we may register to receive changes to the irq affinity masks.
3734  **/
3735 static void i40e_irq_affinity_notify(struct irq_affinity_notify *notify,
3736 				     const cpumask_t *mask)
3737 {
3738 	struct i40e_q_vector *q_vector =
3739 		container_of(notify, struct i40e_q_vector, affinity_notify);
3740 
3741 	cpumask_copy(&q_vector->affinity_mask, mask);
3742 }
3743 
3744 /**
3745  * i40e_irq_affinity_release - Callback for affinity notifier release
3746  * @ref: internal core kernel usage
3747  *
3748  * This is a callback function used by the irq_set_affinity_notifier function
3749  * to inform the current notification subscriber that they will no longer
3750  * receive notifications.
3751  **/
3752 static void i40e_irq_affinity_release(struct kref *ref) {}
3753 
3754 /**
3755  * i40e_vsi_request_irq_msix - Initialize MSI-X interrupts
3756  * @vsi: the VSI being configured
3757  * @basename: name for the vector
3758  *
3759  * Allocates MSI-X vectors and requests interrupts from the kernel.
3760  **/
3761 static int i40e_vsi_request_irq_msix(struct i40e_vsi *vsi, char *basename)
3762 {
3763 	int q_vectors = vsi->num_q_vectors;
3764 	struct i40e_pf *pf = vsi->back;
3765 	int base = vsi->base_vector;
3766 	int rx_int_idx = 0;
3767 	int tx_int_idx = 0;
3768 	int vector, err;
3769 	int irq_num;
3770 	int cpu;
3771 
3772 	for (vector = 0; vector < q_vectors; vector++) {
3773 		struct i40e_q_vector *q_vector = vsi->q_vectors[vector];
3774 
3775 		irq_num = pf->msix_entries[base + vector].vector;
3776 
3777 		if (q_vector->tx.ring && q_vector->rx.ring) {
3778 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3779 				 "%s-%s-%d", basename, "TxRx", rx_int_idx++);
3780 			tx_int_idx++;
3781 		} else if (q_vector->rx.ring) {
3782 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3783 				 "%s-%s-%d", basename, "rx", rx_int_idx++);
3784 		} else if (q_vector->tx.ring) {
3785 			snprintf(q_vector->name, sizeof(q_vector->name) - 1,
3786 				 "%s-%s-%d", basename, "tx", tx_int_idx++);
3787 		} else {
3788 			/* skip this unused q_vector */
3789 			continue;
3790 		}
3791 		err = request_irq(irq_num,
3792 				  vsi->irq_handler,
3793 				  0,
3794 				  q_vector->name,
3795 				  q_vector);
3796 		if (err) {
3797 			dev_info(&pf->pdev->dev,
3798 				 "MSIX request_irq failed, error: %d\n", err);
3799 			goto free_queue_irqs;
3800 		}
3801 
3802 		/* register for affinity change notifications */
3803 		q_vector->affinity_notify.notify = i40e_irq_affinity_notify;
3804 		q_vector->affinity_notify.release = i40e_irq_affinity_release;
3805 		irq_set_affinity_notifier(irq_num, &q_vector->affinity_notify);
3806 		/* Spread affinity hints out across online CPUs.
3807 		 *
3808 		 * get_cpu_mask returns a static constant mask with
3809 		 * a permanent lifetime so it's ok to pass to
3810 		 * irq_set_affinity_hint without making a copy.
3811 		 */
3812 		cpu = cpumask_local_spread(q_vector->v_idx, -1);
3813 		irq_set_affinity_hint(irq_num, get_cpu_mask(cpu));
3814 	}
3815 
3816 	vsi->irqs_ready = true;
3817 	return 0;
3818 
3819 free_queue_irqs:
3820 	while (vector) {
3821 		vector--;
3822 		irq_num = pf->msix_entries[base + vector].vector;
3823 		irq_set_affinity_notifier(irq_num, NULL);
3824 		irq_set_affinity_hint(irq_num, NULL);
3825 		free_irq(irq_num, &vsi->q_vectors[vector]);
3826 	}
3827 	return err;
3828 }
3829 
3830 /**
3831  * i40e_vsi_disable_irq - Mask off queue interrupt generation on the VSI
3832  * @vsi: the VSI being un-configured
3833  **/
3834 static void i40e_vsi_disable_irq(struct i40e_vsi *vsi)
3835 {
3836 	struct i40e_pf *pf = vsi->back;
3837 	struct i40e_hw *hw = &pf->hw;
3838 	int base = vsi->base_vector;
3839 	int i;
3840 
3841 	/* disable interrupt causation from each queue */
3842 	for (i = 0; i < vsi->num_queue_pairs; i++) {
3843 		u32 val;
3844 
3845 		val = rd32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx));
3846 		val &= ~I40E_QINT_TQCTL_CAUSE_ENA_MASK;
3847 		wr32(hw, I40E_QINT_TQCTL(vsi->tx_rings[i]->reg_idx), val);
3848 
3849 		val = rd32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx));
3850 		val &= ~I40E_QINT_RQCTL_CAUSE_ENA_MASK;
3851 		wr32(hw, I40E_QINT_RQCTL(vsi->rx_rings[i]->reg_idx), val);
3852 
3853 		if (!i40e_enabled_xdp_vsi(vsi))
3854 			continue;
3855 		wr32(hw, I40E_QINT_TQCTL(vsi->xdp_rings[i]->reg_idx), 0);
3856 	}
3857 
3858 	/* disable each interrupt */
3859 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3860 		for (i = vsi->base_vector;
3861 		     i < (vsi->num_q_vectors + vsi->base_vector); i++)
3862 			wr32(hw, I40E_PFINT_DYN_CTLN(i - 1), 0);
3863 
3864 		i40e_flush(hw);
3865 		for (i = 0; i < vsi->num_q_vectors; i++)
3866 			synchronize_irq(pf->msix_entries[i + base].vector);
3867 	} else {
3868 		/* Legacy and MSI mode - this stops all interrupt handling */
3869 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
3870 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
3871 		i40e_flush(hw);
3872 		synchronize_irq(pf->pdev->irq);
3873 	}
3874 }
3875 
3876 /**
3877  * i40e_vsi_enable_irq - Enable IRQ for the given VSI
3878  * @vsi: the VSI being configured
3879  **/
3880 static int i40e_vsi_enable_irq(struct i40e_vsi *vsi)
3881 {
3882 	struct i40e_pf *pf = vsi->back;
3883 	int i;
3884 
3885 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
3886 		for (i = 0; i < vsi->num_q_vectors; i++)
3887 			i40e_irq_dynamic_enable(vsi, i);
3888 	} else {
3889 		i40e_irq_dynamic_enable_icr0(pf);
3890 	}
3891 
3892 	i40e_flush(&pf->hw);
3893 	return 0;
3894 }
3895 
3896 /**
3897  * i40e_free_misc_vector - Free the vector that handles non-queue events
3898  * @pf: board private structure
3899  **/
3900 static void i40e_free_misc_vector(struct i40e_pf *pf)
3901 {
3902 	/* Disable ICR 0 */
3903 	wr32(&pf->hw, I40E_PFINT_ICR0_ENA, 0);
3904 	i40e_flush(&pf->hw);
3905 
3906 	if (pf->flags & I40E_FLAG_MSIX_ENABLED && pf->msix_entries) {
3907 		synchronize_irq(pf->msix_entries[0].vector);
3908 		free_irq(pf->msix_entries[0].vector, pf);
3909 		clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
3910 	}
3911 }
3912 
3913 /**
3914  * i40e_intr - MSI/Legacy and non-queue interrupt handler
3915  * @irq: interrupt number
3916  * @data: pointer to a q_vector
3917  *
3918  * This is the handler used for all MSI/Legacy interrupts, and deals
3919  * with both queue and non-queue interrupts.  This is also used in
3920  * MSIX mode to handle the non-queue interrupts.
3921  **/
3922 static irqreturn_t i40e_intr(int irq, void *data)
3923 {
3924 	struct i40e_pf *pf = (struct i40e_pf *)data;
3925 	struct i40e_hw *hw = &pf->hw;
3926 	irqreturn_t ret = IRQ_NONE;
3927 	u32 icr0, icr0_remaining;
3928 	u32 val, ena_mask;
3929 
3930 	icr0 = rd32(hw, I40E_PFINT_ICR0);
3931 	ena_mask = rd32(hw, I40E_PFINT_ICR0_ENA);
3932 
3933 	/* if sharing a legacy IRQ, we might get called w/o an intr pending */
3934 	if ((icr0 & I40E_PFINT_ICR0_INTEVENT_MASK) == 0)
3935 		goto enable_intr;
3936 
3937 	/* if interrupt but no bits showing, must be SWINT */
3938 	if (((icr0 & ~I40E_PFINT_ICR0_INTEVENT_MASK) == 0) ||
3939 	    (icr0 & I40E_PFINT_ICR0_SWINT_MASK))
3940 		pf->sw_int_count++;
3941 
3942 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
3943 	    (icr0 & I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK)) {
3944 		ena_mask &= ~I40E_PFINT_ICR0_ENA_PE_CRITERR_MASK;
3945 		dev_dbg(&pf->pdev->dev, "cleared PE_CRITERR\n");
3946 		set_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
3947 	}
3948 
3949 	/* only q0 is used in MSI/Legacy mode, and none are used in MSIX */
3950 	if (icr0 & I40E_PFINT_ICR0_QUEUE_0_MASK) {
3951 		struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
3952 		struct i40e_q_vector *q_vector = vsi->q_vectors[0];
3953 
3954 		/* We do not have a way to disarm Queue causes while leaving
3955 		 * interrupt enabled for all other causes, ideally
3956 		 * interrupt should be disabled while we are in NAPI but
3957 		 * this is not a performance path and napi_schedule()
3958 		 * can deal with rescheduling.
3959 		 */
3960 		if (!test_bit(__I40E_DOWN, pf->state))
3961 			napi_schedule_irqoff(&q_vector->napi);
3962 	}
3963 
3964 	if (icr0 & I40E_PFINT_ICR0_ADMINQ_MASK) {
3965 		ena_mask &= ~I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
3966 		set_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
3967 		i40e_debug(&pf->hw, I40E_DEBUG_NVM, "AdminQ event\n");
3968 	}
3969 
3970 	if (icr0 & I40E_PFINT_ICR0_MAL_DETECT_MASK) {
3971 		ena_mask &= ~I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
3972 		set_bit(__I40E_MDD_EVENT_PENDING, pf->state);
3973 	}
3974 
3975 	if (icr0 & I40E_PFINT_ICR0_VFLR_MASK) {
3976 		ena_mask &= ~I40E_PFINT_ICR0_ENA_VFLR_MASK;
3977 		set_bit(__I40E_VFLR_EVENT_PENDING, pf->state);
3978 	}
3979 
3980 	if (icr0 & I40E_PFINT_ICR0_GRST_MASK) {
3981 		if (!test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
3982 			set_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
3983 		ena_mask &= ~I40E_PFINT_ICR0_ENA_GRST_MASK;
3984 		val = rd32(hw, I40E_GLGEN_RSTAT);
3985 		val = (val & I40E_GLGEN_RSTAT_RESET_TYPE_MASK)
3986 		       >> I40E_GLGEN_RSTAT_RESET_TYPE_SHIFT;
3987 		if (val == I40E_RESET_CORER) {
3988 			pf->corer_count++;
3989 		} else if (val == I40E_RESET_GLOBR) {
3990 			pf->globr_count++;
3991 		} else if (val == I40E_RESET_EMPR) {
3992 			pf->empr_count++;
3993 			set_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state);
3994 		}
3995 	}
3996 
3997 	if (icr0 & I40E_PFINT_ICR0_HMC_ERR_MASK) {
3998 		icr0 &= ~I40E_PFINT_ICR0_HMC_ERR_MASK;
3999 		dev_info(&pf->pdev->dev, "HMC error interrupt\n");
4000 		dev_info(&pf->pdev->dev, "HMC error info 0x%x, HMC error data 0x%x\n",
4001 			 rd32(hw, I40E_PFHMC_ERRORINFO),
4002 			 rd32(hw, I40E_PFHMC_ERRORDATA));
4003 	}
4004 
4005 	if (icr0 & I40E_PFINT_ICR0_TIMESYNC_MASK) {
4006 		u32 prttsyn_stat = rd32(hw, I40E_PRTTSYN_STAT_0);
4007 
4008 		if (prttsyn_stat & I40E_PRTTSYN_STAT_0_TXTIME_MASK) {
4009 			icr0 &= ~I40E_PFINT_ICR0_ENA_TIMESYNC_MASK;
4010 			i40e_ptp_tx_hwtstamp(pf);
4011 		}
4012 	}
4013 
4014 	/* If a critical error is pending we have no choice but to reset the
4015 	 * device.
4016 	 * Report and mask out any remaining unexpected interrupts.
4017 	 */
4018 	icr0_remaining = icr0 & ena_mask;
4019 	if (icr0_remaining) {
4020 		dev_info(&pf->pdev->dev, "unhandled interrupt icr0=0x%08x\n",
4021 			 icr0_remaining);
4022 		if ((icr0_remaining & I40E_PFINT_ICR0_PE_CRITERR_MASK) ||
4023 		    (icr0_remaining & I40E_PFINT_ICR0_PCI_EXCEPTION_MASK) ||
4024 		    (icr0_remaining & I40E_PFINT_ICR0_ECC_ERR_MASK)) {
4025 			dev_info(&pf->pdev->dev, "device will be reset\n");
4026 			set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
4027 			i40e_service_event_schedule(pf);
4028 		}
4029 		ena_mask &= ~icr0_remaining;
4030 	}
4031 	ret = IRQ_HANDLED;
4032 
4033 enable_intr:
4034 	/* re-enable interrupt causes */
4035 	wr32(hw, I40E_PFINT_ICR0_ENA, ena_mask);
4036 	if (!test_bit(__I40E_DOWN, pf->state) ||
4037 	    test_bit(__I40E_RECOVERY_MODE, pf->state)) {
4038 		i40e_service_event_schedule(pf);
4039 		i40e_irq_dynamic_enable_icr0(pf);
4040 	}
4041 
4042 	return ret;
4043 }
4044 
4045 /**
4046  * i40e_clean_fdir_tx_irq - Reclaim resources after transmit completes
4047  * @tx_ring:  tx ring to clean
4048  * @budget:   how many cleans we're allowed
4049  *
4050  * Returns true if there's any budget left (e.g. the clean is finished)
4051  **/
4052 static bool i40e_clean_fdir_tx_irq(struct i40e_ring *tx_ring, int budget)
4053 {
4054 	struct i40e_vsi *vsi = tx_ring->vsi;
4055 	u16 i = tx_ring->next_to_clean;
4056 	struct i40e_tx_buffer *tx_buf;
4057 	struct i40e_tx_desc *tx_desc;
4058 
4059 	tx_buf = &tx_ring->tx_bi[i];
4060 	tx_desc = I40E_TX_DESC(tx_ring, i);
4061 	i -= tx_ring->count;
4062 
4063 	do {
4064 		struct i40e_tx_desc *eop_desc = tx_buf->next_to_watch;
4065 
4066 		/* if next_to_watch is not set then there is no work pending */
4067 		if (!eop_desc)
4068 			break;
4069 
4070 		/* prevent any other reads prior to eop_desc */
4071 		smp_rmb();
4072 
4073 		/* if the descriptor isn't done, no work yet to do */
4074 		if (!(eop_desc->cmd_type_offset_bsz &
4075 		      cpu_to_le64(I40E_TX_DESC_DTYPE_DESC_DONE)))
4076 			break;
4077 
4078 		/* clear next_to_watch to prevent false hangs */
4079 		tx_buf->next_to_watch = NULL;
4080 
4081 		tx_desc->buffer_addr = 0;
4082 		tx_desc->cmd_type_offset_bsz = 0;
4083 		/* move past filter desc */
4084 		tx_buf++;
4085 		tx_desc++;
4086 		i++;
4087 		if (unlikely(!i)) {
4088 			i -= tx_ring->count;
4089 			tx_buf = tx_ring->tx_bi;
4090 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4091 		}
4092 		/* unmap skb header data */
4093 		dma_unmap_single(tx_ring->dev,
4094 				 dma_unmap_addr(tx_buf, dma),
4095 				 dma_unmap_len(tx_buf, len),
4096 				 DMA_TO_DEVICE);
4097 		if (tx_buf->tx_flags & I40E_TX_FLAGS_FD_SB)
4098 			kfree(tx_buf->raw_buf);
4099 
4100 		tx_buf->raw_buf = NULL;
4101 		tx_buf->tx_flags = 0;
4102 		tx_buf->next_to_watch = NULL;
4103 		dma_unmap_len_set(tx_buf, len, 0);
4104 		tx_desc->buffer_addr = 0;
4105 		tx_desc->cmd_type_offset_bsz = 0;
4106 
4107 		/* move us past the eop_desc for start of next FD desc */
4108 		tx_buf++;
4109 		tx_desc++;
4110 		i++;
4111 		if (unlikely(!i)) {
4112 			i -= tx_ring->count;
4113 			tx_buf = tx_ring->tx_bi;
4114 			tx_desc = I40E_TX_DESC(tx_ring, 0);
4115 		}
4116 
4117 		/* update budget accounting */
4118 		budget--;
4119 	} while (likely(budget));
4120 
4121 	i += tx_ring->count;
4122 	tx_ring->next_to_clean = i;
4123 
4124 	if (vsi->back->flags & I40E_FLAG_MSIX_ENABLED)
4125 		i40e_irq_dynamic_enable(vsi, tx_ring->q_vector->v_idx);
4126 
4127 	return budget > 0;
4128 }
4129 
4130 /**
4131  * i40e_fdir_clean_ring - Interrupt Handler for FDIR SB ring
4132  * @irq: interrupt number
4133  * @data: pointer to a q_vector
4134  **/
4135 static irqreturn_t i40e_fdir_clean_ring(int irq, void *data)
4136 {
4137 	struct i40e_q_vector *q_vector = data;
4138 	struct i40e_vsi *vsi;
4139 
4140 	if (!q_vector->tx.ring)
4141 		return IRQ_HANDLED;
4142 
4143 	vsi = q_vector->tx.ring->vsi;
4144 	i40e_clean_fdir_tx_irq(q_vector->tx.ring, vsi->work_limit);
4145 
4146 	return IRQ_HANDLED;
4147 }
4148 
4149 /**
4150  * i40e_map_vector_to_qp - Assigns the queue pair to the vector
4151  * @vsi: the VSI being configured
4152  * @v_idx: vector index
4153  * @qp_idx: queue pair index
4154  **/
4155 static void i40e_map_vector_to_qp(struct i40e_vsi *vsi, int v_idx, int qp_idx)
4156 {
4157 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4158 	struct i40e_ring *tx_ring = vsi->tx_rings[qp_idx];
4159 	struct i40e_ring *rx_ring = vsi->rx_rings[qp_idx];
4160 
4161 	tx_ring->q_vector = q_vector;
4162 	tx_ring->next = q_vector->tx.ring;
4163 	q_vector->tx.ring = tx_ring;
4164 	q_vector->tx.count++;
4165 
4166 	/* Place XDP Tx ring in the same q_vector ring list as regular Tx */
4167 	if (i40e_enabled_xdp_vsi(vsi)) {
4168 		struct i40e_ring *xdp_ring = vsi->xdp_rings[qp_idx];
4169 
4170 		xdp_ring->q_vector = q_vector;
4171 		xdp_ring->next = q_vector->tx.ring;
4172 		q_vector->tx.ring = xdp_ring;
4173 		q_vector->tx.count++;
4174 	}
4175 
4176 	rx_ring->q_vector = q_vector;
4177 	rx_ring->next = q_vector->rx.ring;
4178 	q_vector->rx.ring = rx_ring;
4179 	q_vector->rx.count++;
4180 }
4181 
4182 /**
4183  * i40e_vsi_map_rings_to_vectors - Maps descriptor rings to vectors
4184  * @vsi: the VSI being configured
4185  *
4186  * This function maps descriptor rings to the queue-specific vectors
4187  * we were allotted through the MSI-X enabling code.  Ideally, we'd have
4188  * one vector per queue pair, but on a constrained vector budget, we
4189  * group the queue pairs as "efficiently" as possible.
4190  **/
4191 static void i40e_vsi_map_rings_to_vectors(struct i40e_vsi *vsi)
4192 {
4193 	int qp_remaining = vsi->num_queue_pairs;
4194 	int q_vectors = vsi->num_q_vectors;
4195 	int num_ringpairs;
4196 	int v_start = 0;
4197 	int qp_idx = 0;
4198 
4199 	/* If we don't have enough vectors for a 1-to-1 mapping, we'll have to
4200 	 * group them so there are multiple queues per vector.
4201 	 * It is also important to go through all the vectors available to be
4202 	 * sure that if we don't use all the vectors, that the remaining vectors
4203 	 * are cleared. This is especially important when decreasing the
4204 	 * number of queues in use.
4205 	 */
4206 	for (; v_start < q_vectors; v_start++) {
4207 		struct i40e_q_vector *q_vector = vsi->q_vectors[v_start];
4208 
4209 		num_ringpairs = DIV_ROUND_UP(qp_remaining, q_vectors - v_start);
4210 
4211 		q_vector->num_ringpairs = num_ringpairs;
4212 		q_vector->reg_idx = q_vector->v_idx + vsi->base_vector - 1;
4213 
4214 		q_vector->rx.count = 0;
4215 		q_vector->tx.count = 0;
4216 		q_vector->rx.ring = NULL;
4217 		q_vector->tx.ring = NULL;
4218 
4219 		while (num_ringpairs--) {
4220 			i40e_map_vector_to_qp(vsi, v_start, qp_idx);
4221 			qp_idx++;
4222 			qp_remaining--;
4223 		}
4224 	}
4225 }
4226 
4227 /**
4228  * i40e_vsi_request_irq - Request IRQ from the OS
4229  * @vsi: the VSI being configured
4230  * @basename: name for the vector
4231  **/
4232 static int i40e_vsi_request_irq(struct i40e_vsi *vsi, char *basename)
4233 {
4234 	struct i40e_pf *pf = vsi->back;
4235 	int err;
4236 
4237 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
4238 		err = i40e_vsi_request_irq_msix(vsi, basename);
4239 	else if (pf->flags & I40E_FLAG_MSI_ENABLED)
4240 		err = request_irq(pf->pdev->irq, i40e_intr, 0,
4241 				  pf->int_name, pf);
4242 	else
4243 		err = request_irq(pf->pdev->irq, i40e_intr, IRQF_SHARED,
4244 				  pf->int_name, pf);
4245 
4246 	if (err)
4247 		dev_info(&pf->pdev->dev, "request_irq failed, Error %d\n", err);
4248 
4249 	return err;
4250 }
4251 
4252 #ifdef CONFIG_NET_POLL_CONTROLLER
4253 /**
4254  * i40e_netpoll - A Polling 'interrupt' handler
4255  * @netdev: network interface device structure
4256  *
4257  * This is used by netconsole to send skbs without having to re-enable
4258  * interrupts.  It's not called while the normal interrupt routine is executing.
4259  **/
4260 static void i40e_netpoll(struct net_device *netdev)
4261 {
4262 	struct i40e_netdev_priv *np = netdev_priv(netdev);
4263 	struct i40e_vsi *vsi = np->vsi;
4264 	struct i40e_pf *pf = vsi->back;
4265 	int i;
4266 
4267 	/* if interface is down do nothing */
4268 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4269 		return;
4270 
4271 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4272 		for (i = 0; i < vsi->num_q_vectors; i++)
4273 			i40e_msix_clean_rings(0, vsi->q_vectors[i]);
4274 	} else {
4275 		i40e_intr(pf->pdev->irq, netdev);
4276 	}
4277 }
4278 #endif
4279 
4280 #define I40E_QTX_ENA_WAIT_COUNT 50
4281 
4282 /**
4283  * i40e_pf_txq_wait - Wait for a PF's Tx queue to be enabled or disabled
4284  * @pf: the PF being configured
4285  * @pf_q: the PF queue
4286  * @enable: enable or disable state of the queue
4287  *
4288  * This routine will wait for the given Tx queue of the PF to reach the
4289  * enabled or disabled state.
4290  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4291  * multiple retries; else will return 0 in case of success.
4292  **/
4293 static int i40e_pf_txq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4294 {
4295 	int i;
4296 	u32 tx_reg;
4297 
4298 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4299 		tx_reg = rd32(&pf->hw, I40E_QTX_ENA(pf_q));
4300 		if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4301 			break;
4302 
4303 		usleep_range(10, 20);
4304 	}
4305 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4306 		return -ETIMEDOUT;
4307 
4308 	return 0;
4309 }
4310 
4311 /**
4312  * i40e_control_tx_q - Start or stop a particular Tx queue
4313  * @pf: the PF structure
4314  * @pf_q: the PF queue to configure
4315  * @enable: start or stop the queue
4316  *
4317  * This function enables or disables a single queue. Note that any delay
4318  * required after the operation is expected to be handled by the caller of
4319  * this function.
4320  **/
4321 static void i40e_control_tx_q(struct i40e_pf *pf, int pf_q, bool enable)
4322 {
4323 	struct i40e_hw *hw = &pf->hw;
4324 	u32 tx_reg;
4325 	int i;
4326 
4327 	/* warn the TX unit of coming changes */
4328 	i40e_pre_tx_queue_cfg(&pf->hw, pf_q, enable);
4329 	if (!enable)
4330 		usleep_range(10, 20);
4331 
4332 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4333 		tx_reg = rd32(hw, I40E_QTX_ENA(pf_q));
4334 		if (((tx_reg >> I40E_QTX_ENA_QENA_REQ_SHIFT) & 1) ==
4335 		    ((tx_reg >> I40E_QTX_ENA_QENA_STAT_SHIFT) & 1))
4336 			break;
4337 		usleep_range(1000, 2000);
4338 	}
4339 
4340 	/* Skip if the queue is already in the requested state */
4341 	if (enable == !!(tx_reg & I40E_QTX_ENA_QENA_STAT_MASK))
4342 		return;
4343 
4344 	/* turn on/off the queue */
4345 	if (enable) {
4346 		wr32(hw, I40E_QTX_HEAD(pf_q), 0);
4347 		tx_reg |= I40E_QTX_ENA_QENA_REQ_MASK;
4348 	} else {
4349 		tx_reg &= ~I40E_QTX_ENA_QENA_REQ_MASK;
4350 	}
4351 
4352 	wr32(hw, I40E_QTX_ENA(pf_q), tx_reg);
4353 }
4354 
4355 /**
4356  * i40e_control_wait_tx_q - Start/stop Tx queue and wait for completion
4357  * @seid: VSI SEID
4358  * @pf: the PF structure
4359  * @pf_q: the PF queue to configure
4360  * @is_xdp: true if the queue is used for XDP
4361  * @enable: start or stop the queue
4362  **/
4363 int i40e_control_wait_tx_q(int seid, struct i40e_pf *pf, int pf_q,
4364 			   bool is_xdp, bool enable)
4365 {
4366 	int ret;
4367 
4368 	i40e_control_tx_q(pf, pf_q, enable);
4369 
4370 	/* wait for the change to finish */
4371 	ret = i40e_pf_txq_wait(pf, pf_q, enable);
4372 	if (ret) {
4373 		dev_info(&pf->pdev->dev,
4374 			 "VSI seid %d %sTx ring %d %sable timeout\n",
4375 			 seid, (is_xdp ? "XDP " : ""), pf_q,
4376 			 (enable ? "en" : "dis"));
4377 	}
4378 
4379 	return ret;
4380 }
4381 
4382 /**
4383  * i40e_vsi_control_tx - Start or stop a VSI's rings
4384  * @vsi: the VSI being configured
4385  * @enable: start or stop the rings
4386  **/
4387 static int i40e_vsi_control_tx(struct i40e_vsi *vsi, bool enable)
4388 {
4389 	struct i40e_pf *pf = vsi->back;
4390 	int i, pf_q, ret = 0;
4391 
4392 	pf_q = vsi->base_queue;
4393 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4394 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4395 					     pf_q,
4396 					     false /*is xdp*/, enable);
4397 		if (ret)
4398 			break;
4399 
4400 		if (!i40e_enabled_xdp_vsi(vsi))
4401 			continue;
4402 
4403 		ret = i40e_control_wait_tx_q(vsi->seid, pf,
4404 					     pf_q + vsi->alloc_queue_pairs,
4405 					     true /*is xdp*/, enable);
4406 		if (ret)
4407 			break;
4408 	}
4409 	return ret;
4410 }
4411 
4412 /**
4413  * i40e_pf_rxq_wait - Wait for a PF's Rx queue to be enabled or disabled
4414  * @pf: the PF being configured
4415  * @pf_q: the PF queue
4416  * @enable: enable or disable state of the queue
4417  *
4418  * This routine will wait for the given Rx queue of the PF to reach the
4419  * enabled or disabled state.
4420  * Returns -ETIMEDOUT in case of failing to reach the requested state after
4421  * multiple retries; else will return 0 in case of success.
4422  **/
4423 static int i40e_pf_rxq_wait(struct i40e_pf *pf, int pf_q, bool enable)
4424 {
4425 	int i;
4426 	u32 rx_reg;
4427 
4428 	for (i = 0; i < I40E_QUEUE_WAIT_RETRY_LIMIT; i++) {
4429 		rx_reg = rd32(&pf->hw, I40E_QRX_ENA(pf_q));
4430 		if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4431 			break;
4432 
4433 		usleep_range(10, 20);
4434 	}
4435 	if (i >= I40E_QUEUE_WAIT_RETRY_LIMIT)
4436 		return -ETIMEDOUT;
4437 
4438 	return 0;
4439 }
4440 
4441 /**
4442  * i40e_control_rx_q - Start or stop a particular Rx queue
4443  * @pf: the PF structure
4444  * @pf_q: the PF queue to configure
4445  * @enable: start or stop the queue
4446  *
4447  * This function enables or disables a single queue. Note that
4448  * any delay required after the operation is expected to be
4449  * handled by the caller of this function.
4450  **/
4451 static void i40e_control_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4452 {
4453 	struct i40e_hw *hw = &pf->hw;
4454 	u32 rx_reg;
4455 	int i;
4456 
4457 	for (i = 0; i < I40E_QTX_ENA_WAIT_COUNT; i++) {
4458 		rx_reg = rd32(hw, I40E_QRX_ENA(pf_q));
4459 		if (((rx_reg >> I40E_QRX_ENA_QENA_REQ_SHIFT) & 1) ==
4460 		    ((rx_reg >> I40E_QRX_ENA_QENA_STAT_SHIFT) & 1))
4461 			break;
4462 		usleep_range(1000, 2000);
4463 	}
4464 
4465 	/* Skip if the queue is already in the requested state */
4466 	if (enable == !!(rx_reg & I40E_QRX_ENA_QENA_STAT_MASK))
4467 		return;
4468 
4469 	/* turn on/off the queue */
4470 	if (enable)
4471 		rx_reg |= I40E_QRX_ENA_QENA_REQ_MASK;
4472 	else
4473 		rx_reg &= ~I40E_QRX_ENA_QENA_REQ_MASK;
4474 
4475 	wr32(hw, I40E_QRX_ENA(pf_q), rx_reg);
4476 }
4477 
4478 /**
4479  * i40e_control_wait_rx_q
4480  * @pf: the PF structure
4481  * @pf_q: queue being configured
4482  * @enable: start or stop the rings
4483  *
4484  * This function enables or disables a single queue along with waiting
4485  * for the change to finish. The caller of this function should handle
4486  * the delays needed in the case of disabling queues.
4487  **/
4488 int i40e_control_wait_rx_q(struct i40e_pf *pf, int pf_q, bool enable)
4489 {
4490 	int ret = 0;
4491 
4492 	i40e_control_rx_q(pf, pf_q, enable);
4493 
4494 	/* wait for the change to finish */
4495 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
4496 	if (ret)
4497 		return ret;
4498 
4499 	return ret;
4500 }
4501 
4502 /**
4503  * i40e_vsi_control_rx - Start or stop a VSI's rings
4504  * @vsi: the VSI being configured
4505  * @enable: start or stop the rings
4506  **/
4507 static int i40e_vsi_control_rx(struct i40e_vsi *vsi, bool enable)
4508 {
4509 	struct i40e_pf *pf = vsi->back;
4510 	int i, pf_q, ret = 0;
4511 
4512 	pf_q = vsi->base_queue;
4513 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4514 		ret = i40e_control_wait_rx_q(pf, pf_q, enable);
4515 		if (ret) {
4516 			dev_info(&pf->pdev->dev,
4517 				 "VSI seid %d Rx ring %d %sable timeout\n",
4518 				 vsi->seid, pf_q, (enable ? "en" : "dis"));
4519 			break;
4520 		}
4521 	}
4522 
4523 	/* Due to HW errata, on Rx disable only, the register can indicate done
4524 	 * before it really is. Needs 50ms to be sure
4525 	 */
4526 	if (!enable)
4527 		mdelay(50);
4528 
4529 	return ret;
4530 }
4531 
4532 /**
4533  * i40e_vsi_start_rings - Start a VSI's rings
4534  * @vsi: the VSI being configured
4535  **/
4536 int i40e_vsi_start_rings(struct i40e_vsi *vsi)
4537 {
4538 	int ret = 0;
4539 
4540 	/* do rx first for enable and last for disable */
4541 	ret = i40e_vsi_control_rx(vsi, true);
4542 	if (ret)
4543 		return ret;
4544 	ret = i40e_vsi_control_tx(vsi, true);
4545 
4546 	return ret;
4547 }
4548 
4549 /**
4550  * i40e_vsi_stop_rings - Stop a VSI's rings
4551  * @vsi: the VSI being configured
4552  **/
4553 void i40e_vsi_stop_rings(struct i40e_vsi *vsi)
4554 {
4555 	/* When port TX is suspended, don't wait */
4556 	if (test_bit(__I40E_PORT_SUSPENDED, vsi->back->state))
4557 		return i40e_vsi_stop_rings_no_wait(vsi);
4558 
4559 	/* do rx first for enable and last for disable
4560 	 * Ignore return value, we need to shutdown whatever we can
4561 	 */
4562 	i40e_vsi_control_tx(vsi, false);
4563 	i40e_vsi_control_rx(vsi, false);
4564 }
4565 
4566 /**
4567  * i40e_vsi_stop_rings_no_wait - Stop a VSI's rings and do not delay
4568  * @vsi: the VSI being shutdown
4569  *
4570  * This function stops all the rings for a VSI but does not delay to verify
4571  * that rings have been disabled. It is expected that the caller is shutting
4572  * down multiple VSIs at once and will delay together for all the VSIs after
4573  * initiating the shutdown. This is particularly useful for shutting down lots
4574  * of VFs together. Otherwise, a large delay can be incurred while configuring
4575  * each VSI in serial.
4576  **/
4577 void i40e_vsi_stop_rings_no_wait(struct i40e_vsi *vsi)
4578 {
4579 	struct i40e_pf *pf = vsi->back;
4580 	int i, pf_q;
4581 
4582 	pf_q = vsi->base_queue;
4583 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4584 		i40e_control_tx_q(pf, pf_q, false);
4585 		i40e_control_rx_q(pf, pf_q, false);
4586 	}
4587 }
4588 
4589 /**
4590  * i40e_vsi_free_irq - Free the irq association with the OS
4591  * @vsi: the VSI being configured
4592  **/
4593 static void i40e_vsi_free_irq(struct i40e_vsi *vsi)
4594 {
4595 	struct i40e_pf *pf = vsi->back;
4596 	struct i40e_hw *hw = &pf->hw;
4597 	int base = vsi->base_vector;
4598 	u32 val, qp;
4599 	int i;
4600 
4601 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4602 		if (!vsi->q_vectors)
4603 			return;
4604 
4605 		if (!vsi->irqs_ready)
4606 			return;
4607 
4608 		vsi->irqs_ready = false;
4609 		for (i = 0; i < vsi->num_q_vectors; i++) {
4610 			int irq_num;
4611 			u16 vector;
4612 
4613 			vector = i + base;
4614 			irq_num = pf->msix_entries[vector].vector;
4615 
4616 			/* free only the irqs that were actually requested */
4617 			if (!vsi->q_vectors[i] ||
4618 			    !vsi->q_vectors[i]->num_ringpairs)
4619 				continue;
4620 
4621 			/* clear the affinity notifier in the IRQ descriptor */
4622 			irq_set_affinity_notifier(irq_num, NULL);
4623 			/* remove our suggested affinity mask for this IRQ */
4624 			irq_set_affinity_hint(irq_num, NULL);
4625 			synchronize_irq(irq_num);
4626 			free_irq(irq_num, vsi->q_vectors[i]);
4627 
4628 			/* Tear down the interrupt queue link list
4629 			 *
4630 			 * We know that they come in pairs and always
4631 			 * the Rx first, then the Tx.  To clear the
4632 			 * link list, stick the EOL value into the
4633 			 * next_q field of the registers.
4634 			 */
4635 			val = rd32(hw, I40E_PFINT_LNKLSTN(vector - 1));
4636 			qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4637 				>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4638 			val |= I40E_QUEUE_END_OF_LIST
4639 				<< I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4640 			wr32(hw, I40E_PFINT_LNKLSTN(vector - 1), val);
4641 
4642 			while (qp != I40E_QUEUE_END_OF_LIST) {
4643 				u32 next;
4644 
4645 				val = rd32(hw, I40E_QINT_RQCTL(qp));
4646 
4647 				val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4648 					 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4649 					 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4650 					 I40E_QINT_RQCTL_INTEVENT_MASK);
4651 
4652 				val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4653 					 I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4654 
4655 				wr32(hw, I40E_QINT_RQCTL(qp), val);
4656 
4657 				val = rd32(hw, I40E_QINT_TQCTL(qp));
4658 
4659 				next = (val & I40E_QINT_TQCTL_NEXTQ_INDX_MASK)
4660 					>> I40E_QINT_TQCTL_NEXTQ_INDX_SHIFT;
4661 
4662 				val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4663 					 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4664 					 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4665 					 I40E_QINT_TQCTL_INTEVENT_MASK);
4666 
4667 				val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4668 					 I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4669 
4670 				wr32(hw, I40E_QINT_TQCTL(qp), val);
4671 				qp = next;
4672 			}
4673 		}
4674 	} else {
4675 		free_irq(pf->pdev->irq, pf);
4676 
4677 		val = rd32(hw, I40E_PFINT_LNKLST0);
4678 		qp = (val & I40E_PFINT_LNKLSTN_FIRSTQ_INDX_MASK)
4679 			>> I40E_PFINT_LNKLSTN_FIRSTQ_INDX_SHIFT;
4680 		val |= I40E_QUEUE_END_OF_LIST
4681 			<< I40E_PFINT_LNKLST0_FIRSTQ_INDX_SHIFT;
4682 		wr32(hw, I40E_PFINT_LNKLST0, val);
4683 
4684 		val = rd32(hw, I40E_QINT_RQCTL(qp));
4685 		val &= ~(I40E_QINT_RQCTL_MSIX_INDX_MASK  |
4686 			 I40E_QINT_RQCTL_MSIX0_INDX_MASK |
4687 			 I40E_QINT_RQCTL_CAUSE_ENA_MASK  |
4688 			 I40E_QINT_RQCTL_INTEVENT_MASK);
4689 
4690 		val |= (I40E_QINT_RQCTL_ITR_INDX_MASK |
4691 			I40E_QINT_RQCTL_NEXTQ_INDX_MASK);
4692 
4693 		wr32(hw, I40E_QINT_RQCTL(qp), val);
4694 
4695 		val = rd32(hw, I40E_QINT_TQCTL(qp));
4696 
4697 		val &= ~(I40E_QINT_TQCTL_MSIX_INDX_MASK  |
4698 			 I40E_QINT_TQCTL_MSIX0_INDX_MASK |
4699 			 I40E_QINT_TQCTL_CAUSE_ENA_MASK  |
4700 			 I40E_QINT_TQCTL_INTEVENT_MASK);
4701 
4702 		val |= (I40E_QINT_TQCTL_ITR_INDX_MASK |
4703 			I40E_QINT_TQCTL_NEXTQ_INDX_MASK);
4704 
4705 		wr32(hw, I40E_QINT_TQCTL(qp), val);
4706 	}
4707 }
4708 
4709 /**
4710  * i40e_free_q_vector - Free memory allocated for specific interrupt vector
4711  * @vsi: the VSI being configured
4712  * @v_idx: Index of vector to be freed
4713  *
4714  * This function frees the memory allocated to the q_vector.  In addition if
4715  * NAPI is enabled it will delete any references to the NAPI struct prior
4716  * to freeing the q_vector.
4717  **/
4718 static void i40e_free_q_vector(struct i40e_vsi *vsi, int v_idx)
4719 {
4720 	struct i40e_q_vector *q_vector = vsi->q_vectors[v_idx];
4721 	struct i40e_ring *ring;
4722 
4723 	if (!q_vector)
4724 		return;
4725 
4726 	/* disassociate q_vector from rings */
4727 	i40e_for_each_ring(ring, q_vector->tx)
4728 		ring->q_vector = NULL;
4729 
4730 	i40e_for_each_ring(ring, q_vector->rx)
4731 		ring->q_vector = NULL;
4732 
4733 	/* only VSI w/ an associated netdev is set up w/ NAPI */
4734 	if (vsi->netdev)
4735 		netif_napi_del(&q_vector->napi);
4736 
4737 	vsi->q_vectors[v_idx] = NULL;
4738 
4739 	kfree_rcu(q_vector, rcu);
4740 }
4741 
4742 /**
4743  * i40e_vsi_free_q_vectors - Free memory allocated for interrupt vectors
4744  * @vsi: the VSI being un-configured
4745  *
4746  * This frees the memory allocated to the q_vectors and
4747  * deletes references to the NAPI struct.
4748  **/
4749 static void i40e_vsi_free_q_vectors(struct i40e_vsi *vsi)
4750 {
4751 	int v_idx;
4752 
4753 	for (v_idx = 0; v_idx < vsi->num_q_vectors; v_idx++)
4754 		i40e_free_q_vector(vsi, v_idx);
4755 }
4756 
4757 /**
4758  * i40e_reset_interrupt_capability - Disable interrupt setup in OS
4759  * @pf: board private structure
4760  **/
4761 static void i40e_reset_interrupt_capability(struct i40e_pf *pf)
4762 {
4763 	/* If we're in Legacy mode, the interrupt was cleaned in vsi_close */
4764 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
4765 		pci_disable_msix(pf->pdev);
4766 		kfree(pf->msix_entries);
4767 		pf->msix_entries = NULL;
4768 		kfree(pf->irq_pile);
4769 		pf->irq_pile = NULL;
4770 	} else if (pf->flags & I40E_FLAG_MSI_ENABLED) {
4771 		pci_disable_msi(pf->pdev);
4772 	}
4773 	pf->flags &= ~(I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
4774 }
4775 
4776 /**
4777  * i40e_clear_interrupt_scheme - Clear the current interrupt scheme settings
4778  * @pf: board private structure
4779  *
4780  * We go through and clear interrupt specific resources and reset the structure
4781  * to pre-load conditions
4782  **/
4783 static void i40e_clear_interrupt_scheme(struct i40e_pf *pf)
4784 {
4785 	int i;
4786 
4787 	i40e_free_misc_vector(pf);
4788 
4789 	i40e_put_lump(pf->irq_pile, pf->iwarp_base_vector,
4790 		      I40E_IWARP_IRQ_PILE_ID);
4791 
4792 	i40e_put_lump(pf->irq_pile, 0, I40E_PILE_VALID_BIT-1);
4793 	for (i = 0; i < pf->num_alloc_vsi; i++)
4794 		if (pf->vsi[i])
4795 			i40e_vsi_free_q_vectors(pf->vsi[i]);
4796 	i40e_reset_interrupt_capability(pf);
4797 }
4798 
4799 /**
4800  * i40e_napi_enable_all - Enable NAPI for all q_vectors in the VSI
4801  * @vsi: the VSI being configured
4802  **/
4803 static void i40e_napi_enable_all(struct i40e_vsi *vsi)
4804 {
4805 	int q_idx;
4806 
4807 	if (!vsi->netdev)
4808 		return;
4809 
4810 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4811 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4812 
4813 		if (q_vector->rx.ring || q_vector->tx.ring)
4814 			napi_enable(&q_vector->napi);
4815 	}
4816 }
4817 
4818 /**
4819  * i40e_napi_disable_all - Disable NAPI for all q_vectors in the VSI
4820  * @vsi: the VSI being configured
4821  **/
4822 static void i40e_napi_disable_all(struct i40e_vsi *vsi)
4823 {
4824 	int q_idx;
4825 
4826 	if (!vsi->netdev)
4827 		return;
4828 
4829 	for (q_idx = 0; q_idx < vsi->num_q_vectors; q_idx++) {
4830 		struct i40e_q_vector *q_vector = vsi->q_vectors[q_idx];
4831 
4832 		if (q_vector->rx.ring || q_vector->tx.ring)
4833 			napi_disable(&q_vector->napi);
4834 	}
4835 }
4836 
4837 /**
4838  * i40e_vsi_close - Shut down a VSI
4839  * @vsi: the vsi to be quelled
4840  **/
4841 static void i40e_vsi_close(struct i40e_vsi *vsi)
4842 {
4843 	struct i40e_pf *pf = vsi->back;
4844 	if (!test_and_set_bit(__I40E_VSI_DOWN, vsi->state))
4845 		i40e_down(vsi);
4846 	i40e_vsi_free_irq(vsi);
4847 	i40e_vsi_free_tx_resources(vsi);
4848 	i40e_vsi_free_rx_resources(vsi);
4849 	vsi->current_netdev_flags = 0;
4850 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
4851 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
4852 		set_bit(__I40E_CLIENT_RESET, pf->state);
4853 }
4854 
4855 /**
4856  * i40e_quiesce_vsi - Pause a given VSI
4857  * @vsi: the VSI being paused
4858  **/
4859 static void i40e_quiesce_vsi(struct i40e_vsi *vsi)
4860 {
4861 	if (test_bit(__I40E_VSI_DOWN, vsi->state))
4862 		return;
4863 
4864 	set_bit(__I40E_VSI_NEEDS_RESTART, vsi->state);
4865 	if (vsi->netdev && netif_running(vsi->netdev))
4866 		vsi->netdev->netdev_ops->ndo_stop(vsi->netdev);
4867 	else
4868 		i40e_vsi_close(vsi);
4869 }
4870 
4871 /**
4872  * i40e_unquiesce_vsi - Resume a given VSI
4873  * @vsi: the VSI being resumed
4874  **/
4875 static void i40e_unquiesce_vsi(struct i40e_vsi *vsi)
4876 {
4877 	if (!test_and_clear_bit(__I40E_VSI_NEEDS_RESTART, vsi->state))
4878 		return;
4879 
4880 	if (vsi->netdev && netif_running(vsi->netdev))
4881 		vsi->netdev->netdev_ops->ndo_open(vsi->netdev);
4882 	else
4883 		i40e_vsi_open(vsi);   /* this clears the DOWN bit */
4884 }
4885 
4886 /**
4887  * i40e_pf_quiesce_all_vsi - Pause all VSIs on a PF
4888  * @pf: the PF
4889  **/
4890 static void i40e_pf_quiesce_all_vsi(struct i40e_pf *pf)
4891 {
4892 	int v;
4893 
4894 	for (v = 0; v < pf->num_alloc_vsi; v++) {
4895 		if (pf->vsi[v])
4896 			i40e_quiesce_vsi(pf->vsi[v]);
4897 	}
4898 }
4899 
4900 /**
4901  * i40e_pf_unquiesce_all_vsi - Resume all VSIs on a PF
4902  * @pf: the PF
4903  **/
4904 static void i40e_pf_unquiesce_all_vsi(struct i40e_pf *pf)
4905 {
4906 	int v;
4907 
4908 	for (v = 0; v < pf->num_alloc_vsi; v++) {
4909 		if (pf->vsi[v])
4910 			i40e_unquiesce_vsi(pf->vsi[v]);
4911 	}
4912 }
4913 
4914 /**
4915  * i40e_vsi_wait_queues_disabled - Wait for VSI's queues to be disabled
4916  * @vsi: the VSI being configured
4917  *
4918  * Wait until all queues on a given VSI have been disabled.
4919  **/
4920 int i40e_vsi_wait_queues_disabled(struct i40e_vsi *vsi)
4921 {
4922 	struct i40e_pf *pf = vsi->back;
4923 	int i, pf_q, ret;
4924 
4925 	pf_q = vsi->base_queue;
4926 	for (i = 0; i < vsi->num_queue_pairs; i++, pf_q++) {
4927 		/* Check and wait for the Tx queue */
4928 		ret = i40e_pf_txq_wait(pf, pf_q, false);
4929 		if (ret) {
4930 			dev_info(&pf->pdev->dev,
4931 				 "VSI seid %d Tx ring %d disable timeout\n",
4932 				 vsi->seid, pf_q);
4933 			return ret;
4934 		}
4935 
4936 		if (!i40e_enabled_xdp_vsi(vsi))
4937 			goto wait_rx;
4938 
4939 		/* Check and wait for the XDP Tx queue */
4940 		ret = i40e_pf_txq_wait(pf, pf_q + vsi->alloc_queue_pairs,
4941 				       false);
4942 		if (ret) {
4943 			dev_info(&pf->pdev->dev,
4944 				 "VSI seid %d XDP Tx ring %d disable timeout\n",
4945 				 vsi->seid, pf_q);
4946 			return ret;
4947 		}
4948 wait_rx:
4949 		/* Check and wait for the Rx queue */
4950 		ret = i40e_pf_rxq_wait(pf, pf_q, false);
4951 		if (ret) {
4952 			dev_info(&pf->pdev->dev,
4953 				 "VSI seid %d Rx ring %d disable timeout\n",
4954 				 vsi->seid, pf_q);
4955 			return ret;
4956 		}
4957 	}
4958 
4959 	return 0;
4960 }
4961 
4962 #ifdef CONFIG_I40E_DCB
4963 /**
4964  * i40e_pf_wait_queues_disabled - Wait for all queues of PF VSIs to be disabled
4965  * @pf: the PF
4966  *
4967  * This function waits for the queues to be in disabled state for all the
4968  * VSIs that are managed by this PF.
4969  **/
4970 static int i40e_pf_wait_queues_disabled(struct i40e_pf *pf)
4971 {
4972 	int v, ret = 0;
4973 
4974 	for (v = 0; v < pf->hw.func_caps.num_vsis; v++) {
4975 		if (pf->vsi[v]) {
4976 			ret = i40e_vsi_wait_queues_disabled(pf->vsi[v]);
4977 			if (ret)
4978 				break;
4979 		}
4980 	}
4981 
4982 	return ret;
4983 }
4984 
4985 #endif
4986 
4987 /**
4988  * i40e_get_iscsi_tc_map - Return TC map for iSCSI APP
4989  * @pf: pointer to PF
4990  *
4991  * Get TC map for ISCSI PF type that will include iSCSI TC
4992  * and LAN TC.
4993  **/
4994 static u8 i40e_get_iscsi_tc_map(struct i40e_pf *pf)
4995 {
4996 	struct i40e_dcb_app_priority_table app;
4997 	struct i40e_hw *hw = &pf->hw;
4998 	u8 enabled_tc = 1; /* TC0 is always enabled */
4999 	u8 tc, i;
5000 	/* Get the iSCSI APP TLV */
5001 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5002 
5003 	for (i = 0; i < dcbcfg->numapps; i++) {
5004 		app = dcbcfg->app[i];
5005 		if (app.selector == I40E_APP_SEL_TCPIP &&
5006 		    app.protocolid == I40E_APP_PROTOID_ISCSI) {
5007 			tc = dcbcfg->etscfg.prioritytable[app.priority];
5008 			enabled_tc |= BIT(tc);
5009 			break;
5010 		}
5011 	}
5012 
5013 	return enabled_tc;
5014 }
5015 
5016 /**
5017  * i40e_dcb_get_num_tc -  Get the number of TCs from DCBx config
5018  * @dcbcfg: the corresponding DCBx configuration structure
5019  *
5020  * Return the number of TCs from given DCBx configuration
5021  **/
5022 static u8 i40e_dcb_get_num_tc(struct i40e_dcbx_config *dcbcfg)
5023 {
5024 	int i, tc_unused = 0;
5025 	u8 num_tc = 0;
5026 	u8 ret = 0;
5027 
5028 	/* Scan the ETS Config Priority Table to find
5029 	 * traffic class enabled for a given priority
5030 	 * and create a bitmask of enabled TCs
5031 	 */
5032 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++)
5033 		num_tc |= BIT(dcbcfg->etscfg.prioritytable[i]);
5034 
5035 	/* Now scan the bitmask to check for
5036 	 * contiguous TCs starting with TC0
5037 	 */
5038 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5039 		if (num_tc & BIT(i)) {
5040 			if (!tc_unused) {
5041 				ret++;
5042 			} else {
5043 				pr_err("Non-contiguous TC - Disabling DCB\n");
5044 				return 1;
5045 			}
5046 		} else {
5047 			tc_unused = 1;
5048 		}
5049 	}
5050 
5051 	/* There is always at least TC0 */
5052 	if (!ret)
5053 		ret = 1;
5054 
5055 	return ret;
5056 }
5057 
5058 /**
5059  * i40e_dcb_get_enabled_tc - Get enabled traffic classes
5060  * @dcbcfg: the corresponding DCBx configuration structure
5061  *
5062  * Query the current DCB configuration and return the number of
5063  * traffic classes enabled from the given DCBX config
5064  **/
5065 static u8 i40e_dcb_get_enabled_tc(struct i40e_dcbx_config *dcbcfg)
5066 {
5067 	u8 num_tc = i40e_dcb_get_num_tc(dcbcfg);
5068 	u8 enabled_tc = 1;
5069 	u8 i;
5070 
5071 	for (i = 0; i < num_tc; i++)
5072 		enabled_tc |= BIT(i);
5073 
5074 	return enabled_tc;
5075 }
5076 
5077 /**
5078  * i40e_mqprio_get_enabled_tc - Get enabled traffic classes
5079  * @pf: PF being queried
5080  *
5081  * Query the current MQPRIO configuration and return the number of
5082  * traffic classes enabled.
5083  **/
5084 static u8 i40e_mqprio_get_enabled_tc(struct i40e_pf *pf)
5085 {
5086 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
5087 	u8 num_tc = vsi->mqprio_qopt.qopt.num_tc;
5088 	u8 enabled_tc = 1, i;
5089 
5090 	for (i = 1; i < num_tc; i++)
5091 		enabled_tc |= BIT(i);
5092 	return enabled_tc;
5093 }
5094 
5095 /**
5096  * i40e_pf_get_num_tc - Get enabled traffic classes for PF
5097  * @pf: PF being queried
5098  *
5099  * Return number of traffic classes enabled for the given PF
5100  **/
5101 static u8 i40e_pf_get_num_tc(struct i40e_pf *pf)
5102 {
5103 	struct i40e_hw *hw = &pf->hw;
5104 	u8 i, enabled_tc = 1;
5105 	u8 num_tc = 0;
5106 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5107 
5108 	if (pf->flags & I40E_FLAG_TC_MQPRIO)
5109 		return pf->vsi[pf->lan_vsi]->mqprio_qopt.qopt.num_tc;
5110 
5111 	/* If neither MQPRIO nor DCB is enabled, then always use single TC */
5112 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5113 		return 1;
5114 
5115 	/* SFP mode will be enabled for all TCs on port */
5116 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5117 		return i40e_dcb_get_num_tc(dcbcfg);
5118 
5119 	/* MFP mode return count of enabled TCs for this PF */
5120 	if (pf->hw.func_caps.iscsi)
5121 		enabled_tc =  i40e_get_iscsi_tc_map(pf);
5122 	else
5123 		return 1; /* Only TC0 */
5124 
5125 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5126 		if (enabled_tc & BIT(i))
5127 			num_tc++;
5128 	}
5129 	return num_tc;
5130 }
5131 
5132 /**
5133  * i40e_pf_get_pf_tc_map - Get bitmap for enabled traffic classes
5134  * @pf: PF being queried
5135  *
5136  * Return a bitmap for enabled traffic classes for this PF.
5137  **/
5138 static u8 i40e_pf_get_tc_map(struct i40e_pf *pf)
5139 {
5140 	if (pf->flags & I40E_FLAG_TC_MQPRIO)
5141 		return i40e_mqprio_get_enabled_tc(pf);
5142 
5143 	/* If neither MQPRIO nor DCB is enabled for this PF then just return
5144 	 * default TC
5145 	 */
5146 	if (!(pf->flags & I40E_FLAG_DCB_ENABLED))
5147 		return I40E_DEFAULT_TRAFFIC_CLASS;
5148 
5149 	/* SFP mode we want PF to be enabled for all TCs */
5150 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
5151 		return i40e_dcb_get_enabled_tc(&pf->hw.local_dcbx_config);
5152 
5153 	/* MFP enabled and iSCSI PF type */
5154 	if (pf->hw.func_caps.iscsi)
5155 		return i40e_get_iscsi_tc_map(pf);
5156 	else
5157 		return I40E_DEFAULT_TRAFFIC_CLASS;
5158 }
5159 
5160 /**
5161  * i40e_vsi_get_bw_info - Query VSI BW Information
5162  * @vsi: the VSI being queried
5163  *
5164  * Returns 0 on success, negative value on failure
5165  **/
5166 static int i40e_vsi_get_bw_info(struct i40e_vsi *vsi)
5167 {
5168 	struct i40e_aqc_query_vsi_ets_sla_config_resp bw_ets_config = {0};
5169 	struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5170 	struct i40e_pf *pf = vsi->back;
5171 	struct i40e_hw *hw = &pf->hw;
5172 	i40e_status ret;
5173 	u32 tc_bw_max;
5174 	int i;
5175 
5176 	/* Get the VSI level BW configuration */
5177 	ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid, &bw_config, NULL);
5178 	if (ret) {
5179 		dev_info(&pf->pdev->dev,
5180 			 "couldn't get PF vsi bw config, err %s aq_err %s\n",
5181 			 i40e_stat_str(&pf->hw, ret),
5182 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5183 		return -EINVAL;
5184 	}
5185 
5186 	/* Get the VSI level BW configuration per TC */
5187 	ret = i40e_aq_query_vsi_ets_sla_config(hw, vsi->seid, &bw_ets_config,
5188 					       NULL);
5189 	if (ret) {
5190 		dev_info(&pf->pdev->dev,
5191 			 "couldn't get PF vsi ets bw config, err %s aq_err %s\n",
5192 			 i40e_stat_str(&pf->hw, ret),
5193 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5194 		return -EINVAL;
5195 	}
5196 
5197 	if (bw_config.tc_valid_bits != bw_ets_config.tc_valid_bits) {
5198 		dev_info(&pf->pdev->dev,
5199 			 "Enabled TCs mismatch from querying VSI BW info 0x%08x 0x%08x\n",
5200 			 bw_config.tc_valid_bits,
5201 			 bw_ets_config.tc_valid_bits);
5202 		/* Still continuing */
5203 	}
5204 
5205 	vsi->bw_limit = le16_to_cpu(bw_config.port_bw_limit);
5206 	vsi->bw_max_quanta = bw_config.max_bw;
5207 	tc_bw_max = le16_to_cpu(bw_ets_config.tc_bw_max[0]) |
5208 		    (le16_to_cpu(bw_ets_config.tc_bw_max[1]) << 16);
5209 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5210 		vsi->bw_ets_share_credits[i] = bw_ets_config.share_credits[i];
5211 		vsi->bw_ets_limit_credits[i] =
5212 					le16_to_cpu(bw_ets_config.credits[i]);
5213 		/* 3 bits out of 4 for each TC */
5214 		vsi->bw_ets_max_quanta[i] = (u8)((tc_bw_max >> (i*4)) & 0x7);
5215 	}
5216 
5217 	return 0;
5218 }
5219 
5220 /**
5221  * i40e_vsi_configure_bw_alloc - Configure VSI BW allocation per TC
5222  * @vsi: the VSI being configured
5223  * @enabled_tc: TC bitmap
5224  * @bw_share: BW shared credits per TC
5225  *
5226  * Returns 0 on success, negative value on failure
5227  **/
5228 static int i40e_vsi_configure_bw_alloc(struct i40e_vsi *vsi, u8 enabled_tc,
5229 				       u8 *bw_share)
5230 {
5231 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5232 	struct i40e_pf *pf = vsi->back;
5233 	i40e_status ret;
5234 	int i;
5235 
5236 	/* There is no need to reset BW when mqprio mode is on.  */
5237 	if (pf->flags & I40E_FLAG_TC_MQPRIO)
5238 		return 0;
5239 	if (!vsi->mqprio_qopt.qopt.hw && !(pf->flags & I40E_FLAG_DCB_ENABLED)) {
5240 		ret = i40e_set_bw_limit(vsi, vsi->seid, 0);
5241 		if (ret)
5242 			dev_info(&pf->pdev->dev,
5243 				 "Failed to reset tx rate for vsi->seid %u\n",
5244 				 vsi->seid);
5245 		return ret;
5246 	}
5247 	bw_data.tc_valid_bits = enabled_tc;
5248 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5249 		bw_data.tc_bw_credits[i] = bw_share[i];
5250 
5251 	ret = i40e_aq_config_vsi_tc_bw(&pf->hw, vsi->seid, &bw_data, NULL);
5252 	if (ret) {
5253 		dev_info(&pf->pdev->dev,
5254 			 "AQ command Config VSI BW allocation per TC failed = %d\n",
5255 			 pf->hw.aq.asq_last_status);
5256 		return -EINVAL;
5257 	}
5258 
5259 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5260 		vsi->info.qs_handle[i] = bw_data.qs_handles[i];
5261 
5262 	return 0;
5263 }
5264 
5265 /**
5266  * i40e_vsi_config_netdev_tc - Setup the netdev TC configuration
5267  * @vsi: the VSI being configured
5268  * @enabled_tc: TC map to be enabled
5269  *
5270  **/
5271 static void i40e_vsi_config_netdev_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5272 {
5273 	struct net_device *netdev = vsi->netdev;
5274 	struct i40e_pf *pf = vsi->back;
5275 	struct i40e_hw *hw = &pf->hw;
5276 	u8 netdev_tc = 0;
5277 	int i;
5278 	struct i40e_dcbx_config *dcbcfg = &hw->local_dcbx_config;
5279 
5280 	if (!netdev)
5281 		return;
5282 
5283 	if (!enabled_tc) {
5284 		netdev_reset_tc(netdev);
5285 		return;
5286 	}
5287 
5288 	/* Set up actual enabled TCs on the VSI */
5289 	if (netdev_set_num_tc(netdev, vsi->tc_config.numtc))
5290 		return;
5291 
5292 	/* set per TC queues for the VSI */
5293 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5294 		/* Only set TC queues for enabled tcs
5295 		 *
5296 		 * e.g. For a VSI that has TC0 and TC3 enabled the
5297 		 * enabled_tc bitmap would be 0x00001001; the driver
5298 		 * will set the numtc for netdev as 2 that will be
5299 		 * referenced by the netdev layer as TC 0 and 1.
5300 		 */
5301 		if (vsi->tc_config.enabled_tc & BIT(i))
5302 			netdev_set_tc_queue(netdev,
5303 					vsi->tc_config.tc_info[i].netdev_tc,
5304 					vsi->tc_config.tc_info[i].qcount,
5305 					vsi->tc_config.tc_info[i].qoffset);
5306 	}
5307 
5308 	if (pf->flags & I40E_FLAG_TC_MQPRIO)
5309 		return;
5310 
5311 	/* Assign UP2TC map for the VSI */
5312 	for (i = 0; i < I40E_MAX_USER_PRIORITY; i++) {
5313 		/* Get the actual TC# for the UP */
5314 		u8 ets_tc = dcbcfg->etscfg.prioritytable[i];
5315 		/* Get the mapped netdev TC# for the UP */
5316 		netdev_tc =  vsi->tc_config.tc_info[ets_tc].netdev_tc;
5317 		netdev_set_prio_tc_map(netdev, i, netdev_tc);
5318 	}
5319 }
5320 
5321 /**
5322  * i40e_vsi_update_queue_map - Update our copy of VSi info with new queue map
5323  * @vsi: the VSI being configured
5324  * @ctxt: the ctxt buffer returned from AQ VSI update param command
5325  **/
5326 static void i40e_vsi_update_queue_map(struct i40e_vsi *vsi,
5327 				      struct i40e_vsi_context *ctxt)
5328 {
5329 	/* copy just the sections touched not the entire info
5330 	 * since not all sections are valid as returned by
5331 	 * update vsi params
5332 	 */
5333 	vsi->info.mapping_flags = ctxt->info.mapping_flags;
5334 	memcpy(&vsi->info.queue_mapping,
5335 	       &ctxt->info.queue_mapping, sizeof(vsi->info.queue_mapping));
5336 	memcpy(&vsi->info.tc_mapping, ctxt->info.tc_mapping,
5337 	       sizeof(vsi->info.tc_mapping));
5338 }
5339 
5340 /**
5341  * i40e_vsi_config_tc - Configure VSI Tx Scheduler for given TC map
5342  * @vsi: VSI to be configured
5343  * @enabled_tc: TC bitmap
5344  *
5345  * This configures a particular VSI for TCs that are mapped to the
5346  * given TC bitmap. It uses default bandwidth share for TCs across
5347  * VSIs to configure TC for a particular VSI.
5348  *
5349  * NOTE:
5350  * It is expected that the VSI queues have been quisced before calling
5351  * this function.
5352  **/
5353 static int i40e_vsi_config_tc(struct i40e_vsi *vsi, u8 enabled_tc)
5354 {
5355 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5356 	struct i40e_pf *pf = vsi->back;
5357 	struct i40e_hw *hw = &pf->hw;
5358 	struct i40e_vsi_context ctxt;
5359 	int ret = 0;
5360 	int i;
5361 
5362 	/* Check if enabled_tc is same as existing or new TCs */
5363 	if (vsi->tc_config.enabled_tc == enabled_tc &&
5364 	    vsi->mqprio_qopt.mode != TC_MQPRIO_MODE_CHANNEL)
5365 		return ret;
5366 
5367 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5368 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5369 		if (enabled_tc & BIT(i))
5370 			bw_share[i] = 1;
5371 	}
5372 
5373 	ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5374 	if (ret) {
5375 		struct i40e_aqc_query_vsi_bw_config_resp bw_config = {0};
5376 
5377 		dev_info(&pf->pdev->dev,
5378 			 "Failed configuring TC map %d for VSI %d\n",
5379 			 enabled_tc, vsi->seid);
5380 		ret = i40e_aq_query_vsi_bw_config(hw, vsi->seid,
5381 						  &bw_config, NULL);
5382 		if (ret) {
5383 			dev_info(&pf->pdev->dev,
5384 				 "Failed querying vsi bw info, err %s aq_err %s\n",
5385 				 i40e_stat_str(hw, ret),
5386 				 i40e_aq_str(hw, hw->aq.asq_last_status));
5387 			goto out;
5388 		}
5389 		if ((bw_config.tc_valid_bits & enabled_tc) != enabled_tc) {
5390 			u8 valid_tc = bw_config.tc_valid_bits & enabled_tc;
5391 
5392 			if (!valid_tc)
5393 				valid_tc = bw_config.tc_valid_bits;
5394 			/* Always enable TC0, no matter what */
5395 			valid_tc |= 1;
5396 			dev_info(&pf->pdev->dev,
5397 				 "Requested tc 0x%x, but FW reports 0x%x as valid. Attempting to use 0x%x.\n",
5398 				 enabled_tc, bw_config.tc_valid_bits, valid_tc);
5399 			enabled_tc = valid_tc;
5400 		}
5401 
5402 		ret = i40e_vsi_configure_bw_alloc(vsi, enabled_tc, bw_share);
5403 		if (ret) {
5404 			dev_err(&pf->pdev->dev,
5405 				"Unable to  configure TC map %d for VSI %d\n",
5406 				enabled_tc, vsi->seid);
5407 			goto out;
5408 		}
5409 	}
5410 
5411 	/* Update Queue Pairs Mapping for currently enabled UPs */
5412 	ctxt.seid = vsi->seid;
5413 	ctxt.pf_num = vsi->back->hw.pf_id;
5414 	ctxt.vf_num = 0;
5415 	ctxt.uplink_seid = vsi->uplink_seid;
5416 	ctxt.info = vsi->info;
5417 	if (vsi->back->flags & I40E_FLAG_TC_MQPRIO) {
5418 		ret = i40e_vsi_setup_queue_map_mqprio(vsi, &ctxt, enabled_tc);
5419 		if (ret)
5420 			goto out;
5421 	} else {
5422 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
5423 	}
5424 
5425 	/* On destroying the qdisc, reset vsi->rss_size, as number of enabled
5426 	 * queues changed.
5427 	 */
5428 	if (!vsi->mqprio_qopt.qopt.hw && vsi->reconfig_rss) {
5429 		vsi->rss_size = min_t(int, vsi->back->alloc_rss_size,
5430 				      vsi->num_queue_pairs);
5431 		ret = i40e_vsi_config_rss(vsi);
5432 		if (ret) {
5433 			dev_info(&vsi->back->pdev->dev,
5434 				 "Failed to reconfig rss for num_queues\n");
5435 			return ret;
5436 		}
5437 		vsi->reconfig_rss = false;
5438 	}
5439 	if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
5440 		ctxt.info.valid_sections |=
5441 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
5442 		ctxt.info.queueing_opt_flags |= I40E_AQ_VSI_QUE_OPT_TCP_ENA;
5443 	}
5444 
5445 	/* Update the VSI after updating the VSI queue-mapping
5446 	 * information
5447 	 */
5448 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
5449 	if (ret) {
5450 		dev_info(&pf->pdev->dev,
5451 			 "Update vsi tc config failed, err %s aq_err %s\n",
5452 			 i40e_stat_str(hw, ret),
5453 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5454 		goto out;
5455 	}
5456 	/* update the local VSI info with updated queue map */
5457 	i40e_vsi_update_queue_map(vsi, &ctxt);
5458 	vsi->info.valid_sections = 0;
5459 
5460 	/* Update current VSI BW information */
5461 	ret = i40e_vsi_get_bw_info(vsi);
5462 	if (ret) {
5463 		dev_info(&pf->pdev->dev,
5464 			 "Failed updating vsi bw info, err %s aq_err %s\n",
5465 			 i40e_stat_str(hw, ret),
5466 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5467 		goto out;
5468 	}
5469 
5470 	/* Update the netdev TC setup */
5471 	i40e_vsi_config_netdev_tc(vsi, enabled_tc);
5472 out:
5473 	return ret;
5474 }
5475 
5476 /**
5477  * i40e_get_link_speed - Returns link speed for the interface
5478  * @vsi: VSI to be configured
5479  *
5480  **/
5481 static int i40e_get_link_speed(struct i40e_vsi *vsi)
5482 {
5483 	struct i40e_pf *pf = vsi->back;
5484 
5485 	switch (pf->hw.phy.link_info.link_speed) {
5486 	case I40E_LINK_SPEED_40GB:
5487 		return 40000;
5488 	case I40E_LINK_SPEED_25GB:
5489 		return 25000;
5490 	case I40E_LINK_SPEED_20GB:
5491 		return 20000;
5492 	case I40E_LINK_SPEED_10GB:
5493 		return 10000;
5494 	case I40E_LINK_SPEED_1GB:
5495 		return 1000;
5496 	default:
5497 		return -EINVAL;
5498 	}
5499 }
5500 
5501 /**
5502  * i40e_set_bw_limit - setup BW limit for Tx traffic based on max_tx_rate
5503  * @vsi: VSI to be configured
5504  * @seid: seid of the channel/VSI
5505  * @max_tx_rate: max TX rate to be configured as BW limit
5506  *
5507  * Helper function to set BW limit for a given VSI
5508  **/
5509 int i40e_set_bw_limit(struct i40e_vsi *vsi, u16 seid, u64 max_tx_rate)
5510 {
5511 	struct i40e_pf *pf = vsi->back;
5512 	u64 credits = 0;
5513 	int speed = 0;
5514 	int ret = 0;
5515 
5516 	speed = i40e_get_link_speed(vsi);
5517 	if (max_tx_rate > speed) {
5518 		dev_err(&pf->pdev->dev,
5519 			"Invalid max tx rate %llu specified for VSI seid %d.",
5520 			max_tx_rate, seid);
5521 		return -EINVAL;
5522 	}
5523 	if (max_tx_rate && max_tx_rate < 50) {
5524 		dev_warn(&pf->pdev->dev,
5525 			 "Setting max tx rate to minimum usable value of 50Mbps.\n");
5526 		max_tx_rate = 50;
5527 	}
5528 
5529 	/* Tx rate credits are in values of 50Mbps, 0 is disabled */
5530 	credits = max_tx_rate;
5531 	do_div(credits, I40E_BW_CREDIT_DIVISOR);
5532 	ret = i40e_aq_config_vsi_bw_limit(&pf->hw, seid, credits,
5533 					  I40E_MAX_BW_INACTIVE_ACCUM, NULL);
5534 	if (ret)
5535 		dev_err(&pf->pdev->dev,
5536 			"Failed set tx rate (%llu Mbps) for vsi->seid %u, err %s aq_err %s\n",
5537 			max_tx_rate, seid, i40e_stat_str(&pf->hw, ret),
5538 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
5539 	return ret;
5540 }
5541 
5542 /**
5543  * i40e_remove_queue_channels - Remove queue channels for the TCs
5544  * @vsi: VSI to be configured
5545  *
5546  * Remove queue channels for the TCs
5547  **/
5548 static void i40e_remove_queue_channels(struct i40e_vsi *vsi)
5549 {
5550 	enum i40e_admin_queue_err last_aq_status;
5551 	struct i40e_cloud_filter *cfilter;
5552 	struct i40e_channel *ch, *ch_tmp;
5553 	struct i40e_pf *pf = vsi->back;
5554 	struct hlist_node *node;
5555 	int ret, i;
5556 
5557 	/* Reset rss size that was stored when reconfiguring rss for
5558 	 * channel VSIs with non-power-of-2 queue count.
5559 	 */
5560 	vsi->current_rss_size = 0;
5561 
5562 	/* perform cleanup for channels if they exist */
5563 	if (list_empty(&vsi->ch_list))
5564 		return;
5565 
5566 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5567 		struct i40e_vsi *p_vsi;
5568 
5569 		list_del(&ch->list);
5570 		p_vsi = ch->parent_vsi;
5571 		if (!p_vsi || !ch->initialized) {
5572 			kfree(ch);
5573 			continue;
5574 		}
5575 		/* Reset queue contexts */
5576 		for (i = 0; i < ch->num_queue_pairs; i++) {
5577 			struct i40e_ring *tx_ring, *rx_ring;
5578 			u16 pf_q;
5579 
5580 			pf_q = ch->base_queue + i;
5581 			tx_ring = vsi->tx_rings[pf_q];
5582 			tx_ring->ch = NULL;
5583 
5584 			rx_ring = vsi->rx_rings[pf_q];
5585 			rx_ring->ch = NULL;
5586 		}
5587 
5588 		/* Reset BW configured for this VSI via mqprio */
5589 		ret = i40e_set_bw_limit(vsi, ch->seid, 0);
5590 		if (ret)
5591 			dev_info(&vsi->back->pdev->dev,
5592 				 "Failed to reset tx rate for ch->seid %u\n",
5593 				 ch->seid);
5594 
5595 		/* delete cloud filters associated with this channel */
5596 		hlist_for_each_entry_safe(cfilter, node,
5597 					  &pf->cloud_filter_list, cloud_node) {
5598 			if (cfilter->seid != ch->seid)
5599 				continue;
5600 
5601 			hash_del(&cfilter->cloud_node);
5602 			if (cfilter->dst_port)
5603 				ret = i40e_add_del_cloud_filter_big_buf(vsi,
5604 									cfilter,
5605 									false);
5606 			else
5607 				ret = i40e_add_del_cloud_filter(vsi, cfilter,
5608 								false);
5609 			last_aq_status = pf->hw.aq.asq_last_status;
5610 			if (ret)
5611 				dev_info(&pf->pdev->dev,
5612 					 "Failed to delete cloud filter, err %s aq_err %s\n",
5613 					 i40e_stat_str(&pf->hw, ret),
5614 					 i40e_aq_str(&pf->hw, last_aq_status));
5615 			kfree(cfilter);
5616 		}
5617 
5618 		/* delete VSI from FW */
5619 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
5620 					     NULL);
5621 		if (ret)
5622 			dev_err(&vsi->back->pdev->dev,
5623 				"unable to remove channel (%d) for parent VSI(%d)\n",
5624 				ch->seid, p_vsi->seid);
5625 		kfree(ch);
5626 	}
5627 	INIT_LIST_HEAD(&vsi->ch_list);
5628 }
5629 
5630 /**
5631  * i40e_is_any_channel - channel exist or not
5632  * @vsi: ptr to VSI to which channels are associated with
5633  *
5634  * Returns true or false if channel(s) exist for associated VSI or not
5635  **/
5636 static bool i40e_is_any_channel(struct i40e_vsi *vsi)
5637 {
5638 	struct i40e_channel *ch, *ch_tmp;
5639 
5640 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5641 		if (ch->initialized)
5642 			return true;
5643 	}
5644 
5645 	return false;
5646 }
5647 
5648 /**
5649  * i40e_get_max_queues_for_channel
5650  * @vsi: ptr to VSI to which channels are associated with
5651  *
5652  * Helper function which returns max value among the queue counts set on the
5653  * channels/TCs created.
5654  **/
5655 static int i40e_get_max_queues_for_channel(struct i40e_vsi *vsi)
5656 {
5657 	struct i40e_channel *ch, *ch_tmp;
5658 	int max = 0;
5659 
5660 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
5661 		if (!ch->initialized)
5662 			continue;
5663 		if (ch->num_queue_pairs > max)
5664 			max = ch->num_queue_pairs;
5665 	}
5666 
5667 	return max;
5668 }
5669 
5670 /**
5671  * i40e_validate_num_queues - validate num_queues w.r.t channel
5672  * @pf: ptr to PF device
5673  * @num_queues: number of queues
5674  * @vsi: the parent VSI
5675  * @reconfig_rss: indicates should the RSS be reconfigured or not
5676  *
5677  * This function validates number of queues in the context of new channel
5678  * which is being established and determines if RSS should be reconfigured
5679  * or not for parent VSI.
5680  **/
5681 static int i40e_validate_num_queues(struct i40e_pf *pf, int num_queues,
5682 				    struct i40e_vsi *vsi, bool *reconfig_rss)
5683 {
5684 	int max_ch_queues;
5685 
5686 	if (!reconfig_rss)
5687 		return -EINVAL;
5688 
5689 	*reconfig_rss = false;
5690 	if (vsi->current_rss_size) {
5691 		if (num_queues > vsi->current_rss_size) {
5692 			dev_dbg(&pf->pdev->dev,
5693 				"Error: num_queues (%d) > vsi's current_size(%d)\n",
5694 				num_queues, vsi->current_rss_size);
5695 			return -EINVAL;
5696 		} else if ((num_queues < vsi->current_rss_size) &&
5697 			   (!is_power_of_2(num_queues))) {
5698 			dev_dbg(&pf->pdev->dev,
5699 				"Error: num_queues (%d) < vsi's current_size(%d), but not power of 2\n",
5700 				num_queues, vsi->current_rss_size);
5701 			return -EINVAL;
5702 		}
5703 	}
5704 
5705 	if (!is_power_of_2(num_queues)) {
5706 		/* Find the max num_queues configured for channel if channel
5707 		 * exist.
5708 		 * if channel exist, then enforce 'num_queues' to be more than
5709 		 * max ever queues configured for channel.
5710 		 */
5711 		max_ch_queues = i40e_get_max_queues_for_channel(vsi);
5712 		if (num_queues < max_ch_queues) {
5713 			dev_dbg(&pf->pdev->dev,
5714 				"Error: num_queues (%d) < max queues configured for channel(%d)\n",
5715 				num_queues, max_ch_queues);
5716 			return -EINVAL;
5717 		}
5718 		*reconfig_rss = true;
5719 	}
5720 
5721 	return 0;
5722 }
5723 
5724 /**
5725  * i40e_vsi_reconfig_rss - reconfig RSS based on specified rss_size
5726  * @vsi: the VSI being setup
5727  * @rss_size: size of RSS, accordingly LUT gets reprogrammed
5728  *
5729  * This function reconfigures RSS by reprogramming LUTs using 'rss_size'
5730  **/
5731 static int i40e_vsi_reconfig_rss(struct i40e_vsi *vsi, u16 rss_size)
5732 {
5733 	struct i40e_pf *pf = vsi->back;
5734 	u8 seed[I40E_HKEY_ARRAY_SIZE];
5735 	struct i40e_hw *hw = &pf->hw;
5736 	int local_rss_size;
5737 	u8 *lut;
5738 	int ret;
5739 
5740 	if (!vsi->rss_size)
5741 		return -EINVAL;
5742 
5743 	if (rss_size > vsi->rss_size)
5744 		return -EINVAL;
5745 
5746 	local_rss_size = min_t(int, vsi->rss_size, rss_size);
5747 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
5748 	if (!lut)
5749 		return -ENOMEM;
5750 
5751 	/* Ignoring user configured lut if there is one */
5752 	i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, local_rss_size);
5753 
5754 	/* Use user configured hash key if there is one, otherwise
5755 	 * use default.
5756 	 */
5757 	if (vsi->rss_hkey_user)
5758 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
5759 	else
5760 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
5761 
5762 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
5763 	if (ret) {
5764 		dev_info(&pf->pdev->dev,
5765 			 "Cannot set RSS lut, err %s aq_err %s\n",
5766 			 i40e_stat_str(hw, ret),
5767 			 i40e_aq_str(hw, hw->aq.asq_last_status));
5768 		kfree(lut);
5769 		return ret;
5770 	}
5771 	kfree(lut);
5772 
5773 	/* Do the update w.r.t. storing rss_size */
5774 	if (!vsi->orig_rss_size)
5775 		vsi->orig_rss_size = vsi->rss_size;
5776 	vsi->current_rss_size = local_rss_size;
5777 
5778 	return ret;
5779 }
5780 
5781 /**
5782  * i40e_channel_setup_queue_map - Setup a channel queue map
5783  * @pf: ptr to PF device
5784  * @vsi: the VSI being setup
5785  * @ctxt: VSI context structure
5786  * @ch: ptr to channel structure
5787  *
5788  * Setup queue map for a specific channel
5789  **/
5790 static void i40e_channel_setup_queue_map(struct i40e_pf *pf,
5791 					 struct i40e_vsi_context *ctxt,
5792 					 struct i40e_channel *ch)
5793 {
5794 	u16 qcount, qmap, sections = 0;
5795 	u8 offset = 0;
5796 	int pow;
5797 
5798 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
5799 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
5800 
5801 	qcount = min_t(int, ch->num_queue_pairs, pf->num_lan_msix);
5802 	ch->num_queue_pairs = qcount;
5803 
5804 	/* find the next higher power-of-2 of num queue pairs */
5805 	pow = ilog2(qcount);
5806 	if (!is_power_of_2(qcount))
5807 		pow++;
5808 
5809 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
5810 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
5811 
5812 	/* Setup queue TC[0].qmap for given VSI context */
5813 	ctxt->info.tc_mapping[0] = cpu_to_le16(qmap);
5814 
5815 	ctxt->info.up_enable_bits = 0x1; /* TC0 enabled */
5816 	ctxt->info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
5817 	ctxt->info.queue_mapping[0] = cpu_to_le16(ch->base_queue);
5818 	ctxt->info.valid_sections |= cpu_to_le16(sections);
5819 }
5820 
5821 /**
5822  * i40e_add_channel - add a channel by adding VSI
5823  * @pf: ptr to PF device
5824  * @uplink_seid: underlying HW switching element (VEB) ID
5825  * @ch: ptr to channel structure
5826  *
5827  * Add a channel (VSI) using add_vsi and queue_map
5828  **/
5829 static int i40e_add_channel(struct i40e_pf *pf, u16 uplink_seid,
5830 			    struct i40e_channel *ch)
5831 {
5832 	struct i40e_hw *hw = &pf->hw;
5833 	struct i40e_vsi_context ctxt;
5834 	u8 enabled_tc = 0x1; /* TC0 enabled */
5835 	int ret;
5836 
5837 	if (ch->type != I40E_VSI_VMDQ2) {
5838 		dev_info(&pf->pdev->dev,
5839 			 "add new vsi failed, ch->type %d\n", ch->type);
5840 		return -EINVAL;
5841 	}
5842 
5843 	memset(&ctxt, 0, sizeof(ctxt));
5844 	ctxt.pf_num = hw->pf_id;
5845 	ctxt.vf_num = 0;
5846 	ctxt.uplink_seid = uplink_seid;
5847 	ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
5848 	if (ch->type == I40E_VSI_VMDQ2)
5849 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
5850 
5851 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED) {
5852 		ctxt.info.valid_sections |=
5853 		     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
5854 		ctxt.info.switch_id =
5855 		   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
5856 	}
5857 
5858 	/* Set queue map for a given VSI context */
5859 	i40e_channel_setup_queue_map(pf, &ctxt, ch);
5860 
5861 	/* Now time to create VSI */
5862 	ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
5863 	if (ret) {
5864 		dev_info(&pf->pdev->dev,
5865 			 "add new vsi failed, err %s aq_err %s\n",
5866 			 i40e_stat_str(&pf->hw, ret),
5867 			 i40e_aq_str(&pf->hw,
5868 				     pf->hw.aq.asq_last_status));
5869 		return -ENOENT;
5870 	}
5871 
5872 	/* Success, update channel, set enabled_tc only if the channel
5873 	 * is not a macvlan
5874 	 */
5875 	ch->enabled_tc = !i40e_is_channel_macvlan(ch) && enabled_tc;
5876 	ch->seid = ctxt.seid;
5877 	ch->vsi_number = ctxt.vsi_number;
5878 	ch->stat_counter_idx = cpu_to_le16(ctxt.info.stat_counter_idx);
5879 
5880 	/* copy just the sections touched not the entire info
5881 	 * since not all sections are valid as returned by
5882 	 * update vsi params
5883 	 */
5884 	ch->info.mapping_flags = ctxt.info.mapping_flags;
5885 	memcpy(&ch->info.queue_mapping,
5886 	       &ctxt.info.queue_mapping, sizeof(ctxt.info.queue_mapping));
5887 	memcpy(&ch->info.tc_mapping, ctxt.info.tc_mapping,
5888 	       sizeof(ctxt.info.tc_mapping));
5889 
5890 	return 0;
5891 }
5892 
5893 static int i40e_channel_config_bw(struct i40e_vsi *vsi, struct i40e_channel *ch,
5894 				  u8 *bw_share)
5895 {
5896 	struct i40e_aqc_configure_vsi_tc_bw_data bw_data;
5897 	i40e_status ret;
5898 	int i;
5899 
5900 	bw_data.tc_valid_bits = ch->enabled_tc;
5901 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5902 		bw_data.tc_bw_credits[i] = bw_share[i];
5903 
5904 	ret = i40e_aq_config_vsi_tc_bw(&vsi->back->hw, ch->seid,
5905 				       &bw_data, NULL);
5906 	if (ret) {
5907 		dev_info(&vsi->back->pdev->dev,
5908 			 "Config VSI BW allocation per TC failed, aq_err: %d for new_vsi->seid %u\n",
5909 			 vsi->back->hw.aq.asq_last_status, ch->seid);
5910 		return -EINVAL;
5911 	}
5912 
5913 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++)
5914 		ch->info.qs_handle[i] = bw_data.qs_handles[i];
5915 
5916 	return 0;
5917 }
5918 
5919 /**
5920  * i40e_channel_config_tx_ring - config TX ring associated with new channel
5921  * @pf: ptr to PF device
5922  * @vsi: the VSI being setup
5923  * @ch: ptr to channel structure
5924  *
5925  * Configure TX rings associated with channel (VSI) since queues are being
5926  * from parent VSI.
5927  **/
5928 static int i40e_channel_config_tx_ring(struct i40e_pf *pf,
5929 				       struct i40e_vsi *vsi,
5930 				       struct i40e_channel *ch)
5931 {
5932 	i40e_status ret;
5933 	int i;
5934 	u8 bw_share[I40E_MAX_TRAFFIC_CLASS] = {0};
5935 
5936 	/* Enable ETS TCs with equal BW Share for now across all VSIs */
5937 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
5938 		if (ch->enabled_tc & BIT(i))
5939 			bw_share[i] = 1;
5940 	}
5941 
5942 	/* configure BW for new VSI */
5943 	ret = i40e_channel_config_bw(vsi, ch, bw_share);
5944 	if (ret) {
5945 		dev_info(&vsi->back->pdev->dev,
5946 			 "Failed configuring TC map %d for channel (seid %u)\n",
5947 			 ch->enabled_tc, ch->seid);
5948 		return ret;
5949 	}
5950 
5951 	for (i = 0; i < ch->num_queue_pairs; i++) {
5952 		struct i40e_ring *tx_ring, *rx_ring;
5953 		u16 pf_q;
5954 
5955 		pf_q = ch->base_queue + i;
5956 
5957 		/* Get to TX ring ptr of main VSI, for re-setup TX queue
5958 		 * context
5959 		 */
5960 		tx_ring = vsi->tx_rings[pf_q];
5961 		tx_ring->ch = ch;
5962 
5963 		/* Get the RX ring ptr */
5964 		rx_ring = vsi->rx_rings[pf_q];
5965 		rx_ring->ch = ch;
5966 	}
5967 
5968 	return 0;
5969 }
5970 
5971 /**
5972  * i40e_setup_hw_channel - setup new channel
5973  * @pf: ptr to PF device
5974  * @vsi: the VSI being setup
5975  * @ch: ptr to channel structure
5976  * @uplink_seid: underlying HW switching element (VEB) ID
5977  * @type: type of channel to be created (VMDq2/VF)
5978  *
5979  * Setup new channel (VSI) based on specified type (VMDq2/VF)
5980  * and configures TX rings accordingly
5981  **/
5982 static inline int i40e_setup_hw_channel(struct i40e_pf *pf,
5983 					struct i40e_vsi *vsi,
5984 					struct i40e_channel *ch,
5985 					u16 uplink_seid, u8 type)
5986 {
5987 	int ret;
5988 
5989 	ch->initialized = false;
5990 	ch->base_queue = vsi->next_base_queue;
5991 	ch->type = type;
5992 
5993 	/* Proceed with creation of channel (VMDq2) VSI */
5994 	ret = i40e_add_channel(pf, uplink_seid, ch);
5995 	if (ret) {
5996 		dev_info(&pf->pdev->dev,
5997 			 "failed to add_channel using uplink_seid %u\n",
5998 			 uplink_seid);
5999 		return ret;
6000 	}
6001 
6002 	/* Mark the successful creation of channel */
6003 	ch->initialized = true;
6004 
6005 	/* Reconfigure TX queues using QTX_CTL register */
6006 	ret = i40e_channel_config_tx_ring(pf, vsi, ch);
6007 	if (ret) {
6008 		dev_info(&pf->pdev->dev,
6009 			 "failed to configure TX rings for channel %u\n",
6010 			 ch->seid);
6011 		return ret;
6012 	}
6013 
6014 	/* update 'next_base_queue' */
6015 	vsi->next_base_queue = vsi->next_base_queue + ch->num_queue_pairs;
6016 	dev_dbg(&pf->pdev->dev,
6017 		"Added channel: vsi_seid %u, vsi_number %u, stat_counter_idx %u, num_queue_pairs %u, pf->next_base_queue %d\n",
6018 		ch->seid, ch->vsi_number, ch->stat_counter_idx,
6019 		ch->num_queue_pairs,
6020 		vsi->next_base_queue);
6021 	return ret;
6022 }
6023 
6024 /**
6025  * i40e_setup_channel - setup new channel using uplink element
6026  * @pf: ptr to PF device
6027  * @type: type of channel to be created (VMDq2/VF)
6028  * @uplink_seid: underlying HW switching element (VEB) ID
6029  * @ch: ptr to channel structure
6030  *
6031  * Setup new channel (VSI) based on specified type (VMDq2/VF)
6032  * and uplink switching element (uplink_seid)
6033  **/
6034 static bool i40e_setup_channel(struct i40e_pf *pf, struct i40e_vsi *vsi,
6035 			       struct i40e_channel *ch)
6036 {
6037 	u8 vsi_type;
6038 	u16 seid;
6039 	int ret;
6040 
6041 	if (vsi->type == I40E_VSI_MAIN) {
6042 		vsi_type = I40E_VSI_VMDQ2;
6043 	} else {
6044 		dev_err(&pf->pdev->dev, "unsupported parent vsi type(%d)\n",
6045 			vsi->type);
6046 		return false;
6047 	}
6048 
6049 	/* underlying switching element */
6050 	seid = pf->vsi[pf->lan_vsi]->uplink_seid;
6051 
6052 	/* create channel (VSI), configure TX rings */
6053 	ret = i40e_setup_hw_channel(pf, vsi, ch, seid, vsi_type);
6054 	if (ret) {
6055 		dev_err(&pf->pdev->dev, "failed to setup hw_channel\n");
6056 		return false;
6057 	}
6058 
6059 	return ch->initialized ? true : false;
6060 }
6061 
6062 /**
6063  * i40e_validate_and_set_switch_mode - sets up switch mode correctly
6064  * @vsi: ptr to VSI which has PF backing
6065  *
6066  * Sets up switch mode correctly if it needs to be changed and perform
6067  * what are allowed modes.
6068  **/
6069 static int i40e_validate_and_set_switch_mode(struct i40e_vsi *vsi)
6070 {
6071 	u8 mode;
6072 	struct i40e_pf *pf = vsi->back;
6073 	struct i40e_hw *hw = &pf->hw;
6074 	int ret;
6075 
6076 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_dev_capabilities);
6077 	if (ret)
6078 		return -EINVAL;
6079 
6080 	if (hw->dev_caps.switch_mode) {
6081 		/* if switch mode is set, support mode2 (non-tunneled for
6082 		 * cloud filter) for now
6083 		 */
6084 		u32 switch_mode = hw->dev_caps.switch_mode &
6085 				  I40E_SWITCH_MODE_MASK;
6086 		if (switch_mode >= I40E_CLOUD_FILTER_MODE1) {
6087 			if (switch_mode == I40E_CLOUD_FILTER_MODE2)
6088 				return 0;
6089 			dev_err(&pf->pdev->dev,
6090 				"Invalid switch_mode (%d), only non-tunneled mode for cloud filter is supported\n",
6091 				hw->dev_caps.switch_mode);
6092 			return -EINVAL;
6093 		}
6094 	}
6095 
6096 	/* Set Bit 7 to be valid */
6097 	mode = I40E_AQ_SET_SWITCH_BIT7_VALID;
6098 
6099 	/* Set L4type for TCP support */
6100 	mode |= I40E_AQ_SET_SWITCH_L4_TYPE_TCP;
6101 
6102 	/* Set cloud filter mode */
6103 	mode |= I40E_AQ_SET_SWITCH_MODE_NON_TUNNEL;
6104 
6105 	/* Prep mode field for set_switch_config */
6106 	ret = i40e_aq_set_switch_config(hw, pf->last_sw_conf_flags,
6107 					pf->last_sw_conf_valid_flags,
6108 					mode, NULL);
6109 	if (ret && hw->aq.asq_last_status != I40E_AQ_RC_ESRCH)
6110 		dev_err(&pf->pdev->dev,
6111 			"couldn't set switch config bits, err %s aq_err %s\n",
6112 			i40e_stat_str(hw, ret),
6113 			i40e_aq_str(hw,
6114 				    hw->aq.asq_last_status));
6115 
6116 	return ret;
6117 }
6118 
6119 /**
6120  * i40e_create_queue_channel - function to create channel
6121  * @vsi: VSI to be configured
6122  * @ch: ptr to channel (it contains channel specific params)
6123  *
6124  * This function creates channel (VSI) using num_queues specified by user,
6125  * reconfigs RSS if needed.
6126  **/
6127 int i40e_create_queue_channel(struct i40e_vsi *vsi,
6128 			      struct i40e_channel *ch)
6129 {
6130 	struct i40e_pf *pf = vsi->back;
6131 	bool reconfig_rss;
6132 	int err;
6133 
6134 	if (!ch)
6135 		return -EINVAL;
6136 
6137 	if (!ch->num_queue_pairs) {
6138 		dev_err(&pf->pdev->dev, "Invalid num_queues requested: %d\n",
6139 			ch->num_queue_pairs);
6140 		return -EINVAL;
6141 	}
6142 
6143 	/* validate user requested num_queues for channel */
6144 	err = i40e_validate_num_queues(pf, ch->num_queue_pairs, vsi,
6145 				       &reconfig_rss);
6146 	if (err) {
6147 		dev_info(&pf->pdev->dev, "Failed to validate num_queues (%d)\n",
6148 			 ch->num_queue_pairs);
6149 		return -EINVAL;
6150 	}
6151 
6152 	/* By default we are in VEPA mode, if this is the first VF/VMDq
6153 	 * VSI to be added switch to VEB mode.
6154 	 */
6155 	if ((!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) ||
6156 	    (!i40e_is_any_channel(vsi))) {
6157 		if (!is_power_of_2(vsi->tc_config.tc_info[0].qcount)) {
6158 			dev_dbg(&pf->pdev->dev,
6159 				"Failed to create channel. Override queues (%u) not power of 2\n",
6160 				vsi->tc_config.tc_info[0].qcount);
6161 			return -EINVAL;
6162 		}
6163 
6164 		if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
6165 			pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
6166 
6167 			if (vsi->type == I40E_VSI_MAIN) {
6168 				if (pf->flags & I40E_FLAG_TC_MQPRIO)
6169 					i40e_do_reset(pf, I40E_PF_RESET_FLAG,
6170 						      true);
6171 				else
6172 					i40e_do_reset_safe(pf,
6173 							   I40E_PF_RESET_FLAG);
6174 			}
6175 		}
6176 		/* now onwards for main VSI, number of queues will be value
6177 		 * of TC0's queue count
6178 		 */
6179 	}
6180 
6181 	/* By this time, vsi->cnt_q_avail shall be set to non-zero and
6182 	 * it should be more than num_queues
6183 	 */
6184 	if (!vsi->cnt_q_avail || vsi->cnt_q_avail < ch->num_queue_pairs) {
6185 		dev_dbg(&pf->pdev->dev,
6186 			"Error: cnt_q_avail (%u) less than num_queues %d\n",
6187 			vsi->cnt_q_avail, ch->num_queue_pairs);
6188 		return -EINVAL;
6189 	}
6190 
6191 	/* reconfig_rss only if vsi type is MAIN_VSI */
6192 	if (reconfig_rss && (vsi->type == I40E_VSI_MAIN)) {
6193 		err = i40e_vsi_reconfig_rss(vsi, ch->num_queue_pairs);
6194 		if (err) {
6195 			dev_info(&pf->pdev->dev,
6196 				 "Error: unable to reconfig rss for num_queues (%u)\n",
6197 				 ch->num_queue_pairs);
6198 			return -EINVAL;
6199 		}
6200 	}
6201 
6202 	if (!i40e_setup_channel(pf, vsi, ch)) {
6203 		dev_info(&pf->pdev->dev, "Failed to setup channel\n");
6204 		return -EINVAL;
6205 	}
6206 
6207 	dev_info(&pf->pdev->dev,
6208 		 "Setup channel (id:%u) utilizing num_queues %d\n",
6209 		 ch->seid, ch->num_queue_pairs);
6210 
6211 	/* configure VSI for BW limit */
6212 	if (ch->max_tx_rate) {
6213 		u64 credits = ch->max_tx_rate;
6214 
6215 		if (i40e_set_bw_limit(vsi, ch->seid, ch->max_tx_rate))
6216 			return -EINVAL;
6217 
6218 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
6219 		dev_dbg(&pf->pdev->dev,
6220 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
6221 			ch->max_tx_rate,
6222 			credits,
6223 			ch->seid);
6224 	}
6225 
6226 	/* in case of VF, this will be main SRIOV VSI */
6227 	ch->parent_vsi = vsi;
6228 
6229 	/* and update main_vsi's count for queue_available to use */
6230 	vsi->cnt_q_avail -= ch->num_queue_pairs;
6231 
6232 	return 0;
6233 }
6234 
6235 /**
6236  * i40e_configure_queue_channels - Add queue channel for the given TCs
6237  * @vsi: VSI to be configured
6238  *
6239  * Configures queue channel mapping to the given TCs
6240  **/
6241 static int i40e_configure_queue_channels(struct i40e_vsi *vsi)
6242 {
6243 	struct i40e_channel *ch;
6244 	u64 max_rate = 0;
6245 	int ret = 0, i;
6246 
6247 	/* Create app vsi with the TCs. Main VSI with TC0 is already set up */
6248 	vsi->tc_seid_map[0] = vsi->seid;
6249 	for (i = 1; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6250 		if (vsi->tc_config.enabled_tc & BIT(i)) {
6251 			ch = kzalloc(sizeof(*ch), GFP_KERNEL);
6252 			if (!ch) {
6253 				ret = -ENOMEM;
6254 				goto err_free;
6255 			}
6256 
6257 			INIT_LIST_HEAD(&ch->list);
6258 			ch->num_queue_pairs =
6259 				vsi->tc_config.tc_info[i].qcount;
6260 			ch->base_queue =
6261 				vsi->tc_config.tc_info[i].qoffset;
6262 
6263 			/* Bandwidth limit through tc interface is in bytes/s,
6264 			 * change to Mbit/s
6265 			 */
6266 			max_rate = vsi->mqprio_qopt.max_rate[i];
6267 			do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6268 			ch->max_tx_rate = max_rate;
6269 
6270 			list_add_tail(&ch->list, &vsi->ch_list);
6271 
6272 			ret = i40e_create_queue_channel(vsi, ch);
6273 			if (ret) {
6274 				dev_err(&vsi->back->pdev->dev,
6275 					"Failed creating queue channel with TC%d: queues %d\n",
6276 					i, ch->num_queue_pairs);
6277 				goto err_free;
6278 			}
6279 			vsi->tc_seid_map[i] = ch->seid;
6280 		}
6281 	}
6282 	return ret;
6283 
6284 err_free:
6285 	i40e_remove_queue_channels(vsi);
6286 	return ret;
6287 }
6288 
6289 /**
6290  * i40e_veb_config_tc - Configure TCs for given VEB
6291  * @veb: given VEB
6292  * @enabled_tc: TC bitmap
6293  *
6294  * Configures given TC bitmap for VEB (switching) element
6295  **/
6296 int i40e_veb_config_tc(struct i40e_veb *veb, u8 enabled_tc)
6297 {
6298 	struct i40e_aqc_configure_switching_comp_bw_config_data bw_data = {0};
6299 	struct i40e_pf *pf = veb->pf;
6300 	int ret = 0;
6301 	int i;
6302 
6303 	/* No TCs or already enabled TCs just return */
6304 	if (!enabled_tc || veb->enabled_tc == enabled_tc)
6305 		return ret;
6306 
6307 	bw_data.tc_valid_bits = enabled_tc;
6308 	/* bw_data.absolute_credits is not set (relative) */
6309 
6310 	/* Enable ETS TCs with equal BW Share for now */
6311 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6312 		if (enabled_tc & BIT(i))
6313 			bw_data.tc_bw_share_credits[i] = 1;
6314 	}
6315 
6316 	ret = i40e_aq_config_switch_comp_bw_config(&pf->hw, veb->seid,
6317 						   &bw_data, NULL);
6318 	if (ret) {
6319 		dev_info(&pf->pdev->dev,
6320 			 "VEB bw config failed, err %s aq_err %s\n",
6321 			 i40e_stat_str(&pf->hw, ret),
6322 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6323 		goto out;
6324 	}
6325 
6326 	/* Update the BW information */
6327 	ret = i40e_veb_get_bw_info(veb);
6328 	if (ret) {
6329 		dev_info(&pf->pdev->dev,
6330 			 "Failed getting veb bw config, err %s aq_err %s\n",
6331 			 i40e_stat_str(&pf->hw, ret),
6332 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6333 	}
6334 
6335 out:
6336 	return ret;
6337 }
6338 
6339 #ifdef CONFIG_I40E_DCB
6340 /**
6341  * i40e_dcb_reconfigure - Reconfigure all VEBs and VSIs
6342  * @pf: PF struct
6343  *
6344  * Reconfigure VEB/VSIs on a given PF; it is assumed that
6345  * the caller would've quiesce all the VSIs before calling
6346  * this function
6347  **/
6348 static void i40e_dcb_reconfigure(struct i40e_pf *pf)
6349 {
6350 	u8 tc_map = 0;
6351 	int ret;
6352 	u8 v;
6353 
6354 	/* Enable the TCs available on PF to all VEBs */
6355 	tc_map = i40e_pf_get_tc_map(pf);
6356 	for (v = 0; v < I40E_MAX_VEB; v++) {
6357 		if (!pf->veb[v])
6358 			continue;
6359 		ret = i40e_veb_config_tc(pf->veb[v], tc_map);
6360 		if (ret) {
6361 			dev_info(&pf->pdev->dev,
6362 				 "Failed configuring TC for VEB seid=%d\n",
6363 				 pf->veb[v]->seid);
6364 			/* Will try to configure as many components */
6365 		}
6366 	}
6367 
6368 	/* Update each VSI */
6369 	for (v = 0; v < pf->num_alloc_vsi; v++) {
6370 		if (!pf->vsi[v])
6371 			continue;
6372 
6373 		/* - Enable all TCs for the LAN VSI
6374 		 * - For all others keep them at TC0 for now
6375 		 */
6376 		if (v == pf->lan_vsi)
6377 			tc_map = i40e_pf_get_tc_map(pf);
6378 		else
6379 			tc_map = I40E_DEFAULT_TRAFFIC_CLASS;
6380 
6381 		ret = i40e_vsi_config_tc(pf->vsi[v], tc_map);
6382 		if (ret) {
6383 			dev_info(&pf->pdev->dev,
6384 				 "Failed configuring TC for VSI seid=%d\n",
6385 				 pf->vsi[v]->seid);
6386 			/* Will try to configure as many components */
6387 		} else {
6388 			/* Re-configure VSI vectors based on updated TC map */
6389 			i40e_vsi_map_rings_to_vectors(pf->vsi[v]);
6390 			if (pf->vsi[v]->netdev)
6391 				i40e_dcbnl_set_all(pf->vsi[v]);
6392 		}
6393 	}
6394 }
6395 
6396 /**
6397  * i40e_resume_port_tx - Resume port Tx
6398  * @pf: PF struct
6399  *
6400  * Resume a port's Tx and issue a PF reset in case of failure to
6401  * resume.
6402  **/
6403 static int i40e_resume_port_tx(struct i40e_pf *pf)
6404 {
6405 	struct i40e_hw *hw = &pf->hw;
6406 	int ret;
6407 
6408 	ret = i40e_aq_resume_port_tx(hw, NULL);
6409 	if (ret) {
6410 		dev_info(&pf->pdev->dev,
6411 			 "Resume Port Tx failed, err %s aq_err %s\n",
6412 			  i40e_stat_str(&pf->hw, ret),
6413 			  i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6414 		/* Schedule PF reset to recover */
6415 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
6416 		i40e_service_event_schedule(pf);
6417 	}
6418 
6419 	return ret;
6420 }
6421 
6422 /**
6423  * i40e_init_pf_dcb - Initialize DCB configuration
6424  * @pf: PF being configured
6425  *
6426  * Query the current DCB configuration and cache it
6427  * in the hardware structure
6428  **/
6429 static int i40e_init_pf_dcb(struct i40e_pf *pf)
6430 {
6431 	struct i40e_hw *hw = &pf->hw;
6432 	int err = 0;
6433 
6434 	/* Do not enable DCB for SW1 and SW2 images even if the FW is capable
6435 	 * Also do not enable DCBx if FW LLDP agent is disabled
6436 	 */
6437 	if ((pf->hw_features & I40E_HW_NO_DCB_SUPPORT) ||
6438 	    (pf->flags & I40E_FLAG_DISABLE_FW_LLDP)) {
6439 		dev_info(&pf->pdev->dev, "DCB is not supported or FW LLDP is disabled\n");
6440 		err = I40E_NOT_SUPPORTED;
6441 		goto out;
6442 	}
6443 
6444 	err = i40e_init_dcb(hw, true);
6445 	if (!err) {
6446 		/* Device/Function is not DCBX capable */
6447 		if ((!hw->func_caps.dcb) ||
6448 		    (hw->dcbx_status == I40E_DCBX_STATUS_DISABLED)) {
6449 			dev_info(&pf->pdev->dev,
6450 				 "DCBX offload is not supported or is disabled for this PF.\n");
6451 		} else {
6452 			/* When status is not DISABLED then DCBX in FW */
6453 			pf->dcbx_cap = DCB_CAP_DCBX_LLD_MANAGED |
6454 				       DCB_CAP_DCBX_VER_IEEE;
6455 
6456 			pf->flags |= I40E_FLAG_DCB_CAPABLE;
6457 			/* Enable DCB tagging only when more than one TC
6458 			 * or explicitly disable if only one TC
6459 			 */
6460 			if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
6461 				pf->flags |= I40E_FLAG_DCB_ENABLED;
6462 			else
6463 				pf->flags &= ~I40E_FLAG_DCB_ENABLED;
6464 			dev_dbg(&pf->pdev->dev,
6465 				"DCBX offload is supported for this PF.\n");
6466 		}
6467 	} else if (pf->hw.aq.asq_last_status == I40E_AQ_RC_EPERM) {
6468 		dev_info(&pf->pdev->dev, "FW LLDP disabled for this PF.\n");
6469 		pf->flags |= I40E_FLAG_DISABLE_FW_LLDP;
6470 	} else {
6471 		dev_info(&pf->pdev->dev,
6472 			 "Query for DCB configuration failed, err %s aq_err %s\n",
6473 			 i40e_stat_str(&pf->hw, err),
6474 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6475 	}
6476 
6477 out:
6478 	return err;
6479 }
6480 #endif /* CONFIG_I40E_DCB */
6481 #define SPEED_SIZE 14
6482 #define FC_SIZE 8
6483 /**
6484  * i40e_print_link_message - print link up or down
6485  * @vsi: the VSI for which link needs a message
6486  * @isup: true of link is up, false otherwise
6487  */
6488 void i40e_print_link_message(struct i40e_vsi *vsi, bool isup)
6489 {
6490 	enum i40e_aq_link_speed new_speed;
6491 	struct i40e_pf *pf = vsi->back;
6492 	char *speed = "Unknown";
6493 	char *fc = "Unknown";
6494 	char *fec = "";
6495 	char *req_fec = "";
6496 	char *an = "";
6497 
6498 	if (isup)
6499 		new_speed = pf->hw.phy.link_info.link_speed;
6500 	else
6501 		new_speed = I40E_LINK_SPEED_UNKNOWN;
6502 
6503 	if ((vsi->current_isup == isup) && (vsi->current_speed == new_speed))
6504 		return;
6505 	vsi->current_isup = isup;
6506 	vsi->current_speed = new_speed;
6507 	if (!isup) {
6508 		netdev_info(vsi->netdev, "NIC Link is Down\n");
6509 		return;
6510 	}
6511 
6512 	/* Warn user if link speed on NPAR enabled partition is not at
6513 	 * least 10GB
6514 	 */
6515 	if (pf->hw.func_caps.npar_enable &&
6516 	    (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_1GB ||
6517 	     pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_100MB))
6518 		netdev_warn(vsi->netdev,
6519 			    "The partition detected link speed that is less than 10Gbps\n");
6520 
6521 	switch (pf->hw.phy.link_info.link_speed) {
6522 	case I40E_LINK_SPEED_40GB:
6523 		speed = "40 G";
6524 		break;
6525 	case I40E_LINK_SPEED_20GB:
6526 		speed = "20 G";
6527 		break;
6528 	case I40E_LINK_SPEED_25GB:
6529 		speed = "25 G";
6530 		break;
6531 	case I40E_LINK_SPEED_10GB:
6532 		speed = "10 G";
6533 		break;
6534 	case I40E_LINK_SPEED_5GB:
6535 		speed = "5 G";
6536 		break;
6537 	case I40E_LINK_SPEED_2_5GB:
6538 		speed = "2.5 G";
6539 		break;
6540 	case I40E_LINK_SPEED_1GB:
6541 		speed = "1000 M";
6542 		break;
6543 	case I40E_LINK_SPEED_100MB:
6544 		speed = "100 M";
6545 		break;
6546 	default:
6547 		break;
6548 	}
6549 
6550 	switch (pf->hw.fc.current_mode) {
6551 	case I40E_FC_FULL:
6552 		fc = "RX/TX";
6553 		break;
6554 	case I40E_FC_TX_PAUSE:
6555 		fc = "TX";
6556 		break;
6557 	case I40E_FC_RX_PAUSE:
6558 		fc = "RX";
6559 		break;
6560 	default:
6561 		fc = "None";
6562 		break;
6563 	}
6564 
6565 	if (pf->hw.phy.link_info.link_speed == I40E_LINK_SPEED_25GB) {
6566 		req_fec = ", Requested FEC: None";
6567 		fec = ", FEC: None";
6568 		an = ", Autoneg: False";
6569 
6570 		if (pf->hw.phy.link_info.an_info & I40E_AQ_AN_COMPLETED)
6571 			an = ", Autoneg: True";
6572 
6573 		if (pf->hw.phy.link_info.fec_info &
6574 		    I40E_AQ_CONFIG_FEC_KR_ENA)
6575 			fec = ", FEC: CL74 FC-FEC/BASE-R";
6576 		else if (pf->hw.phy.link_info.fec_info &
6577 			 I40E_AQ_CONFIG_FEC_RS_ENA)
6578 			fec = ", FEC: CL108 RS-FEC";
6579 
6580 		/* 'CL108 RS-FEC' should be displayed when RS is requested, or
6581 		 * both RS and FC are requested
6582 		 */
6583 		if (vsi->back->hw.phy.link_info.req_fec_info &
6584 		    (I40E_AQ_REQUEST_FEC_KR | I40E_AQ_REQUEST_FEC_RS)) {
6585 			if (vsi->back->hw.phy.link_info.req_fec_info &
6586 			    I40E_AQ_REQUEST_FEC_RS)
6587 				req_fec = ", Requested FEC: CL108 RS-FEC";
6588 			else
6589 				req_fec = ", Requested FEC: CL74 FC-FEC/BASE-R";
6590 		}
6591 	}
6592 
6593 	netdev_info(vsi->netdev, "NIC Link is Up, %sbps Full Duplex%s%s%s, Flow Control: %s\n",
6594 		    speed, req_fec, fec, an, fc);
6595 }
6596 
6597 /**
6598  * i40e_up_complete - Finish the last steps of bringing up a connection
6599  * @vsi: the VSI being configured
6600  **/
6601 static int i40e_up_complete(struct i40e_vsi *vsi)
6602 {
6603 	struct i40e_pf *pf = vsi->back;
6604 	int err;
6605 
6606 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
6607 		i40e_vsi_configure_msix(vsi);
6608 	else
6609 		i40e_configure_msi_and_legacy(vsi);
6610 
6611 	/* start rings */
6612 	err = i40e_vsi_start_rings(vsi);
6613 	if (err)
6614 		return err;
6615 
6616 	clear_bit(__I40E_VSI_DOWN, vsi->state);
6617 	i40e_napi_enable_all(vsi);
6618 	i40e_vsi_enable_irq(vsi);
6619 
6620 	if ((pf->hw.phy.link_info.link_info & I40E_AQ_LINK_UP) &&
6621 	    (vsi->netdev)) {
6622 		i40e_print_link_message(vsi, true);
6623 		netif_tx_start_all_queues(vsi->netdev);
6624 		netif_carrier_on(vsi->netdev);
6625 	}
6626 
6627 	/* replay FDIR SB filters */
6628 	if (vsi->type == I40E_VSI_FDIR) {
6629 		/* reset fd counters */
6630 		pf->fd_add_err = 0;
6631 		pf->fd_atr_cnt = 0;
6632 		i40e_fdir_filter_restore(vsi);
6633 	}
6634 
6635 	/* On the next run of the service_task, notify any clients of the new
6636 	 * opened netdev
6637 	 */
6638 	set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
6639 	i40e_service_event_schedule(pf);
6640 
6641 	return 0;
6642 }
6643 
6644 /**
6645  * i40e_vsi_reinit_locked - Reset the VSI
6646  * @vsi: the VSI being configured
6647  *
6648  * Rebuild the ring structs after some configuration
6649  * has changed, e.g. MTU size.
6650  **/
6651 static void i40e_vsi_reinit_locked(struct i40e_vsi *vsi)
6652 {
6653 	struct i40e_pf *pf = vsi->back;
6654 
6655 	WARN_ON(in_interrupt());
6656 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state))
6657 		usleep_range(1000, 2000);
6658 	i40e_down(vsi);
6659 
6660 	i40e_up(vsi);
6661 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
6662 }
6663 
6664 /**
6665  * i40e_up - Bring the connection back up after being down
6666  * @vsi: the VSI being configured
6667  **/
6668 int i40e_up(struct i40e_vsi *vsi)
6669 {
6670 	int err;
6671 
6672 	err = i40e_vsi_configure(vsi);
6673 	if (!err)
6674 		err = i40e_up_complete(vsi);
6675 
6676 	return err;
6677 }
6678 
6679 /**
6680  * i40e_force_link_state - Force the link status
6681  * @pf: board private structure
6682  * @is_up: whether the link state should be forced up or down
6683  **/
6684 static i40e_status i40e_force_link_state(struct i40e_pf *pf, bool is_up)
6685 {
6686 	struct i40e_aq_get_phy_abilities_resp abilities;
6687 	struct i40e_aq_set_phy_config config = {0};
6688 	struct i40e_hw *hw = &pf->hw;
6689 	i40e_status err;
6690 	u64 mask;
6691 	u8 speed;
6692 
6693 	/* Card might've been put in an unstable state by other drivers
6694 	 * and applications, which causes incorrect speed values being
6695 	 * set on startup. In order to clear speed registers, we call
6696 	 * get_phy_capabilities twice, once to get initial state of
6697 	 * available speeds, and once to get current PHY config.
6698 	 */
6699 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities,
6700 					   NULL);
6701 	if (err) {
6702 		dev_err(&pf->pdev->dev,
6703 			"failed to get phy cap., ret =  %s last_status =  %s\n",
6704 			i40e_stat_str(hw, err),
6705 			i40e_aq_str(hw, hw->aq.asq_last_status));
6706 		return err;
6707 	}
6708 	speed = abilities.link_speed;
6709 
6710 	/* Get the current phy config */
6711 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities,
6712 					   NULL);
6713 	if (err) {
6714 		dev_err(&pf->pdev->dev,
6715 			"failed to get phy cap., ret =  %s last_status =  %s\n",
6716 			i40e_stat_str(hw, err),
6717 			i40e_aq_str(hw, hw->aq.asq_last_status));
6718 		return err;
6719 	}
6720 
6721 	/* If link needs to go up, but was not forced to go down,
6722 	 * and its speed values are OK, no need for a flap
6723 	 */
6724 	if (is_up && abilities.phy_type != 0 && abilities.link_speed != 0)
6725 		return I40E_SUCCESS;
6726 
6727 	/* To force link we need to set bits for all supported PHY types,
6728 	 * but there are now more than 32, so we need to split the bitmap
6729 	 * across two fields.
6730 	 */
6731 	mask = I40E_PHY_TYPES_BITMASK;
6732 	config.phy_type = is_up ? cpu_to_le32((u32)(mask & 0xffffffff)) : 0;
6733 	config.phy_type_ext = is_up ? (u8)((mask >> 32) & 0xff) : 0;
6734 	/* Copy the old settings, except of phy_type */
6735 	config.abilities = abilities.abilities;
6736 	if (abilities.link_speed != 0)
6737 		config.link_speed = abilities.link_speed;
6738 	else
6739 		config.link_speed = speed;
6740 	config.eee_capability = abilities.eee_capability;
6741 	config.eeer = abilities.eeer_val;
6742 	config.low_power_ctrl = abilities.d3_lpan;
6743 	config.fec_config = abilities.fec_cfg_curr_mod_ext_info &
6744 			    I40E_AQ_PHY_FEC_CONFIG_MASK;
6745 	err = i40e_aq_set_phy_config(hw, &config, NULL);
6746 
6747 	if (err) {
6748 		dev_err(&pf->pdev->dev,
6749 			"set phy config ret =  %s last_status =  %s\n",
6750 			i40e_stat_str(&pf->hw, err),
6751 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
6752 		return err;
6753 	}
6754 
6755 	/* Update the link info */
6756 	err = i40e_update_link_info(hw);
6757 	if (err) {
6758 		/* Wait a little bit (on 40G cards it sometimes takes a really
6759 		 * long time for link to come back from the atomic reset)
6760 		 * and try once more
6761 		 */
6762 		msleep(1000);
6763 		i40e_update_link_info(hw);
6764 	}
6765 
6766 	i40e_aq_set_link_restart_an(hw, true, NULL);
6767 
6768 	return I40E_SUCCESS;
6769 }
6770 
6771 /**
6772  * i40e_down - Shutdown the connection processing
6773  * @vsi: the VSI being stopped
6774  **/
6775 void i40e_down(struct i40e_vsi *vsi)
6776 {
6777 	int i;
6778 
6779 	/* It is assumed that the caller of this function
6780 	 * sets the vsi->state __I40E_VSI_DOWN bit.
6781 	 */
6782 	if (vsi->netdev) {
6783 		netif_carrier_off(vsi->netdev);
6784 		netif_tx_disable(vsi->netdev);
6785 	}
6786 	i40e_vsi_disable_irq(vsi);
6787 	i40e_vsi_stop_rings(vsi);
6788 	if (vsi->type == I40E_VSI_MAIN &&
6789 	    vsi->back->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED)
6790 		i40e_force_link_state(vsi->back, false);
6791 	i40e_napi_disable_all(vsi);
6792 
6793 	for (i = 0; i < vsi->num_queue_pairs; i++) {
6794 		i40e_clean_tx_ring(vsi->tx_rings[i]);
6795 		if (i40e_enabled_xdp_vsi(vsi)) {
6796 			/* Make sure that in-progress ndo_xdp_xmit
6797 			 * calls are completed.
6798 			 */
6799 			synchronize_rcu();
6800 			i40e_clean_tx_ring(vsi->xdp_rings[i]);
6801 		}
6802 		i40e_clean_rx_ring(vsi->rx_rings[i]);
6803 	}
6804 
6805 }
6806 
6807 /**
6808  * i40e_validate_mqprio_qopt- validate queue mapping info
6809  * @vsi: the VSI being configured
6810  * @mqprio_qopt: queue parametrs
6811  **/
6812 static int i40e_validate_mqprio_qopt(struct i40e_vsi *vsi,
6813 				     struct tc_mqprio_qopt_offload *mqprio_qopt)
6814 {
6815 	u64 sum_max_rate = 0;
6816 	u64 max_rate = 0;
6817 	int i;
6818 
6819 	if (mqprio_qopt->qopt.offset[0] != 0 ||
6820 	    mqprio_qopt->qopt.num_tc < 1 ||
6821 	    mqprio_qopt->qopt.num_tc > I40E_MAX_TRAFFIC_CLASS)
6822 		return -EINVAL;
6823 	for (i = 0; ; i++) {
6824 		if (!mqprio_qopt->qopt.count[i])
6825 			return -EINVAL;
6826 		if (mqprio_qopt->min_rate[i]) {
6827 			dev_err(&vsi->back->pdev->dev,
6828 				"Invalid min tx rate (greater than 0) specified\n");
6829 			return -EINVAL;
6830 		}
6831 		max_rate = mqprio_qopt->max_rate[i];
6832 		do_div(max_rate, I40E_BW_MBPS_DIVISOR);
6833 		sum_max_rate += max_rate;
6834 
6835 		if (i >= mqprio_qopt->qopt.num_tc - 1)
6836 			break;
6837 		if (mqprio_qopt->qopt.offset[i + 1] !=
6838 		    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i]))
6839 			return -EINVAL;
6840 	}
6841 	if (vsi->num_queue_pairs <
6842 	    (mqprio_qopt->qopt.offset[i] + mqprio_qopt->qopt.count[i])) {
6843 		return -EINVAL;
6844 	}
6845 	if (sum_max_rate > i40e_get_link_speed(vsi)) {
6846 		dev_err(&vsi->back->pdev->dev,
6847 			"Invalid max tx rate specified\n");
6848 		return -EINVAL;
6849 	}
6850 	return 0;
6851 }
6852 
6853 /**
6854  * i40e_vsi_set_default_tc_config - set default values for tc configuration
6855  * @vsi: the VSI being configured
6856  **/
6857 static void i40e_vsi_set_default_tc_config(struct i40e_vsi *vsi)
6858 {
6859 	u16 qcount;
6860 	int i;
6861 
6862 	/* Only TC0 is enabled */
6863 	vsi->tc_config.numtc = 1;
6864 	vsi->tc_config.enabled_tc = 1;
6865 	qcount = min_t(int, vsi->alloc_queue_pairs,
6866 		       i40e_pf_get_max_q_per_tc(vsi->back));
6867 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
6868 		/* For the TC that is not enabled set the offset to to default
6869 		 * queue and allocate one queue for the given TC.
6870 		 */
6871 		vsi->tc_config.tc_info[i].qoffset = 0;
6872 		if (i == 0)
6873 			vsi->tc_config.tc_info[i].qcount = qcount;
6874 		else
6875 			vsi->tc_config.tc_info[i].qcount = 1;
6876 		vsi->tc_config.tc_info[i].netdev_tc = 0;
6877 	}
6878 }
6879 
6880 /**
6881  * i40e_del_macvlan_filter
6882  * @hw: pointer to the HW structure
6883  * @seid: seid of the channel VSI
6884  * @macaddr: the mac address to apply as a filter
6885  * @aq_err: store the admin Q error
6886  *
6887  * This function deletes a mac filter on the channel VSI which serves as the
6888  * macvlan. Returns 0 on success.
6889  **/
6890 static i40e_status i40e_del_macvlan_filter(struct i40e_hw *hw, u16 seid,
6891 					   const u8 *macaddr, int *aq_err)
6892 {
6893 	struct i40e_aqc_remove_macvlan_element_data element;
6894 	i40e_status status;
6895 
6896 	memset(&element, 0, sizeof(element));
6897 	ether_addr_copy(element.mac_addr, macaddr);
6898 	element.vlan_tag = 0;
6899 	element.flags = I40E_AQC_MACVLAN_DEL_PERFECT_MATCH;
6900 	status = i40e_aq_remove_macvlan(hw, seid, &element, 1, NULL);
6901 	*aq_err = hw->aq.asq_last_status;
6902 
6903 	return status;
6904 }
6905 
6906 /**
6907  * i40e_add_macvlan_filter
6908  * @hw: pointer to the HW structure
6909  * @seid: seid of the channel VSI
6910  * @macaddr: the mac address to apply as a filter
6911  * @aq_err: store the admin Q error
6912  *
6913  * This function adds a mac filter on the channel VSI which serves as the
6914  * macvlan. Returns 0 on success.
6915  **/
6916 static i40e_status i40e_add_macvlan_filter(struct i40e_hw *hw, u16 seid,
6917 					   const u8 *macaddr, int *aq_err)
6918 {
6919 	struct i40e_aqc_add_macvlan_element_data element;
6920 	i40e_status status;
6921 	u16 cmd_flags = 0;
6922 
6923 	ether_addr_copy(element.mac_addr, macaddr);
6924 	element.vlan_tag = 0;
6925 	element.queue_number = 0;
6926 	element.match_method = I40E_AQC_MM_ERR_NO_RES;
6927 	cmd_flags |= I40E_AQC_MACVLAN_ADD_PERFECT_MATCH;
6928 	element.flags = cpu_to_le16(cmd_flags);
6929 	status = i40e_aq_add_macvlan(hw, seid, &element, 1, NULL);
6930 	*aq_err = hw->aq.asq_last_status;
6931 
6932 	return status;
6933 }
6934 
6935 /**
6936  * i40e_reset_ch_rings - Reset the queue contexts in a channel
6937  * @vsi: the VSI we want to access
6938  * @ch: the channel we want to access
6939  */
6940 static void i40e_reset_ch_rings(struct i40e_vsi *vsi, struct i40e_channel *ch)
6941 {
6942 	struct i40e_ring *tx_ring, *rx_ring;
6943 	u16 pf_q;
6944 	int i;
6945 
6946 	for (i = 0; i < ch->num_queue_pairs; i++) {
6947 		pf_q = ch->base_queue + i;
6948 		tx_ring = vsi->tx_rings[pf_q];
6949 		tx_ring->ch = NULL;
6950 		rx_ring = vsi->rx_rings[pf_q];
6951 		rx_ring->ch = NULL;
6952 	}
6953 }
6954 
6955 /**
6956  * i40e_free_macvlan_channels
6957  * @vsi: the VSI we want to access
6958  *
6959  * This function frees the Qs of the channel VSI from
6960  * the stack and also deletes the channel VSIs which
6961  * serve as macvlans.
6962  */
6963 static void i40e_free_macvlan_channels(struct i40e_vsi *vsi)
6964 {
6965 	struct i40e_channel *ch, *ch_tmp;
6966 	int ret;
6967 
6968 	if (list_empty(&vsi->macvlan_list))
6969 		return;
6970 
6971 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
6972 		struct i40e_vsi *parent_vsi;
6973 
6974 		if (i40e_is_channel_macvlan(ch)) {
6975 			i40e_reset_ch_rings(vsi, ch);
6976 			clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
6977 			netdev_unbind_sb_channel(vsi->netdev, ch->fwd->netdev);
6978 			netdev_set_sb_channel(ch->fwd->netdev, 0);
6979 			kfree(ch->fwd);
6980 			ch->fwd = NULL;
6981 		}
6982 
6983 		list_del(&ch->list);
6984 		parent_vsi = ch->parent_vsi;
6985 		if (!parent_vsi || !ch->initialized) {
6986 			kfree(ch);
6987 			continue;
6988 		}
6989 
6990 		/* remove the VSI */
6991 		ret = i40e_aq_delete_element(&vsi->back->hw, ch->seid,
6992 					     NULL);
6993 		if (ret)
6994 			dev_err(&vsi->back->pdev->dev,
6995 				"unable to remove channel (%d) for parent VSI(%d)\n",
6996 				ch->seid, parent_vsi->seid);
6997 		kfree(ch);
6998 	}
6999 	vsi->macvlan_cnt = 0;
7000 }
7001 
7002 /**
7003  * i40e_fwd_ring_up - bring the macvlan device up
7004  * @vsi: the VSI we want to access
7005  * @vdev: macvlan netdevice
7006  * @fwd: the private fwd structure
7007  */
7008 static int i40e_fwd_ring_up(struct i40e_vsi *vsi, struct net_device *vdev,
7009 			    struct i40e_fwd_adapter *fwd)
7010 {
7011 	int ret = 0, num_tc = 1,  i, aq_err;
7012 	struct i40e_channel *ch, *ch_tmp;
7013 	struct i40e_pf *pf = vsi->back;
7014 	struct i40e_hw *hw = &pf->hw;
7015 
7016 	if (list_empty(&vsi->macvlan_list))
7017 		return -EINVAL;
7018 
7019 	/* Go through the list and find an available channel */
7020 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7021 		if (!i40e_is_channel_macvlan(ch)) {
7022 			ch->fwd = fwd;
7023 			/* record configuration for macvlan interface in vdev */
7024 			for (i = 0; i < num_tc; i++)
7025 				netdev_bind_sb_channel_queue(vsi->netdev, vdev,
7026 							     i,
7027 							     ch->num_queue_pairs,
7028 							     ch->base_queue);
7029 			for (i = 0; i < ch->num_queue_pairs; i++) {
7030 				struct i40e_ring *tx_ring, *rx_ring;
7031 				u16 pf_q;
7032 
7033 				pf_q = ch->base_queue + i;
7034 
7035 				/* Get to TX ring ptr */
7036 				tx_ring = vsi->tx_rings[pf_q];
7037 				tx_ring->ch = ch;
7038 
7039 				/* Get the RX ring ptr */
7040 				rx_ring = vsi->rx_rings[pf_q];
7041 				rx_ring->ch = ch;
7042 			}
7043 			break;
7044 		}
7045 	}
7046 
7047 	/* Guarantee all rings are updated before we update the
7048 	 * MAC address filter.
7049 	 */
7050 	wmb();
7051 
7052 	/* Add a mac filter */
7053 	ret = i40e_add_macvlan_filter(hw, ch->seid, vdev->dev_addr, &aq_err);
7054 	if (ret) {
7055 		/* if we cannot add the MAC rule then disable the offload */
7056 		macvlan_release_l2fw_offload(vdev);
7057 		for (i = 0; i < ch->num_queue_pairs; i++) {
7058 			struct i40e_ring *rx_ring;
7059 			u16 pf_q;
7060 
7061 			pf_q = ch->base_queue + i;
7062 			rx_ring = vsi->rx_rings[pf_q];
7063 			rx_ring->netdev = NULL;
7064 		}
7065 		dev_info(&pf->pdev->dev,
7066 			 "Error adding mac filter on macvlan err %s, aq_err %s\n",
7067 			  i40e_stat_str(hw, ret),
7068 			  i40e_aq_str(hw, aq_err));
7069 		netdev_err(vdev, "L2fwd offload disabled to L2 filter error\n");
7070 	}
7071 
7072 	return ret;
7073 }
7074 
7075 /**
7076  * i40e_setup_macvlans - create the channels which will be macvlans
7077  * @vsi: the VSI we want to access
7078  * @macvlan_cnt: no. of macvlans to be setup
7079  * @qcnt: no. of Qs per macvlan
7080  * @vdev: macvlan netdevice
7081  */
7082 static int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt,
7083 			       struct net_device *vdev)
7084 {
7085 	struct i40e_pf *pf = vsi->back;
7086 	struct i40e_hw *hw = &pf->hw;
7087 	struct i40e_vsi_context ctxt;
7088 	u16 sections, qmap, num_qps;
7089 	struct i40e_channel *ch;
7090 	int i, pow, ret = 0;
7091 	u8 offset = 0;
7092 
7093 	if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt)
7094 		return -EINVAL;
7095 
7096 	num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt);
7097 
7098 	/* find the next higher power-of-2 of num queue pairs */
7099 	pow = fls(roundup_pow_of_two(num_qps) - 1);
7100 
7101 	qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) |
7102 		(pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT);
7103 
7104 	/* Setup context bits for the main VSI */
7105 	sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID;
7106 	sections |= I40E_AQ_VSI_PROP_SCHED_VALID;
7107 	memset(&ctxt, 0, sizeof(ctxt));
7108 	ctxt.seid = vsi->seid;
7109 	ctxt.pf_num = vsi->back->hw.pf_id;
7110 	ctxt.vf_num = 0;
7111 	ctxt.uplink_seid = vsi->uplink_seid;
7112 	ctxt.info = vsi->info;
7113 	ctxt.info.tc_mapping[0] = cpu_to_le16(qmap);
7114 	ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG);
7115 	ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue);
7116 	ctxt.info.valid_sections |= cpu_to_le16(sections);
7117 
7118 	/* Reconfigure RSS for main VSI with new max queue count */
7119 	vsi->rss_size = max_t(u16, num_qps, qcnt);
7120 	ret = i40e_vsi_config_rss(vsi);
7121 	if (ret) {
7122 		dev_info(&pf->pdev->dev,
7123 			 "Failed to reconfig RSS for num_queues (%u)\n",
7124 			 vsi->rss_size);
7125 		return ret;
7126 	}
7127 	vsi->reconfig_rss = true;
7128 	dev_dbg(&vsi->back->pdev->dev,
7129 		"Reconfigured RSS with num_queues (%u)\n", vsi->rss_size);
7130 	vsi->next_base_queue = num_qps;
7131 	vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps;
7132 
7133 	/* Update the VSI after updating the VSI queue-mapping
7134 	 * information
7135 	 */
7136 	ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
7137 	if (ret) {
7138 		dev_info(&pf->pdev->dev,
7139 			 "Update vsi tc config failed, err %s aq_err %s\n",
7140 			 i40e_stat_str(hw, ret),
7141 			 i40e_aq_str(hw, hw->aq.asq_last_status));
7142 		return ret;
7143 	}
7144 	/* update the local VSI info with updated queue map */
7145 	i40e_vsi_update_queue_map(vsi, &ctxt);
7146 	vsi->info.valid_sections = 0;
7147 
7148 	/* Create channels for macvlans */
7149 	INIT_LIST_HEAD(&vsi->macvlan_list);
7150 	for (i = 0; i < macvlan_cnt; i++) {
7151 		ch = kzalloc(sizeof(*ch), GFP_KERNEL);
7152 		if (!ch) {
7153 			ret = -ENOMEM;
7154 			goto err_free;
7155 		}
7156 		INIT_LIST_HEAD(&ch->list);
7157 		ch->num_queue_pairs = qcnt;
7158 		if (!i40e_setup_channel(pf, vsi, ch)) {
7159 			ret = -EINVAL;
7160 			goto err_free;
7161 		}
7162 		ch->parent_vsi = vsi;
7163 		vsi->cnt_q_avail -= ch->num_queue_pairs;
7164 		vsi->macvlan_cnt++;
7165 		list_add_tail(&ch->list, &vsi->macvlan_list);
7166 	}
7167 
7168 	return ret;
7169 
7170 err_free:
7171 	dev_info(&pf->pdev->dev, "Failed to setup macvlans\n");
7172 	i40e_free_macvlan_channels(vsi);
7173 
7174 	return ret;
7175 }
7176 
7177 /**
7178  * i40e_fwd_add - configure macvlans
7179  * @netdev: net device to configure
7180  * @vdev: macvlan netdevice
7181  **/
7182 static void *i40e_fwd_add(struct net_device *netdev, struct net_device *vdev)
7183 {
7184 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7185 	u16 q_per_macvlan = 0, macvlan_cnt = 0, vectors;
7186 	struct i40e_vsi *vsi = np->vsi;
7187 	struct i40e_pf *pf = vsi->back;
7188 	struct i40e_fwd_adapter *fwd;
7189 	int avail_macvlan, ret;
7190 
7191 	if ((pf->flags & I40E_FLAG_DCB_ENABLED)) {
7192 		netdev_info(netdev, "Macvlans are not supported when DCB is enabled\n");
7193 		return ERR_PTR(-EINVAL);
7194 	}
7195 	if ((pf->flags & I40E_FLAG_TC_MQPRIO)) {
7196 		netdev_info(netdev, "Macvlans are not supported when HW TC offload is on\n");
7197 		return ERR_PTR(-EINVAL);
7198 	}
7199 	if (pf->num_lan_msix < I40E_MIN_MACVLAN_VECTORS) {
7200 		netdev_info(netdev, "Not enough vectors available to support macvlans\n");
7201 		return ERR_PTR(-EINVAL);
7202 	}
7203 
7204 	/* The macvlan device has to be a single Q device so that the
7205 	 * tc_to_txq field can be reused to pick the tx queue.
7206 	 */
7207 	if (netif_is_multiqueue(vdev))
7208 		return ERR_PTR(-ERANGE);
7209 
7210 	if (!vsi->macvlan_cnt) {
7211 		/* reserve bit 0 for the pf device */
7212 		set_bit(0, vsi->fwd_bitmask);
7213 
7214 		/* Try to reserve as many queues as possible for macvlans. First
7215 		 * reserve 3/4th of max vectors, then half, then quarter and
7216 		 * calculate Qs per macvlan as you go
7217 		 */
7218 		vectors = pf->num_lan_msix;
7219 		if (vectors <= I40E_MAX_MACVLANS && vectors > 64) {
7220 			/* allocate 4 Qs per macvlan and 32 Qs to the PF*/
7221 			q_per_macvlan = 4;
7222 			macvlan_cnt = (vectors - 32) / 4;
7223 		} else if (vectors <= 64 && vectors > 32) {
7224 			/* allocate 2 Qs per macvlan and 16 Qs to the PF*/
7225 			q_per_macvlan = 2;
7226 			macvlan_cnt = (vectors - 16) / 2;
7227 		} else if (vectors <= 32 && vectors > 16) {
7228 			/* allocate 1 Q per macvlan and 16 Qs to the PF*/
7229 			q_per_macvlan = 1;
7230 			macvlan_cnt = vectors - 16;
7231 		} else if (vectors <= 16 && vectors > 8) {
7232 			/* allocate 1 Q per macvlan and 8 Qs to the PF */
7233 			q_per_macvlan = 1;
7234 			macvlan_cnt = vectors - 8;
7235 		} else {
7236 			/* allocate 1 Q per macvlan and 1 Q to the PF */
7237 			q_per_macvlan = 1;
7238 			macvlan_cnt = vectors - 1;
7239 		}
7240 
7241 		if (macvlan_cnt == 0)
7242 			return ERR_PTR(-EBUSY);
7243 
7244 		/* Quiesce VSI queues */
7245 		i40e_quiesce_vsi(vsi);
7246 
7247 		/* sets up the macvlans but does not "enable" them */
7248 		ret = i40e_setup_macvlans(vsi, macvlan_cnt, q_per_macvlan,
7249 					  vdev);
7250 		if (ret)
7251 			return ERR_PTR(ret);
7252 
7253 		/* Unquiesce VSI */
7254 		i40e_unquiesce_vsi(vsi);
7255 	}
7256 	avail_macvlan = find_first_zero_bit(vsi->fwd_bitmask,
7257 					    vsi->macvlan_cnt);
7258 	if (avail_macvlan >= I40E_MAX_MACVLANS)
7259 		return ERR_PTR(-EBUSY);
7260 
7261 	/* create the fwd struct */
7262 	fwd = kzalloc(sizeof(*fwd), GFP_KERNEL);
7263 	if (!fwd)
7264 		return ERR_PTR(-ENOMEM);
7265 
7266 	set_bit(avail_macvlan, vsi->fwd_bitmask);
7267 	fwd->bit_no = avail_macvlan;
7268 	netdev_set_sb_channel(vdev, avail_macvlan);
7269 	fwd->netdev = vdev;
7270 
7271 	if (!netif_running(netdev))
7272 		return fwd;
7273 
7274 	/* Set fwd ring up */
7275 	ret = i40e_fwd_ring_up(vsi, vdev, fwd);
7276 	if (ret) {
7277 		/* unbind the queues and drop the subordinate channel config */
7278 		netdev_unbind_sb_channel(netdev, vdev);
7279 		netdev_set_sb_channel(vdev, 0);
7280 
7281 		kfree(fwd);
7282 		return ERR_PTR(-EINVAL);
7283 	}
7284 
7285 	return fwd;
7286 }
7287 
7288 /**
7289  * i40e_del_all_macvlans - Delete all the mac filters on the channels
7290  * @vsi: the VSI we want to access
7291  */
7292 static void i40e_del_all_macvlans(struct i40e_vsi *vsi)
7293 {
7294 	struct i40e_channel *ch, *ch_tmp;
7295 	struct i40e_pf *pf = vsi->back;
7296 	struct i40e_hw *hw = &pf->hw;
7297 	int aq_err, ret = 0;
7298 
7299 	if (list_empty(&vsi->macvlan_list))
7300 		return;
7301 
7302 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7303 		if (i40e_is_channel_macvlan(ch)) {
7304 			ret = i40e_del_macvlan_filter(hw, ch->seid,
7305 						      i40e_channel_mac(ch),
7306 						      &aq_err);
7307 			if (!ret) {
7308 				/* Reset queue contexts */
7309 				i40e_reset_ch_rings(vsi, ch);
7310 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7311 				netdev_unbind_sb_channel(vsi->netdev,
7312 							 ch->fwd->netdev);
7313 				netdev_set_sb_channel(ch->fwd->netdev, 0);
7314 				kfree(ch->fwd);
7315 				ch->fwd = NULL;
7316 			}
7317 		}
7318 	}
7319 }
7320 
7321 /**
7322  * i40e_fwd_del - delete macvlan interfaces
7323  * @netdev: net device to configure
7324  * @vdev: macvlan netdevice
7325  */
7326 static void i40e_fwd_del(struct net_device *netdev, void *vdev)
7327 {
7328 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7329 	struct i40e_fwd_adapter *fwd = vdev;
7330 	struct i40e_channel *ch, *ch_tmp;
7331 	struct i40e_vsi *vsi = np->vsi;
7332 	struct i40e_pf *pf = vsi->back;
7333 	struct i40e_hw *hw = &pf->hw;
7334 	int aq_err, ret = 0;
7335 
7336 	/* Find the channel associated with the macvlan and del mac filter */
7337 	list_for_each_entry_safe(ch, ch_tmp, &vsi->macvlan_list, list) {
7338 		if (i40e_is_channel_macvlan(ch) &&
7339 		    ether_addr_equal(i40e_channel_mac(ch),
7340 				     fwd->netdev->dev_addr)) {
7341 			ret = i40e_del_macvlan_filter(hw, ch->seid,
7342 						      i40e_channel_mac(ch),
7343 						      &aq_err);
7344 			if (!ret) {
7345 				/* Reset queue contexts */
7346 				i40e_reset_ch_rings(vsi, ch);
7347 				clear_bit(ch->fwd->bit_no, vsi->fwd_bitmask);
7348 				netdev_unbind_sb_channel(netdev, fwd->netdev);
7349 				netdev_set_sb_channel(fwd->netdev, 0);
7350 				kfree(ch->fwd);
7351 				ch->fwd = NULL;
7352 			} else {
7353 				dev_info(&pf->pdev->dev,
7354 					 "Error deleting mac filter on macvlan err %s, aq_err %s\n",
7355 					  i40e_stat_str(hw, ret),
7356 					  i40e_aq_str(hw, aq_err));
7357 			}
7358 			break;
7359 		}
7360 	}
7361 }
7362 
7363 /**
7364  * i40e_setup_tc - configure multiple traffic classes
7365  * @netdev: net device to configure
7366  * @type_data: tc offload data
7367  **/
7368 static int i40e_setup_tc(struct net_device *netdev, void *type_data)
7369 {
7370 	struct tc_mqprio_qopt_offload *mqprio_qopt = type_data;
7371 	struct i40e_netdev_priv *np = netdev_priv(netdev);
7372 	struct i40e_vsi *vsi = np->vsi;
7373 	struct i40e_pf *pf = vsi->back;
7374 	u8 enabled_tc = 0, num_tc, hw;
7375 	bool need_reset = false;
7376 	int old_queue_pairs;
7377 	int ret = -EINVAL;
7378 	u16 mode;
7379 	int i;
7380 
7381 	old_queue_pairs = vsi->num_queue_pairs;
7382 	num_tc = mqprio_qopt->qopt.num_tc;
7383 	hw = mqprio_qopt->qopt.hw;
7384 	mode = mqprio_qopt->mode;
7385 	if (!hw) {
7386 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
7387 		memcpy(&vsi->mqprio_qopt, mqprio_qopt, sizeof(*mqprio_qopt));
7388 		goto config_tc;
7389 	}
7390 
7391 	/* Check if MFP enabled */
7392 	if (pf->flags & I40E_FLAG_MFP_ENABLED) {
7393 		netdev_info(netdev,
7394 			    "Configuring TC not supported in MFP mode\n");
7395 		return ret;
7396 	}
7397 	switch (mode) {
7398 	case TC_MQPRIO_MODE_DCB:
7399 		pf->flags &= ~I40E_FLAG_TC_MQPRIO;
7400 
7401 		/* Check if DCB enabled to continue */
7402 		if (!(pf->flags & I40E_FLAG_DCB_ENABLED)) {
7403 			netdev_info(netdev,
7404 				    "DCB is not enabled for adapter\n");
7405 			return ret;
7406 		}
7407 
7408 		/* Check whether tc count is within enabled limit */
7409 		if (num_tc > i40e_pf_get_num_tc(pf)) {
7410 			netdev_info(netdev,
7411 				    "TC count greater than enabled on link for adapter\n");
7412 			return ret;
7413 		}
7414 		break;
7415 	case TC_MQPRIO_MODE_CHANNEL:
7416 		if (pf->flags & I40E_FLAG_DCB_ENABLED) {
7417 			netdev_info(netdev,
7418 				    "Full offload of TC Mqprio options is not supported when DCB is enabled\n");
7419 			return ret;
7420 		}
7421 		if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
7422 			return ret;
7423 		ret = i40e_validate_mqprio_qopt(vsi, mqprio_qopt);
7424 		if (ret)
7425 			return ret;
7426 		memcpy(&vsi->mqprio_qopt, mqprio_qopt,
7427 		       sizeof(*mqprio_qopt));
7428 		pf->flags |= I40E_FLAG_TC_MQPRIO;
7429 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
7430 		break;
7431 	default:
7432 		return -EINVAL;
7433 	}
7434 
7435 config_tc:
7436 	/* Generate TC map for number of tc requested */
7437 	for (i = 0; i < num_tc; i++)
7438 		enabled_tc |= BIT(i);
7439 
7440 	/* Requesting same TC configuration as already enabled */
7441 	if (enabled_tc == vsi->tc_config.enabled_tc &&
7442 	    mode != TC_MQPRIO_MODE_CHANNEL)
7443 		return 0;
7444 
7445 	/* Quiesce VSI queues */
7446 	i40e_quiesce_vsi(vsi);
7447 
7448 	if (!hw && !(pf->flags & I40E_FLAG_TC_MQPRIO))
7449 		i40e_remove_queue_channels(vsi);
7450 
7451 	/* Configure VSI for enabled TCs */
7452 	ret = i40e_vsi_config_tc(vsi, enabled_tc);
7453 	if (ret) {
7454 		netdev_info(netdev, "Failed configuring TC for VSI seid=%d\n",
7455 			    vsi->seid);
7456 		need_reset = true;
7457 		goto exit;
7458 	} else {
7459 		dev_info(&vsi->back->pdev->dev,
7460 			 "Setup channel (id:%u) utilizing num_queues %d\n",
7461 			 vsi->seid, vsi->tc_config.tc_info[0].qcount);
7462 	}
7463 
7464 	if (pf->flags & I40E_FLAG_TC_MQPRIO) {
7465 		if (vsi->mqprio_qopt.max_rate[0]) {
7466 			u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
7467 
7468 			do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
7469 			ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
7470 			if (!ret) {
7471 				u64 credits = max_tx_rate;
7472 
7473 				do_div(credits, I40E_BW_CREDIT_DIVISOR);
7474 				dev_dbg(&vsi->back->pdev->dev,
7475 					"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
7476 					max_tx_rate,
7477 					credits,
7478 					vsi->seid);
7479 			} else {
7480 				need_reset = true;
7481 				goto exit;
7482 			}
7483 		}
7484 		ret = i40e_configure_queue_channels(vsi);
7485 		if (ret) {
7486 			vsi->num_queue_pairs = old_queue_pairs;
7487 			netdev_info(netdev,
7488 				    "Failed configuring queue channels\n");
7489 			need_reset = true;
7490 			goto exit;
7491 		}
7492 	}
7493 
7494 exit:
7495 	/* Reset the configuration data to defaults, only TC0 is enabled */
7496 	if (need_reset) {
7497 		i40e_vsi_set_default_tc_config(vsi);
7498 		need_reset = false;
7499 	}
7500 
7501 	/* Unquiesce VSI */
7502 	i40e_unquiesce_vsi(vsi);
7503 	return ret;
7504 }
7505 
7506 /**
7507  * i40e_set_cld_element - sets cloud filter element data
7508  * @filter: cloud filter rule
7509  * @cld: ptr to cloud filter element data
7510  *
7511  * This is helper function to copy data into cloud filter element
7512  **/
7513 static inline void
7514 i40e_set_cld_element(struct i40e_cloud_filter *filter,
7515 		     struct i40e_aqc_cloud_filters_element_data *cld)
7516 {
7517 	int i, j;
7518 	u32 ipa;
7519 
7520 	memset(cld, 0, sizeof(*cld));
7521 	ether_addr_copy(cld->outer_mac, filter->dst_mac);
7522 	ether_addr_copy(cld->inner_mac, filter->src_mac);
7523 
7524 	if (filter->n_proto != ETH_P_IP && filter->n_proto != ETH_P_IPV6)
7525 		return;
7526 
7527 	if (filter->n_proto == ETH_P_IPV6) {
7528 #define IPV6_MAX_INDEX	(ARRAY_SIZE(filter->dst_ipv6) - 1)
7529 		for (i = 0, j = 0; i < ARRAY_SIZE(filter->dst_ipv6);
7530 		     i++, j += 2) {
7531 			ipa = be32_to_cpu(filter->dst_ipv6[IPV6_MAX_INDEX - i]);
7532 			ipa = cpu_to_le32(ipa);
7533 			memcpy(&cld->ipaddr.raw_v6.data[j], &ipa, sizeof(ipa));
7534 		}
7535 	} else {
7536 		ipa = be32_to_cpu(filter->dst_ipv4);
7537 		memcpy(&cld->ipaddr.v4.data, &ipa, sizeof(ipa));
7538 	}
7539 
7540 	cld->inner_vlan = cpu_to_le16(ntohs(filter->vlan_id));
7541 
7542 	/* tenant_id is not supported by FW now, once the support is enabled
7543 	 * fill the cld->tenant_id with cpu_to_le32(filter->tenant_id)
7544 	 */
7545 	if (filter->tenant_id)
7546 		return;
7547 }
7548 
7549 /**
7550  * i40e_add_del_cloud_filter - Add/del cloud filter
7551  * @vsi: pointer to VSI
7552  * @filter: cloud filter rule
7553  * @add: if true, add, if false, delete
7554  *
7555  * Add or delete a cloud filter for a specific flow spec.
7556  * Returns 0 if the filter were successfully added.
7557  **/
7558 int i40e_add_del_cloud_filter(struct i40e_vsi *vsi,
7559 			      struct i40e_cloud_filter *filter, bool add)
7560 {
7561 	struct i40e_aqc_cloud_filters_element_data cld_filter;
7562 	struct i40e_pf *pf = vsi->back;
7563 	int ret;
7564 	static const u16 flag_table[128] = {
7565 		[I40E_CLOUD_FILTER_FLAGS_OMAC]  =
7566 			I40E_AQC_ADD_CLOUD_FILTER_OMAC,
7567 		[I40E_CLOUD_FILTER_FLAGS_IMAC]  =
7568 			I40E_AQC_ADD_CLOUD_FILTER_IMAC,
7569 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN]  =
7570 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN,
7571 		[I40E_CLOUD_FILTER_FLAGS_IMAC_TEN_ID] =
7572 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_TEN_ID,
7573 		[I40E_CLOUD_FILTER_FLAGS_OMAC_TEN_ID_IMAC] =
7574 			I40E_AQC_ADD_CLOUD_FILTER_OMAC_TEN_ID_IMAC,
7575 		[I40E_CLOUD_FILTER_FLAGS_IMAC_IVLAN_TEN_ID] =
7576 			I40E_AQC_ADD_CLOUD_FILTER_IMAC_IVLAN_TEN_ID,
7577 		[I40E_CLOUD_FILTER_FLAGS_IIP] =
7578 			I40E_AQC_ADD_CLOUD_FILTER_IIP,
7579 	};
7580 
7581 	if (filter->flags >= ARRAY_SIZE(flag_table))
7582 		return I40E_ERR_CONFIG;
7583 
7584 	/* copy element needed to add cloud filter from filter */
7585 	i40e_set_cld_element(filter, &cld_filter);
7586 
7587 	if (filter->tunnel_type != I40E_CLOUD_TNL_TYPE_NONE)
7588 		cld_filter.flags = cpu_to_le16(filter->tunnel_type <<
7589 					     I40E_AQC_ADD_CLOUD_TNL_TYPE_SHIFT);
7590 
7591 	if (filter->n_proto == ETH_P_IPV6)
7592 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
7593 						I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
7594 	else
7595 		cld_filter.flags |= cpu_to_le16(flag_table[filter->flags] |
7596 						I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
7597 
7598 	if (add)
7599 		ret = i40e_aq_add_cloud_filters(&pf->hw, filter->seid,
7600 						&cld_filter, 1);
7601 	else
7602 		ret = i40e_aq_rem_cloud_filters(&pf->hw, filter->seid,
7603 						&cld_filter, 1);
7604 	if (ret)
7605 		dev_dbg(&pf->pdev->dev,
7606 			"Failed to %s cloud filter using l4 port %u, err %d aq_err %d\n",
7607 			add ? "add" : "delete", filter->dst_port, ret,
7608 			pf->hw.aq.asq_last_status);
7609 	else
7610 		dev_info(&pf->pdev->dev,
7611 			 "%s cloud filter for VSI: %d\n",
7612 			 add ? "Added" : "Deleted", filter->seid);
7613 	return ret;
7614 }
7615 
7616 /**
7617  * i40e_add_del_cloud_filter_big_buf - Add/del cloud filter using big_buf
7618  * @vsi: pointer to VSI
7619  * @filter: cloud filter rule
7620  * @add: if true, add, if false, delete
7621  *
7622  * Add or delete a cloud filter for a specific flow spec using big buffer.
7623  * Returns 0 if the filter were successfully added.
7624  **/
7625 int i40e_add_del_cloud_filter_big_buf(struct i40e_vsi *vsi,
7626 				      struct i40e_cloud_filter *filter,
7627 				      bool add)
7628 {
7629 	struct i40e_aqc_cloud_filters_element_bb cld_filter;
7630 	struct i40e_pf *pf = vsi->back;
7631 	int ret;
7632 
7633 	/* Both (src/dst) valid mac_addr are not supported */
7634 	if ((is_valid_ether_addr(filter->dst_mac) &&
7635 	     is_valid_ether_addr(filter->src_mac)) ||
7636 	    (is_multicast_ether_addr(filter->dst_mac) &&
7637 	     is_multicast_ether_addr(filter->src_mac)))
7638 		return -EOPNOTSUPP;
7639 
7640 	/* Big buffer cloud filter needs 'L4 port' to be non-zero. Also, UDP
7641 	 * ports are not supported via big buffer now.
7642 	 */
7643 	if (!filter->dst_port || filter->ip_proto == IPPROTO_UDP)
7644 		return -EOPNOTSUPP;
7645 
7646 	/* adding filter using src_port/src_ip is not supported at this stage */
7647 	if (filter->src_port || filter->src_ipv4 ||
7648 	    !ipv6_addr_any(&filter->ip.v6.src_ip6))
7649 		return -EOPNOTSUPP;
7650 
7651 	/* copy element needed to add cloud filter from filter */
7652 	i40e_set_cld_element(filter, &cld_filter.element);
7653 
7654 	if (is_valid_ether_addr(filter->dst_mac) ||
7655 	    is_valid_ether_addr(filter->src_mac) ||
7656 	    is_multicast_ether_addr(filter->dst_mac) ||
7657 	    is_multicast_ether_addr(filter->src_mac)) {
7658 		/* MAC + IP : unsupported mode */
7659 		if (filter->dst_ipv4)
7660 			return -EOPNOTSUPP;
7661 
7662 		/* since we validated that L4 port must be valid before
7663 		 * we get here, start with respective "flags" value
7664 		 * and update if vlan is present or not
7665 		 */
7666 		cld_filter.element.flags =
7667 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_PORT);
7668 
7669 		if (filter->vlan_id) {
7670 			cld_filter.element.flags =
7671 			cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_MAC_VLAN_PORT);
7672 		}
7673 
7674 	} else if (filter->dst_ipv4 ||
7675 		   !ipv6_addr_any(&filter->ip.v6.dst_ip6)) {
7676 		cld_filter.element.flags =
7677 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FILTER_IP_PORT);
7678 		if (filter->n_proto == ETH_P_IPV6)
7679 			cld_filter.element.flags |=
7680 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV6);
7681 		else
7682 			cld_filter.element.flags |=
7683 				cpu_to_le16(I40E_AQC_ADD_CLOUD_FLAGS_IPV4);
7684 	} else {
7685 		dev_err(&pf->pdev->dev,
7686 			"either mac or ip has to be valid for cloud filter\n");
7687 		return -EINVAL;
7688 	}
7689 
7690 	/* Now copy L4 port in Byte 6..7 in general fields */
7691 	cld_filter.general_fields[I40E_AQC_ADD_CLOUD_FV_FLU_0X16_WORD0] =
7692 						be16_to_cpu(filter->dst_port);
7693 
7694 	if (add) {
7695 		/* Validate current device switch mode, change if necessary */
7696 		ret = i40e_validate_and_set_switch_mode(vsi);
7697 		if (ret) {
7698 			dev_err(&pf->pdev->dev,
7699 				"failed to set switch mode, ret %d\n",
7700 				ret);
7701 			return ret;
7702 		}
7703 
7704 		ret = i40e_aq_add_cloud_filters_bb(&pf->hw, filter->seid,
7705 						   &cld_filter, 1);
7706 	} else {
7707 		ret = i40e_aq_rem_cloud_filters_bb(&pf->hw, filter->seid,
7708 						   &cld_filter, 1);
7709 	}
7710 
7711 	if (ret)
7712 		dev_dbg(&pf->pdev->dev,
7713 			"Failed to %s cloud filter(big buffer) err %d aq_err %d\n",
7714 			add ? "add" : "delete", ret, pf->hw.aq.asq_last_status);
7715 	else
7716 		dev_info(&pf->pdev->dev,
7717 			 "%s cloud filter for VSI: %d, L4 port: %d\n",
7718 			 add ? "add" : "delete", filter->seid,
7719 			 ntohs(filter->dst_port));
7720 	return ret;
7721 }
7722 
7723 /**
7724  * i40e_parse_cls_flower - Parse tc flower filters provided by kernel
7725  * @vsi: Pointer to VSI
7726  * @cls_flower: Pointer to struct flow_cls_offload
7727  * @filter: Pointer to cloud filter structure
7728  *
7729  **/
7730 static int i40e_parse_cls_flower(struct i40e_vsi *vsi,
7731 				 struct flow_cls_offload *f,
7732 				 struct i40e_cloud_filter *filter)
7733 {
7734 	struct flow_rule *rule = flow_cls_offload_flow_rule(f);
7735 	struct flow_dissector *dissector = rule->match.dissector;
7736 	u16 n_proto_mask = 0, n_proto_key = 0, addr_type = 0;
7737 	struct i40e_pf *pf = vsi->back;
7738 	u8 field_flags = 0;
7739 
7740 	if (dissector->used_keys &
7741 	    ~(BIT(FLOW_DISSECTOR_KEY_CONTROL) |
7742 	      BIT(FLOW_DISSECTOR_KEY_BASIC) |
7743 	      BIT(FLOW_DISSECTOR_KEY_ETH_ADDRS) |
7744 	      BIT(FLOW_DISSECTOR_KEY_VLAN) |
7745 	      BIT(FLOW_DISSECTOR_KEY_IPV4_ADDRS) |
7746 	      BIT(FLOW_DISSECTOR_KEY_IPV6_ADDRS) |
7747 	      BIT(FLOW_DISSECTOR_KEY_PORTS) |
7748 	      BIT(FLOW_DISSECTOR_KEY_ENC_KEYID))) {
7749 		dev_err(&pf->pdev->dev, "Unsupported key used: 0x%x\n",
7750 			dissector->used_keys);
7751 		return -EOPNOTSUPP;
7752 	}
7753 
7754 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ENC_KEYID)) {
7755 		struct flow_match_enc_keyid match;
7756 
7757 		flow_rule_match_enc_keyid(rule, &match);
7758 		if (match.mask->keyid != 0)
7759 			field_flags |= I40E_CLOUD_FIELD_TEN_ID;
7760 
7761 		filter->tenant_id = be32_to_cpu(match.key->keyid);
7762 	}
7763 
7764 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_BASIC)) {
7765 		struct flow_match_basic match;
7766 
7767 		flow_rule_match_basic(rule, &match);
7768 		n_proto_key = ntohs(match.key->n_proto);
7769 		n_proto_mask = ntohs(match.mask->n_proto);
7770 
7771 		if (n_proto_key == ETH_P_ALL) {
7772 			n_proto_key = 0;
7773 			n_proto_mask = 0;
7774 		}
7775 		filter->n_proto = n_proto_key & n_proto_mask;
7776 		filter->ip_proto = match.key->ip_proto;
7777 	}
7778 
7779 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_ETH_ADDRS)) {
7780 		struct flow_match_eth_addrs match;
7781 
7782 		flow_rule_match_eth_addrs(rule, &match);
7783 
7784 		/* use is_broadcast and is_zero to check for all 0xf or 0 */
7785 		if (!is_zero_ether_addr(match.mask->dst)) {
7786 			if (is_broadcast_ether_addr(match.mask->dst)) {
7787 				field_flags |= I40E_CLOUD_FIELD_OMAC;
7788 			} else {
7789 				dev_err(&pf->pdev->dev, "Bad ether dest mask %pM\n",
7790 					match.mask->dst);
7791 				return I40E_ERR_CONFIG;
7792 			}
7793 		}
7794 
7795 		if (!is_zero_ether_addr(match.mask->src)) {
7796 			if (is_broadcast_ether_addr(match.mask->src)) {
7797 				field_flags |= I40E_CLOUD_FIELD_IMAC;
7798 			} else {
7799 				dev_err(&pf->pdev->dev, "Bad ether src mask %pM\n",
7800 					match.mask->src);
7801 				return I40E_ERR_CONFIG;
7802 			}
7803 		}
7804 		ether_addr_copy(filter->dst_mac, match.key->dst);
7805 		ether_addr_copy(filter->src_mac, match.key->src);
7806 	}
7807 
7808 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_VLAN)) {
7809 		struct flow_match_vlan match;
7810 
7811 		flow_rule_match_vlan(rule, &match);
7812 		if (match.mask->vlan_id) {
7813 			if (match.mask->vlan_id == VLAN_VID_MASK) {
7814 				field_flags |= I40E_CLOUD_FIELD_IVLAN;
7815 
7816 			} else {
7817 				dev_err(&pf->pdev->dev, "Bad vlan mask 0x%04x\n",
7818 					match.mask->vlan_id);
7819 				return I40E_ERR_CONFIG;
7820 			}
7821 		}
7822 
7823 		filter->vlan_id = cpu_to_be16(match.key->vlan_id);
7824 	}
7825 
7826 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_CONTROL)) {
7827 		struct flow_match_control match;
7828 
7829 		flow_rule_match_control(rule, &match);
7830 		addr_type = match.key->addr_type;
7831 	}
7832 
7833 	if (addr_type == FLOW_DISSECTOR_KEY_IPV4_ADDRS) {
7834 		struct flow_match_ipv4_addrs match;
7835 
7836 		flow_rule_match_ipv4_addrs(rule, &match);
7837 		if (match.mask->dst) {
7838 			if (match.mask->dst == cpu_to_be32(0xffffffff)) {
7839 				field_flags |= I40E_CLOUD_FIELD_IIP;
7840 			} else {
7841 				dev_err(&pf->pdev->dev, "Bad ip dst mask %pI4b\n",
7842 					&match.mask->dst);
7843 				return I40E_ERR_CONFIG;
7844 			}
7845 		}
7846 
7847 		if (match.mask->src) {
7848 			if (match.mask->src == cpu_to_be32(0xffffffff)) {
7849 				field_flags |= I40E_CLOUD_FIELD_IIP;
7850 			} else {
7851 				dev_err(&pf->pdev->dev, "Bad ip src mask %pI4b\n",
7852 					&match.mask->src);
7853 				return I40E_ERR_CONFIG;
7854 			}
7855 		}
7856 
7857 		if (field_flags & I40E_CLOUD_FIELD_TEN_ID) {
7858 			dev_err(&pf->pdev->dev, "Tenant id not allowed for ip filter\n");
7859 			return I40E_ERR_CONFIG;
7860 		}
7861 		filter->dst_ipv4 = match.key->dst;
7862 		filter->src_ipv4 = match.key->src;
7863 	}
7864 
7865 	if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
7866 		struct flow_match_ipv6_addrs match;
7867 
7868 		flow_rule_match_ipv6_addrs(rule, &match);
7869 
7870 		/* src and dest IPV6 address should not be LOOPBACK
7871 		 * (0:0:0:0:0:0:0:1), which can be represented as ::1
7872 		 */
7873 		if (ipv6_addr_loopback(&match.key->dst) ||
7874 		    ipv6_addr_loopback(&match.key->src)) {
7875 			dev_err(&pf->pdev->dev,
7876 				"Bad ipv6, addr is LOOPBACK\n");
7877 			return I40E_ERR_CONFIG;
7878 		}
7879 		if (!ipv6_addr_any(&match.mask->dst) ||
7880 		    !ipv6_addr_any(&match.mask->src))
7881 			field_flags |= I40E_CLOUD_FIELD_IIP;
7882 
7883 		memcpy(&filter->src_ipv6, &match.key->src.s6_addr32,
7884 		       sizeof(filter->src_ipv6));
7885 		memcpy(&filter->dst_ipv6, &match.key->dst.s6_addr32,
7886 		       sizeof(filter->dst_ipv6));
7887 	}
7888 
7889 	if (flow_rule_match_key(rule, FLOW_DISSECTOR_KEY_PORTS)) {
7890 		struct flow_match_ports match;
7891 
7892 		flow_rule_match_ports(rule, &match);
7893 		if (match.mask->src) {
7894 			if (match.mask->src == cpu_to_be16(0xffff)) {
7895 				field_flags |= I40E_CLOUD_FIELD_IIP;
7896 			} else {
7897 				dev_err(&pf->pdev->dev, "Bad src port mask 0x%04x\n",
7898 					be16_to_cpu(match.mask->src));
7899 				return I40E_ERR_CONFIG;
7900 			}
7901 		}
7902 
7903 		if (match.mask->dst) {
7904 			if (match.mask->dst == cpu_to_be16(0xffff)) {
7905 				field_flags |= I40E_CLOUD_FIELD_IIP;
7906 			} else {
7907 				dev_err(&pf->pdev->dev, "Bad dst port mask 0x%04x\n",
7908 					be16_to_cpu(match.mask->dst));
7909 				return I40E_ERR_CONFIG;
7910 			}
7911 		}
7912 
7913 		filter->dst_port = match.key->dst;
7914 		filter->src_port = match.key->src;
7915 
7916 		switch (filter->ip_proto) {
7917 		case IPPROTO_TCP:
7918 		case IPPROTO_UDP:
7919 			break;
7920 		default:
7921 			dev_err(&pf->pdev->dev,
7922 				"Only UDP and TCP transport are supported\n");
7923 			return -EINVAL;
7924 		}
7925 	}
7926 	filter->flags = field_flags;
7927 	return 0;
7928 }
7929 
7930 /**
7931  * i40e_handle_tclass: Forward to a traffic class on the device
7932  * @vsi: Pointer to VSI
7933  * @tc: traffic class index on the device
7934  * @filter: Pointer to cloud filter structure
7935  *
7936  **/
7937 static int i40e_handle_tclass(struct i40e_vsi *vsi, u32 tc,
7938 			      struct i40e_cloud_filter *filter)
7939 {
7940 	struct i40e_channel *ch, *ch_tmp;
7941 
7942 	/* direct to a traffic class on the same device */
7943 	if (tc == 0) {
7944 		filter->seid = vsi->seid;
7945 		return 0;
7946 	} else if (vsi->tc_config.enabled_tc & BIT(tc)) {
7947 		if (!filter->dst_port) {
7948 			dev_err(&vsi->back->pdev->dev,
7949 				"Specify destination port to direct to traffic class that is not default\n");
7950 			return -EINVAL;
7951 		}
7952 		if (list_empty(&vsi->ch_list))
7953 			return -EINVAL;
7954 		list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list,
7955 					 list) {
7956 			if (ch->seid == vsi->tc_seid_map[tc])
7957 				filter->seid = ch->seid;
7958 		}
7959 		return 0;
7960 	}
7961 	dev_err(&vsi->back->pdev->dev, "TC is not enabled\n");
7962 	return -EINVAL;
7963 }
7964 
7965 /**
7966  * i40e_configure_clsflower - Configure tc flower filters
7967  * @vsi: Pointer to VSI
7968  * @cls_flower: Pointer to struct flow_cls_offload
7969  *
7970  **/
7971 static int i40e_configure_clsflower(struct i40e_vsi *vsi,
7972 				    struct flow_cls_offload *cls_flower)
7973 {
7974 	int tc = tc_classid_to_hwtc(vsi->netdev, cls_flower->classid);
7975 	struct i40e_cloud_filter *filter = NULL;
7976 	struct i40e_pf *pf = vsi->back;
7977 	int err = 0;
7978 
7979 	if (tc < 0) {
7980 		dev_err(&vsi->back->pdev->dev, "Invalid traffic class\n");
7981 		return -EOPNOTSUPP;
7982 	}
7983 
7984 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
7985 	    test_bit(__I40E_RESET_INTR_RECEIVED, pf->state))
7986 		return -EBUSY;
7987 
7988 	if (pf->fdir_pf_active_filters ||
7989 	    (!hlist_empty(&pf->fdir_filter_list))) {
7990 		dev_err(&vsi->back->pdev->dev,
7991 			"Flow Director Sideband filters exists, turn ntuple off to configure cloud filters\n");
7992 		return -EINVAL;
7993 	}
7994 
7995 	if (vsi->back->flags & I40E_FLAG_FD_SB_ENABLED) {
7996 		dev_err(&vsi->back->pdev->dev,
7997 			"Disable Flow Director Sideband, configuring Cloud filters via tc-flower\n");
7998 		vsi->back->flags &= ~I40E_FLAG_FD_SB_ENABLED;
7999 		vsi->back->flags |= I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8000 	}
8001 
8002 	filter = kzalloc(sizeof(*filter), GFP_KERNEL);
8003 	if (!filter)
8004 		return -ENOMEM;
8005 
8006 	filter->cookie = cls_flower->cookie;
8007 
8008 	err = i40e_parse_cls_flower(vsi, cls_flower, filter);
8009 	if (err < 0)
8010 		goto err;
8011 
8012 	err = i40e_handle_tclass(vsi, tc, filter);
8013 	if (err < 0)
8014 		goto err;
8015 
8016 	/* Add cloud filter */
8017 	if (filter->dst_port)
8018 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, true);
8019 	else
8020 		err = i40e_add_del_cloud_filter(vsi, filter, true);
8021 
8022 	if (err) {
8023 		dev_err(&pf->pdev->dev,
8024 			"Failed to add cloud filter, err %s\n",
8025 			i40e_stat_str(&pf->hw, err));
8026 		goto err;
8027 	}
8028 
8029 	/* add filter to the ordered list */
8030 	INIT_HLIST_NODE(&filter->cloud_node);
8031 
8032 	hlist_add_head(&filter->cloud_node, &pf->cloud_filter_list);
8033 
8034 	pf->num_cloud_filters++;
8035 
8036 	return err;
8037 err:
8038 	kfree(filter);
8039 	return err;
8040 }
8041 
8042 /**
8043  * i40e_find_cloud_filter - Find the could filter in the list
8044  * @vsi: Pointer to VSI
8045  * @cookie: filter specific cookie
8046  *
8047  **/
8048 static struct i40e_cloud_filter *i40e_find_cloud_filter(struct i40e_vsi *vsi,
8049 							unsigned long *cookie)
8050 {
8051 	struct i40e_cloud_filter *filter = NULL;
8052 	struct hlist_node *node2;
8053 
8054 	hlist_for_each_entry_safe(filter, node2,
8055 				  &vsi->back->cloud_filter_list, cloud_node)
8056 		if (!memcmp(cookie, &filter->cookie, sizeof(filter->cookie)))
8057 			return filter;
8058 	return NULL;
8059 }
8060 
8061 /**
8062  * i40e_delete_clsflower - Remove tc flower filters
8063  * @vsi: Pointer to VSI
8064  * @cls_flower: Pointer to struct flow_cls_offload
8065  *
8066  **/
8067 static int i40e_delete_clsflower(struct i40e_vsi *vsi,
8068 				 struct flow_cls_offload *cls_flower)
8069 {
8070 	struct i40e_cloud_filter *filter = NULL;
8071 	struct i40e_pf *pf = vsi->back;
8072 	int err = 0;
8073 
8074 	filter = i40e_find_cloud_filter(vsi, &cls_flower->cookie);
8075 
8076 	if (!filter)
8077 		return -EINVAL;
8078 
8079 	hash_del(&filter->cloud_node);
8080 
8081 	if (filter->dst_port)
8082 		err = i40e_add_del_cloud_filter_big_buf(vsi, filter, false);
8083 	else
8084 		err = i40e_add_del_cloud_filter(vsi, filter, false);
8085 
8086 	kfree(filter);
8087 	if (err) {
8088 		dev_err(&pf->pdev->dev,
8089 			"Failed to delete cloud filter, err %s\n",
8090 			i40e_stat_str(&pf->hw, err));
8091 		return i40e_aq_rc_to_posix(err, pf->hw.aq.asq_last_status);
8092 	}
8093 
8094 	pf->num_cloud_filters--;
8095 	if (!pf->num_cloud_filters)
8096 		if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8097 		    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8098 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8099 			pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8100 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8101 		}
8102 	return 0;
8103 }
8104 
8105 /**
8106  * i40e_setup_tc_cls_flower - flower classifier offloads
8107  * @netdev: net device to configure
8108  * @type_data: offload data
8109  **/
8110 static int i40e_setup_tc_cls_flower(struct i40e_netdev_priv *np,
8111 				    struct flow_cls_offload *cls_flower)
8112 {
8113 	struct i40e_vsi *vsi = np->vsi;
8114 
8115 	switch (cls_flower->command) {
8116 	case FLOW_CLS_REPLACE:
8117 		return i40e_configure_clsflower(vsi, cls_flower);
8118 	case FLOW_CLS_DESTROY:
8119 		return i40e_delete_clsflower(vsi, cls_flower);
8120 	case FLOW_CLS_STATS:
8121 		return -EOPNOTSUPP;
8122 	default:
8123 		return -EOPNOTSUPP;
8124 	}
8125 }
8126 
8127 static int i40e_setup_tc_block_cb(enum tc_setup_type type, void *type_data,
8128 				  void *cb_priv)
8129 {
8130 	struct i40e_netdev_priv *np = cb_priv;
8131 
8132 	if (!tc_cls_can_offload_and_chain0(np->vsi->netdev, type_data))
8133 		return -EOPNOTSUPP;
8134 
8135 	switch (type) {
8136 	case TC_SETUP_CLSFLOWER:
8137 		return i40e_setup_tc_cls_flower(np, type_data);
8138 
8139 	default:
8140 		return -EOPNOTSUPP;
8141 	}
8142 }
8143 
8144 static LIST_HEAD(i40e_block_cb_list);
8145 
8146 static int __i40e_setup_tc(struct net_device *netdev, enum tc_setup_type type,
8147 			   void *type_data)
8148 {
8149 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8150 
8151 	switch (type) {
8152 	case TC_SETUP_QDISC_MQPRIO:
8153 		return i40e_setup_tc(netdev, type_data);
8154 	case TC_SETUP_BLOCK:
8155 		return flow_block_cb_setup_simple(type_data,
8156 						  &i40e_block_cb_list,
8157 						  i40e_setup_tc_block_cb,
8158 						  np, np, true);
8159 	default:
8160 		return -EOPNOTSUPP;
8161 	}
8162 }
8163 
8164 /**
8165  * i40e_open - Called when a network interface is made active
8166  * @netdev: network interface device structure
8167  *
8168  * The open entry point is called when a network interface is made
8169  * active by the system (IFF_UP).  At this point all resources needed
8170  * for transmit and receive operations are allocated, the interrupt
8171  * handler is registered with the OS, the netdev watchdog subtask is
8172  * enabled, and the stack is notified that the interface is ready.
8173  *
8174  * Returns 0 on success, negative value on failure
8175  **/
8176 int i40e_open(struct net_device *netdev)
8177 {
8178 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8179 	struct i40e_vsi *vsi = np->vsi;
8180 	struct i40e_pf *pf = vsi->back;
8181 	int err;
8182 
8183 	/* disallow open during test or if eeprom is broken */
8184 	if (test_bit(__I40E_TESTING, pf->state) ||
8185 	    test_bit(__I40E_BAD_EEPROM, pf->state))
8186 		return -EBUSY;
8187 
8188 	netif_carrier_off(netdev);
8189 
8190 	if (i40e_force_link_state(pf, true))
8191 		return -EAGAIN;
8192 
8193 	err = i40e_vsi_open(vsi);
8194 	if (err)
8195 		return err;
8196 
8197 	/* configure global TSO hardware offload settings */
8198 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_F, be32_to_cpu(TCP_FLAG_PSH |
8199 						       TCP_FLAG_FIN) >> 16);
8200 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_M, be32_to_cpu(TCP_FLAG_PSH |
8201 						       TCP_FLAG_FIN |
8202 						       TCP_FLAG_CWR) >> 16);
8203 	wr32(&pf->hw, I40E_GLLAN_TSOMSK_L, be32_to_cpu(TCP_FLAG_CWR) >> 16);
8204 
8205 	udp_tunnel_get_rx_info(netdev);
8206 
8207 	return 0;
8208 }
8209 
8210 /**
8211  * i40e_vsi_open -
8212  * @vsi: the VSI to open
8213  *
8214  * Finish initialization of the VSI.
8215  *
8216  * Returns 0 on success, negative value on failure
8217  *
8218  * Note: expects to be called while under rtnl_lock()
8219  **/
8220 int i40e_vsi_open(struct i40e_vsi *vsi)
8221 {
8222 	struct i40e_pf *pf = vsi->back;
8223 	char int_name[I40E_INT_NAME_STR_LEN];
8224 	int err;
8225 
8226 	/* allocate descriptors */
8227 	err = i40e_vsi_setup_tx_resources(vsi);
8228 	if (err)
8229 		goto err_setup_tx;
8230 	err = i40e_vsi_setup_rx_resources(vsi);
8231 	if (err)
8232 		goto err_setup_rx;
8233 
8234 	err = i40e_vsi_configure(vsi);
8235 	if (err)
8236 		goto err_setup_rx;
8237 
8238 	if (vsi->netdev) {
8239 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s",
8240 			 dev_driver_string(&pf->pdev->dev), vsi->netdev->name);
8241 		err = i40e_vsi_request_irq(vsi, int_name);
8242 		if (err)
8243 			goto err_setup_rx;
8244 
8245 		/* Notify the stack of the actual queue counts. */
8246 		err = netif_set_real_num_tx_queues(vsi->netdev,
8247 						   vsi->num_queue_pairs);
8248 		if (err)
8249 			goto err_set_queues;
8250 
8251 		err = netif_set_real_num_rx_queues(vsi->netdev,
8252 						   vsi->num_queue_pairs);
8253 		if (err)
8254 			goto err_set_queues;
8255 
8256 	} else if (vsi->type == I40E_VSI_FDIR) {
8257 		snprintf(int_name, sizeof(int_name) - 1, "%s-%s:fdir",
8258 			 dev_driver_string(&pf->pdev->dev),
8259 			 dev_name(&pf->pdev->dev));
8260 		err = i40e_vsi_request_irq(vsi, int_name);
8261 
8262 	} else {
8263 		err = -EINVAL;
8264 		goto err_setup_rx;
8265 	}
8266 
8267 	err = i40e_up_complete(vsi);
8268 	if (err)
8269 		goto err_up_complete;
8270 
8271 	return 0;
8272 
8273 err_up_complete:
8274 	i40e_down(vsi);
8275 err_set_queues:
8276 	i40e_vsi_free_irq(vsi);
8277 err_setup_rx:
8278 	i40e_vsi_free_rx_resources(vsi);
8279 err_setup_tx:
8280 	i40e_vsi_free_tx_resources(vsi);
8281 	if (vsi == pf->vsi[pf->lan_vsi])
8282 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
8283 
8284 	return err;
8285 }
8286 
8287 /**
8288  * i40e_fdir_filter_exit - Cleans up the Flow Director accounting
8289  * @pf: Pointer to PF
8290  *
8291  * This function destroys the hlist where all the Flow Director
8292  * filters were saved.
8293  **/
8294 static void i40e_fdir_filter_exit(struct i40e_pf *pf)
8295 {
8296 	struct i40e_fdir_filter *filter;
8297 	struct i40e_flex_pit *pit_entry, *tmp;
8298 	struct hlist_node *node2;
8299 
8300 	hlist_for_each_entry_safe(filter, node2,
8301 				  &pf->fdir_filter_list, fdir_node) {
8302 		hlist_del(&filter->fdir_node);
8303 		kfree(filter);
8304 	}
8305 
8306 	list_for_each_entry_safe(pit_entry, tmp, &pf->l3_flex_pit_list, list) {
8307 		list_del(&pit_entry->list);
8308 		kfree(pit_entry);
8309 	}
8310 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
8311 
8312 	list_for_each_entry_safe(pit_entry, tmp, &pf->l4_flex_pit_list, list) {
8313 		list_del(&pit_entry->list);
8314 		kfree(pit_entry);
8315 	}
8316 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
8317 
8318 	pf->fdir_pf_active_filters = 0;
8319 	pf->fd_tcp4_filter_cnt = 0;
8320 	pf->fd_udp4_filter_cnt = 0;
8321 	pf->fd_sctp4_filter_cnt = 0;
8322 	pf->fd_ip4_filter_cnt = 0;
8323 
8324 	/* Reprogram the default input set for TCP/IPv4 */
8325 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
8326 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8327 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8328 
8329 	/* Reprogram the default input set for UDP/IPv4 */
8330 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_UDP,
8331 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8332 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8333 
8334 	/* Reprogram the default input set for SCTP/IPv4 */
8335 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_SCTP,
8336 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8337 				I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8338 
8339 	/* Reprogram the default input set for Other/IPv4 */
8340 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_OTHER,
8341 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
8342 
8343 	i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_FRAG_IPV4,
8344 				I40E_L3_SRC_MASK | I40E_L3_DST_MASK);
8345 }
8346 
8347 /**
8348  * i40e_cloud_filter_exit - Cleans up the cloud filters
8349  * @pf: Pointer to PF
8350  *
8351  * This function destroys the hlist where all the cloud filters
8352  * were saved.
8353  **/
8354 static void i40e_cloud_filter_exit(struct i40e_pf *pf)
8355 {
8356 	struct i40e_cloud_filter *cfilter;
8357 	struct hlist_node *node;
8358 
8359 	hlist_for_each_entry_safe(cfilter, node,
8360 				  &pf->cloud_filter_list, cloud_node) {
8361 		hlist_del(&cfilter->cloud_node);
8362 		kfree(cfilter);
8363 	}
8364 	pf->num_cloud_filters = 0;
8365 
8366 	if ((pf->flags & I40E_FLAG_FD_SB_TO_CLOUD_FILTER) &&
8367 	    !(pf->flags & I40E_FLAG_FD_SB_INACTIVE)) {
8368 		pf->flags |= I40E_FLAG_FD_SB_ENABLED;
8369 		pf->flags &= ~I40E_FLAG_FD_SB_TO_CLOUD_FILTER;
8370 		pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
8371 	}
8372 }
8373 
8374 /**
8375  * i40e_close - Disables a network interface
8376  * @netdev: network interface device structure
8377  *
8378  * The close entry point is called when an interface is de-activated
8379  * by the OS.  The hardware is still under the driver's control, but
8380  * this netdev interface is disabled.
8381  *
8382  * Returns 0, this is not allowed to fail
8383  **/
8384 int i40e_close(struct net_device *netdev)
8385 {
8386 	struct i40e_netdev_priv *np = netdev_priv(netdev);
8387 	struct i40e_vsi *vsi = np->vsi;
8388 
8389 	i40e_vsi_close(vsi);
8390 
8391 	return 0;
8392 }
8393 
8394 /**
8395  * i40e_do_reset - Start a PF or Core Reset sequence
8396  * @pf: board private structure
8397  * @reset_flags: which reset is requested
8398  * @lock_acquired: indicates whether or not the lock has been acquired
8399  * before this function was called.
8400  *
8401  * The essential difference in resets is that the PF Reset
8402  * doesn't clear the packet buffers, doesn't reset the PE
8403  * firmware, and doesn't bother the other PFs on the chip.
8404  **/
8405 void i40e_do_reset(struct i40e_pf *pf, u32 reset_flags, bool lock_acquired)
8406 {
8407 	u32 val;
8408 
8409 	WARN_ON(in_interrupt());
8410 
8411 
8412 	/* do the biggest reset indicated */
8413 	if (reset_flags & BIT_ULL(__I40E_GLOBAL_RESET_REQUESTED)) {
8414 
8415 		/* Request a Global Reset
8416 		 *
8417 		 * This will start the chip's countdown to the actual full
8418 		 * chip reset event, and a warning interrupt to be sent
8419 		 * to all PFs, including the requestor.  Our handler
8420 		 * for the warning interrupt will deal with the shutdown
8421 		 * and recovery of the switch setup.
8422 		 */
8423 		dev_dbg(&pf->pdev->dev, "GlobalR requested\n");
8424 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
8425 		val |= I40E_GLGEN_RTRIG_GLOBR_MASK;
8426 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
8427 
8428 	} else if (reset_flags & BIT_ULL(__I40E_CORE_RESET_REQUESTED)) {
8429 
8430 		/* Request a Core Reset
8431 		 *
8432 		 * Same as Global Reset, except does *not* include the MAC/PHY
8433 		 */
8434 		dev_dbg(&pf->pdev->dev, "CoreR requested\n");
8435 		val = rd32(&pf->hw, I40E_GLGEN_RTRIG);
8436 		val |= I40E_GLGEN_RTRIG_CORER_MASK;
8437 		wr32(&pf->hw, I40E_GLGEN_RTRIG, val);
8438 		i40e_flush(&pf->hw);
8439 
8440 	} else if (reset_flags & I40E_PF_RESET_FLAG) {
8441 
8442 		/* Request a PF Reset
8443 		 *
8444 		 * Resets only the PF-specific registers
8445 		 *
8446 		 * This goes directly to the tear-down and rebuild of
8447 		 * the switch, since we need to do all the recovery as
8448 		 * for the Core Reset.
8449 		 */
8450 		dev_dbg(&pf->pdev->dev, "PFR requested\n");
8451 		i40e_handle_reset_warning(pf, lock_acquired);
8452 
8453 		dev_info(&pf->pdev->dev,
8454 			 pf->flags & I40E_FLAG_DISABLE_FW_LLDP ?
8455 			 "FW LLDP is disabled\n" :
8456 			 "FW LLDP is enabled\n");
8457 
8458 	} else if (reset_flags & BIT_ULL(__I40E_REINIT_REQUESTED)) {
8459 		int v;
8460 
8461 		/* Find the VSI(s) that requested a re-init */
8462 		dev_info(&pf->pdev->dev,
8463 			 "VSI reinit requested\n");
8464 		for (v = 0; v < pf->num_alloc_vsi; v++) {
8465 			struct i40e_vsi *vsi = pf->vsi[v];
8466 
8467 			if (vsi != NULL &&
8468 			    test_and_clear_bit(__I40E_VSI_REINIT_REQUESTED,
8469 					       vsi->state))
8470 				i40e_vsi_reinit_locked(pf->vsi[v]);
8471 		}
8472 	} else if (reset_flags & BIT_ULL(__I40E_DOWN_REQUESTED)) {
8473 		int v;
8474 
8475 		/* Find the VSI(s) that needs to be brought down */
8476 		dev_info(&pf->pdev->dev, "VSI down requested\n");
8477 		for (v = 0; v < pf->num_alloc_vsi; v++) {
8478 			struct i40e_vsi *vsi = pf->vsi[v];
8479 
8480 			if (vsi != NULL &&
8481 			    test_and_clear_bit(__I40E_VSI_DOWN_REQUESTED,
8482 					       vsi->state)) {
8483 				set_bit(__I40E_VSI_DOWN, vsi->state);
8484 				i40e_down(vsi);
8485 			}
8486 		}
8487 	} else {
8488 		dev_info(&pf->pdev->dev,
8489 			 "bad reset request 0x%08x\n", reset_flags);
8490 	}
8491 }
8492 
8493 #ifdef CONFIG_I40E_DCB
8494 /**
8495  * i40e_dcb_need_reconfig - Check if DCB needs reconfig
8496  * @pf: board private structure
8497  * @old_cfg: current DCB config
8498  * @new_cfg: new DCB config
8499  **/
8500 bool i40e_dcb_need_reconfig(struct i40e_pf *pf,
8501 			    struct i40e_dcbx_config *old_cfg,
8502 			    struct i40e_dcbx_config *new_cfg)
8503 {
8504 	bool need_reconfig = false;
8505 
8506 	/* Check if ETS configuration has changed */
8507 	if (memcmp(&new_cfg->etscfg,
8508 		   &old_cfg->etscfg,
8509 		   sizeof(new_cfg->etscfg))) {
8510 		/* If Priority Table has changed reconfig is needed */
8511 		if (memcmp(&new_cfg->etscfg.prioritytable,
8512 			   &old_cfg->etscfg.prioritytable,
8513 			   sizeof(new_cfg->etscfg.prioritytable))) {
8514 			need_reconfig = true;
8515 			dev_dbg(&pf->pdev->dev, "ETS UP2TC changed.\n");
8516 		}
8517 
8518 		if (memcmp(&new_cfg->etscfg.tcbwtable,
8519 			   &old_cfg->etscfg.tcbwtable,
8520 			   sizeof(new_cfg->etscfg.tcbwtable)))
8521 			dev_dbg(&pf->pdev->dev, "ETS TC BW Table changed.\n");
8522 
8523 		if (memcmp(&new_cfg->etscfg.tsatable,
8524 			   &old_cfg->etscfg.tsatable,
8525 			   sizeof(new_cfg->etscfg.tsatable)))
8526 			dev_dbg(&pf->pdev->dev, "ETS TSA Table changed.\n");
8527 	}
8528 
8529 	/* Check if PFC configuration has changed */
8530 	if (memcmp(&new_cfg->pfc,
8531 		   &old_cfg->pfc,
8532 		   sizeof(new_cfg->pfc))) {
8533 		need_reconfig = true;
8534 		dev_dbg(&pf->pdev->dev, "PFC config change detected.\n");
8535 	}
8536 
8537 	/* Check if APP Table has changed */
8538 	if (memcmp(&new_cfg->app,
8539 		   &old_cfg->app,
8540 		   sizeof(new_cfg->app))) {
8541 		need_reconfig = true;
8542 		dev_dbg(&pf->pdev->dev, "APP Table change detected.\n");
8543 	}
8544 
8545 	dev_dbg(&pf->pdev->dev, "dcb need_reconfig=%d\n", need_reconfig);
8546 	return need_reconfig;
8547 }
8548 
8549 /**
8550  * i40e_handle_lldp_event - Handle LLDP Change MIB event
8551  * @pf: board private structure
8552  * @e: event info posted on ARQ
8553  **/
8554 static int i40e_handle_lldp_event(struct i40e_pf *pf,
8555 				  struct i40e_arq_event_info *e)
8556 {
8557 	struct i40e_aqc_lldp_get_mib *mib =
8558 		(struct i40e_aqc_lldp_get_mib *)&e->desc.params.raw;
8559 	struct i40e_hw *hw = &pf->hw;
8560 	struct i40e_dcbx_config tmp_dcbx_cfg;
8561 	bool need_reconfig = false;
8562 	int ret = 0;
8563 	u8 type;
8564 
8565 	/* Not DCB capable or capability disabled */
8566 	if (!(pf->flags & I40E_FLAG_DCB_CAPABLE))
8567 		return ret;
8568 
8569 	/* Ignore if event is not for Nearest Bridge */
8570 	type = ((mib->type >> I40E_AQ_LLDP_BRIDGE_TYPE_SHIFT)
8571 		& I40E_AQ_LLDP_BRIDGE_TYPE_MASK);
8572 	dev_dbg(&pf->pdev->dev, "LLDP event mib bridge type 0x%x\n", type);
8573 	if (type != I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE)
8574 		return ret;
8575 
8576 	/* Check MIB Type and return if event for Remote MIB update */
8577 	type = mib->type & I40E_AQ_LLDP_MIB_TYPE_MASK;
8578 	dev_dbg(&pf->pdev->dev,
8579 		"LLDP event mib type %s\n", type ? "remote" : "local");
8580 	if (type == I40E_AQ_LLDP_MIB_REMOTE) {
8581 		/* Update the remote cached instance and return */
8582 		ret = i40e_aq_get_dcb_config(hw, I40E_AQ_LLDP_MIB_REMOTE,
8583 				I40E_AQ_LLDP_BRIDGE_TYPE_NEAREST_BRIDGE,
8584 				&hw->remote_dcbx_config);
8585 		goto exit;
8586 	}
8587 
8588 	/* Store the old configuration */
8589 	tmp_dcbx_cfg = hw->local_dcbx_config;
8590 
8591 	/* Reset the old DCBx configuration data */
8592 	memset(&hw->local_dcbx_config, 0, sizeof(hw->local_dcbx_config));
8593 	/* Get updated DCBX data from firmware */
8594 	ret = i40e_get_dcb_config(&pf->hw);
8595 	if (ret) {
8596 		dev_info(&pf->pdev->dev,
8597 			 "Failed querying DCB configuration data from firmware, err %s aq_err %s\n",
8598 			 i40e_stat_str(&pf->hw, ret),
8599 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
8600 		goto exit;
8601 	}
8602 
8603 	/* No change detected in DCBX configs */
8604 	if (!memcmp(&tmp_dcbx_cfg, &hw->local_dcbx_config,
8605 		    sizeof(tmp_dcbx_cfg))) {
8606 		dev_dbg(&pf->pdev->dev, "No change detected in DCBX configuration.\n");
8607 		goto exit;
8608 	}
8609 
8610 	need_reconfig = i40e_dcb_need_reconfig(pf, &tmp_dcbx_cfg,
8611 					       &hw->local_dcbx_config);
8612 
8613 	i40e_dcbnl_flush_apps(pf, &tmp_dcbx_cfg, &hw->local_dcbx_config);
8614 
8615 	if (!need_reconfig)
8616 		goto exit;
8617 
8618 	/* Enable DCB tagging only when more than one TC */
8619 	if (i40e_dcb_get_num_tc(&hw->local_dcbx_config) > 1)
8620 		pf->flags |= I40E_FLAG_DCB_ENABLED;
8621 	else
8622 		pf->flags &= ~I40E_FLAG_DCB_ENABLED;
8623 
8624 	set_bit(__I40E_PORT_SUSPENDED, pf->state);
8625 	/* Reconfiguration needed quiesce all VSIs */
8626 	i40e_pf_quiesce_all_vsi(pf);
8627 
8628 	/* Changes in configuration update VEB/VSI */
8629 	i40e_dcb_reconfigure(pf);
8630 
8631 	ret = i40e_resume_port_tx(pf);
8632 
8633 	clear_bit(__I40E_PORT_SUSPENDED, pf->state);
8634 	/* In case of error no point in resuming VSIs */
8635 	if (ret)
8636 		goto exit;
8637 
8638 	/* Wait for the PF's queues to be disabled */
8639 	ret = i40e_pf_wait_queues_disabled(pf);
8640 	if (ret) {
8641 		/* Schedule PF reset to recover */
8642 		set_bit(__I40E_PF_RESET_REQUESTED, pf->state);
8643 		i40e_service_event_schedule(pf);
8644 	} else {
8645 		i40e_pf_unquiesce_all_vsi(pf);
8646 		set_bit(__I40E_CLIENT_SERVICE_REQUESTED, pf->state);
8647 		set_bit(__I40E_CLIENT_L2_CHANGE, pf->state);
8648 	}
8649 
8650 exit:
8651 	return ret;
8652 }
8653 #endif /* CONFIG_I40E_DCB */
8654 
8655 /**
8656  * i40e_do_reset_safe - Protected reset path for userland calls.
8657  * @pf: board private structure
8658  * @reset_flags: which reset is requested
8659  *
8660  **/
8661 void i40e_do_reset_safe(struct i40e_pf *pf, u32 reset_flags)
8662 {
8663 	rtnl_lock();
8664 	i40e_do_reset(pf, reset_flags, true);
8665 	rtnl_unlock();
8666 }
8667 
8668 /**
8669  * i40e_handle_lan_overflow_event - Handler for LAN queue overflow event
8670  * @pf: board private structure
8671  * @e: event info posted on ARQ
8672  *
8673  * Handler for LAN Queue Overflow Event generated by the firmware for PF
8674  * and VF queues
8675  **/
8676 static void i40e_handle_lan_overflow_event(struct i40e_pf *pf,
8677 					   struct i40e_arq_event_info *e)
8678 {
8679 	struct i40e_aqc_lan_overflow *data =
8680 		(struct i40e_aqc_lan_overflow *)&e->desc.params.raw;
8681 	u32 queue = le32_to_cpu(data->prtdcb_rupto);
8682 	u32 qtx_ctl = le32_to_cpu(data->otx_ctl);
8683 	struct i40e_hw *hw = &pf->hw;
8684 	struct i40e_vf *vf;
8685 	u16 vf_id;
8686 
8687 	dev_dbg(&pf->pdev->dev, "overflow Rx Queue Number = %d QTX_CTL=0x%08x\n",
8688 		queue, qtx_ctl);
8689 
8690 	/* Queue belongs to VF, find the VF and issue VF reset */
8691 	if (((qtx_ctl & I40E_QTX_CTL_PFVF_Q_MASK)
8692 	    >> I40E_QTX_CTL_PFVF_Q_SHIFT) == I40E_QTX_CTL_VF_QUEUE) {
8693 		vf_id = (u16)((qtx_ctl & I40E_QTX_CTL_VFVM_INDX_MASK)
8694 			 >> I40E_QTX_CTL_VFVM_INDX_SHIFT);
8695 		vf_id -= hw->func_caps.vf_base_id;
8696 		vf = &pf->vf[vf_id];
8697 		i40e_vc_notify_vf_reset(vf);
8698 		/* Allow VF to process pending reset notification */
8699 		msleep(20);
8700 		i40e_reset_vf(vf, false);
8701 	}
8702 }
8703 
8704 /**
8705  * i40e_get_cur_guaranteed_fd_count - Get the consumed guaranteed FD filters
8706  * @pf: board private structure
8707  **/
8708 u32 i40e_get_cur_guaranteed_fd_count(struct i40e_pf *pf)
8709 {
8710 	u32 val, fcnt_prog;
8711 
8712 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
8713 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK);
8714 	return fcnt_prog;
8715 }
8716 
8717 /**
8718  * i40e_get_current_fd_count - Get total FD filters programmed for this PF
8719  * @pf: board private structure
8720  **/
8721 u32 i40e_get_current_fd_count(struct i40e_pf *pf)
8722 {
8723 	u32 val, fcnt_prog;
8724 
8725 	val = rd32(&pf->hw, I40E_PFQF_FDSTAT);
8726 	fcnt_prog = (val & I40E_PFQF_FDSTAT_GUARANT_CNT_MASK) +
8727 		    ((val & I40E_PFQF_FDSTAT_BEST_CNT_MASK) >>
8728 		      I40E_PFQF_FDSTAT_BEST_CNT_SHIFT);
8729 	return fcnt_prog;
8730 }
8731 
8732 /**
8733  * i40e_get_global_fd_count - Get total FD filters programmed on device
8734  * @pf: board private structure
8735  **/
8736 u32 i40e_get_global_fd_count(struct i40e_pf *pf)
8737 {
8738 	u32 val, fcnt_prog;
8739 
8740 	val = rd32(&pf->hw, I40E_GLQF_FDCNT_0);
8741 	fcnt_prog = (val & I40E_GLQF_FDCNT_0_GUARANT_CNT_MASK) +
8742 		    ((val & I40E_GLQF_FDCNT_0_BESTCNT_MASK) >>
8743 		     I40E_GLQF_FDCNT_0_BESTCNT_SHIFT);
8744 	return fcnt_prog;
8745 }
8746 
8747 /**
8748  * i40e_reenable_fdir_sb - Restore FDir SB capability
8749  * @pf: board private structure
8750  **/
8751 static void i40e_reenable_fdir_sb(struct i40e_pf *pf)
8752 {
8753 	if (test_and_clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state))
8754 		if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
8755 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
8756 			dev_info(&pf->pdev->dev, "FD Sideband/ntuple is being enabled since we have space in the table now\n");
8757 }
8758 
8759 /**
8760  * i40e_reenable_fdir_atr - Restore FDir ATR capability
8761  * @pf: board private structure
8762  **/
8763 static void i40e_reenable_fdir_atr(struct i40e_pf *pf)
8764 {
8765 	if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state)) {
8766 		/* ATR uses the same filtering logic as SB rules. It only
8767 		 * functions properly if the input set mask is at the default
8768 		 * settings. It is safe to restore the default input set
8769 		 * because there are no active TCPv4 filter rules.
8770 		 */
8771 		i40e_write_fd_input_set(pf, I40E_FILTER_PCTYPE_NONF_IPV4_TCP,
8772 					I40E_L3_SRC_MASK | I40E_L3_DST_MASK |
8773 					I40E_L4_SRC_MASK | I40E_L4_DST_MASK);
8774 
8775 		if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
8776 		    (I40E_DEBUG_FD & pf->hw.debug_mask))
8777 			dev_info(&pf->pdev->dev, "ATR is being enabled since we have space in the table and there are no conflicting ntuple rules\n");
8778 	}
8779 }
8780 
8781 /**
8782  * i40e_delete_invalid_filter - Delete an invalid FDIR filter
8783  * @pf: board private structure
8784  * @filter: FDir filter to remove
8785  */
8786 static void i40e_delete_invalid_filter(struct i40e_pf *pf,
8787 				       struct i40e_fdir_filter *filter)
8788 {
8789 	/* Update counters */
8790 	pf->fdir_pf_active_filters--;
8791 	pf->fd_inv = 0;
8792 
8793 	switch (filter->flow_type) {
8794 	case TCP_V4_FLOW:
8795 		pf->fd_tcp4_filter_cnt--;
8796 		break;
8797 	case UDP_V4_FLOW:
8798 		pf->fd_udp4_filter_cnt--;
8799 		break;
8800 	case SCTP_V4_FLOW:
8801 		pf->fd_sctp4_filter_cnt--;
8802 		break;
8803 	case IP_USER_FLOW:
8804 		switch (filter->ip4_proto) {
8805 		case IPPROTO_TCP:
8806 			pf->fd_tcp4_filter_cnt--;
8807 			break;
8808 		case IPPROTO_UDP:
8809 			pf->fd_udp4_filter_cnt--;
8810 			break;
8811 		case IPPROTO_SCTP:
8812 			pf->fd_sctp4_filter_cnt--;
8813 			break;
8814 		case IPPROTO_IP:
8815 			pf->fd_ip4_filter_cnt--;
8816 			break;
8817 		}
8818 		break;
8819 	}
8820 
8821 	/* Remove the filter from the list and free memory */
8822 	hlist_del(&filter->fdir_node);
8823 	kfree(filter);
8824 }
8825 
8826 /**
8827  * i40e_fdir_check_and_reenable - Function to reenabe FD ATR or SB if disabled
8828  * @pf: board private structure
8829  **/
8830 void i40e_fdir_check_and_reenable(struct i40e_pf *pf)
8831 {
8832 	struct i40e_fdir_filter *filter;
8833 	u32 fcnt_prog, fcnt_avail;
8834 	struct hlist_node *node;
8835 
8836 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
8837 		return;
8838 
8839 	/* Check if we have enough room to re-enable FDir SB capability. */
8840 	fcnt_prog = i40e_get_global_fd_count(pf);
8841 	fcnt_avail = pf->fdir_pf_filter_count;
8842 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM)) ||
8843 	    (pf->fd_add_err == 0) ||
8844 	    (i40e_get_current_atr_cnt(pf) < pf->fd_atr_cnt))
8845 		i40e_reenable_fdir_sb(pf);
8846 
8847 	/* We should wait for even more space before re-enabling ATR.
8848 	 * Additionally, we cannot enable ATR as long as we still have TCP SB
8849 	 * rules active.
8850 	 */
8851 	if ((fcnt_prog < (fcnt_avail - I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) &&
8852 	    (pf->fd_tcp4_filter_cnt == 0))
8853 		i40e_reenable_fdir_atr(pf);
8854 
8855 	/* if hw had a problem adding a filter, delete it */
8856 	if (pf->fd_inv > 0) {
8857 		hlist_for_each_entry_safe(filter, node,
8858 					  &pf->fdir_filter_list, fdir_node)
8859 			if (filter->fd_id == pf->fd_inv)
8860 				i40e_delete_invalid_filter(pf, filter);
8861 	}
8862 }
8863 
8864 #define I40E_MIN_FD_FLUSH_INTERVAL 10
8865 #define I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE 30
8866 /**
8867  * i40e_fdir_flush_and_replay - Function to flush all FD filters and replay SB
8868  * @pf: board private structure
8869  **/
8870 static void i40e_fdir_flush_and_replay(struct i40e_pf *pf)
8871 {
8872 	unsigned long min_flush_time;
8873 	int flush_wait_retry = 50;
8874 	bool disable_atr = false;
8875 	int fd_room;
8876 	int reg;
8877 
8878 	if (!time_after(jiffies, pf->fd_flush_timestamp +
8879 				 (I40E_MIN_FD_FLUSH_INTERVAL * HZ)))
8880 		return;
8881 
8882 	/* If the flush is happening too quick and we have mostly SB rules we
8883 	 * should not re-enable ATR for some time.
8884 	 */
8885 	min_flush_time = pf->fd_flush_timestamp +
8886 			 (I40E_MIN_FD_FLUSH_SB_ATR_UNSTABLE * HZ);
8887 	fd_room = pf->fdir_pf_filter_count - pf->fdir_pf_active_filters;
8888 
8889 	if (!(time_after(jiffies, min_flush_time)) &&
8890 	    (fd_room < I40E_FDIR_BUFFER_HEAD_ROOM_FOR_ATR)) {
8891 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
8892 			dev_info(&pf->pdev->dev, "ATR disabled, not enough FD filter space.\n");
8893 		disable_atr = true;
8894 	}
8895 
8896 	pf->fd_flush_timestamp = jiffies;
8897 	set_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
8898 	/* flush all filters */
8899 	wr32(&pf->hw, I40E_PFQF_CTL_1,
8900 	     I40E_PFQF_CTL_1_CLEARFDTABLE_MASK);
8901 	i40e_flush(&pf->hw);
8902 	pf->fd_flush_cnt++;
8903 	pf->fd_add_err = 0;
8904 	do {
8905 		/* Check FD flush status every 5-6msec */
8906 		usleep_range(5000, 6000);
8907 		reg = rd32(&pf->hw, I40E_PFQF_CTL_1);
8908 		if (!(reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK))
8909 			break;
8910 	} while (flush_wait_retry--);
8911 	if (reg & I40E_PFQF_CTL_1_CLEARFDTABLE_MASK) {
8912 		dev_warn(&pf->pdev->dev, "FD table did not flush, needs more time\n");
8913 	} else {
8914 		/* replay sideband filters */
8915 		i40e_fdir_filter_restore(pf->vsi[pf->lan_vsi]);
8916 		if (!disable_atr && !pf->fd_tcp4_filter_cnt)
8917 			clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state);
8918 		clear_bit(__I40E_FD_FLUSH_REQUESTED, pf->state);
8919 		if (I40E_DEBUG_FD & pf->hw.debug_mask)
8920 			dev_info(&pf->pdev->dev, "FD Filter table flushed and FD-SB replayed.\n");
8921 	}
8922 }
8923 
8924 /**
8925  * i40e_get_current_atr_count - Get the count of total FD ATR filters programmed
8926  * @pf: board private structure
8927  **/
8928 u32 i40e_get_current_atr_cnt(struct i40e_pf *pf)
8929 {
8930 	return i40e_get_current_fd_count(pf) - pf->fdir_pf_active_filters;
8931 }
8932 
8933 /* We can see up to 256 filter programming desc in transit if the filters are
8934  * being applied really fast; before we see the first
8935  * filter miss error on Rx queue 0. Accumulating enough error messages before
8936  * reacting will make sure we don't cause flush too often.
8937  */
8938 #define I40E_MAX_FD_PROGRAM_ERROR 256
8939 
8940 /**
8941  * i40e_fdir_reinit_subtask - Worker thread to reinit FDIR filter table
8942  * @pf: board private structure
8943  **/
8944 static void i40e_fdir_reinit_subtask(struct i40e_pf *pf)
8945 {
8946 
8947 	/* if interface is down do nothing */
8948 	if (test_bit(__I40E_DOWN, pf->state))
8949 		return;
8950 
8951 	if (test_bit(__I40E_FD_FLUSH_REQUESTED, pf->state))
8952 		i40e_fdir_flush_and_replay(pf);
8953 
8954 	i40e_fdir_check_and_reenable(pf);
8955 
8956 }
8957 
8958 /**
8959  * i40e_vsi_link_event - notify VSI of a link event
8960  * @vsi: vsi to be notified
8961  * @link_up: link up or down
8962  **/
8963 static void i40e_vsi_link_event(struct i40e_vsi *vsi, bool link_up)
8964 {
8965 	if (!vsi || test_bit(__I40E_VSI_DOWN, vsi->state))
8966 		return;
8967 
8968 	switch (vsi->type) {
8969 	case I40E_VSI_MAIN:
8970 		if (!vsi->netdev || !vsi->netdev_registered)
8971 			break;
8972 
8973 		if (link_up) {
8974 			netif_carrier_on(vsi->netdev);
8975 			netif_tx_wake_all_queues(vsi->netdev);
8976 		} else {
8977 			netif_carrier_off(vsi->netdev);
8978 			netif_tx_stop_all_queues(vsi->netdev);
8979 		}
8980 		break;
8981 
8982 	case I40E_VSI_SRIOV:
8983 	case I40E_VSI_VMDQ2:
8984 	case I40E_VSI_CTRL:
8985 	case I40E_VSI_IWARP:
8986 	case I40E_VSI_MIRROR:
8987 	default:
8988 		/* there is no notification for other VSIs */
8989 		break;
8990 	}
8991 }
8992 
8993 /**
8994  * i40e_veb_link_event - notify elements on the veb of a link event
8995  * @veb: veb to be notified
8996  * @link_up: link up or down
8997  **/
8998 static void i40e_veb_link_event(struct i40e_veb *veb, bool link_up)
8999 {
9000 	struct i40e_pf *pf;
9001 	int i;
9002 
9003 	if (!veb || !veb->pf)
9004 		return;
9005 	pf = veb->pf;
9006 
9007 	/* depth first... */
9008 	for (i = 0; i < I40E_MAX_VEB; i++)
9009 		if (pf->veb[i] && (pf->veb[i]->uplink_seid == veb->seid))
9010 			i40e_veb_link_event(pf->veb[i], link_up);
9011 
9012 	/* ... now the local VSIs */
9013 	for (i = 0; i < pf->num_alloc_vsi; i++)
9014 		if (pf->vsi[i] && (pf->vsi[i]->uplink_seid == veb->seid))
9015 			i40e_vsi_link_event(pf->vsi[i], link_up);
9016 }
9017 
9018 /**
9019  * i40e_link_event - Update netif_carrier status
9020  * @pf: board private structure
9021  **/
9022 static void i40e_link_event(struct i40e_pf *pf)
9023 {
9024 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9025 	u8 new_link_speed, old_link_speed;
9026 	i40e_status status;
9027 	bool new_link, old_link;
9028 
9029 	/* set this to force the get_link_status call to refresh state */
9030 	pf->hw.phy.get_link_info = true;
9031 	old_link = (pf->hw.phy.link_info_old.link_info & I40E_AQ_LINK_UP);
9032 	status = i40e_get_link_status(&pf->hw, &new_link);
9033 
9034 	/* On success, disable temp link polling */
9035 	if (status == I40E_SUCCESS) {
9036 		clear_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9037 	} else {
9038 		/* Enable link polling temporarily until i40e_get_link_status
9039 		 * returns I40E_SUCCESS
9040 		 */
9041 		set_bit(__I40E_TEMP_LINK_POLLING, pf->state);
9042 		dev_dbg(&pf->pdev->dev, "couldn't get link state, status: %d\n",
9043 			status);
9044 		return;
9045 	}
9046 
9047 	old_link_speed = pf->hw.phy.link_info_old.link_speed;
9048 	new_link_speed = pf->hw.phy.link_info.link_speed;
9049 
9050 	if (new_link == old_link &&
9051 	    new_link_speed == old_link_speed &&
9052 	    (test_bit(__I40E_VSI_DOWN, vsi->state) ||
9053 	     new_link == netif_carrier_ok(vsi->netdev)))
9054 		return;
9055 
9056 	i40e_print_link_message(vsi, new_link);
9057 
9058 	/* Notify the base of the switch tree connected to
9059 	 * the link.  Floating VEBs are not notified.
9060 	 */
9061 	if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
9062 		i40e_veb_link_event(pf->veb[pf->lan_veb], new_link);
9063 	else
9064 		i40e_vsi_link_event(vsi, new_link);
9065 
9066 	if (pf->vf)
9067 		i40e_vc_notify_link_state(pf);
9068 
9069 	if (pf->flags & I40E_FLAG_PTP)
9070 		i40e_ptp_set_increment(pf);
9071 }
9072 
9073 /**
9074  * i40e_watchdog_subtask - periodic checks not using event driven response
9075  * @pf: board private structure
9076  **/
9077 static void i40e_watchdog_subtask(struct i40e_pf *pf)
9078 {
9079 	int i;
9080 
9081 	/* if interface is down do nothing */
9082 	if (test_bit(__I40E_DOWN, pf->state) ||
9083 	    test_bit(__I40E_CONFIG_BUSY, pf->state))
9084 		return;
9085 
9086 	/* make sure we don't do these things too often */
9087 	if (time_before(jiffies, (pf->service_timer_previous +
9088 				  pf->service_timer_period)))
9089 		return;
9090 	pf->service_timer_previous = jiffies;
9091 
9092 	if ((pf->flags & I40E_FLAG_LINK_POLLING_ENABLED) ||
9093 	    test_bit(__I40E_TEMP_LINK_POLLING, pf->state))
9094 		i40e_link_event(pf);
9095 
9096 	/* Update the stats for active netdevs so the network stack
9097 	 * can look at updated numbers whenever it cares to
9098 	 */
9099 	for (i = 0; i < pf->num_alloc_vsi; i++)
9100 		if (pf->vsi[i] && pf->vsi[i]->netdev)
9101 			i40e_update_stats(pf->vsi[i]);
9102 
9103 	if (pf->flags & I40E_FLAG_VEB_STATS_ENABLED) {
9104 		/* Update the stats for the active switching components */
9105 		for (i = 0; i < I40E_MAX_VEB; i++)
9106 			if (pf->veb[i])
9107 				i40e_update_veb_stats(pf->veb[i]);
9108 	}
9109 
9110 	i40e_ptp_rx_hang(pf);
9111 	i40e_ptp_tx_hang(pf);
9112 }
9113 
9114 /**
9115  * i40e_reset_subtask - Set up for resetting the device and driver
9116  * @pf: board private structure
9117  **/
9118 static void i40e_reset_subtask(struct i40e_pf *pf)
9119 {
9120 	u32 reset_flags = 0;
9121 
9122 	if (test_bit(__I40E_REINIT_REQUESTED, pf->state)) {
9123 		reset_flags |= BIT(__I40E_REINIT_REQUESTED);
9124 		clear_bit(__I40E_REINIT_REQUESTED, pf->state);
9125 	}
9126 	if (test_bit(__I40E_PF_RESET_REQUESTED, pf->state)) {
9127 		reset_flags |= BIT(__I40E_PF_RESET_REQUESTED);
9128 		clear_bit(__I40E_PF_RESET_REQUESTED, pf->state);
9129 	}
9130 	if (test_bit(__I40E_CORE_RESET_REQUESTED, pf->state)) {
9131 		reset_flags |= BIT(__I40E_CORE_RESET_REQUESTED);
9132 		clear_bit(__I40E_CORE_RESET_REQUESTED, pf->state);
9133 	}
9134 	if (test_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state)) {
9135 		reset_flags |= BIT(__I40E_GLOBAL_RESET_REQUESTED);
9136 		clear_bit(__I40E_GLOBAL_RESET_REQUESTED, pf->state);
9137 	}
9138 	if (test_bit(__I40E_DOWN_REQUESTED, pf->state)) {
9139 		reset_flags |= BIT(__I40E_DOWN_REQUESTED);
9140 		clear_bit(__I40E_DOWN_REQUESTED, pf->state);
9141 	}
9142 
9143 	/* If there's a recovery already waiting, it takes
9144 	 * precedence before starting a new reset sequence.
9145 	 */
9146 	if (test_bit(__I40E_RESET_INTR_RECEIVED, pf->state)) {
9147 		i40e_prep_for_reset(pf, false);
9148 		i40e_reset(pf);
9149 		i40e_rebuild(pf, false, false);
9150 	}
9151 
9152 	/* If we're already down or resetting, just bail */
9153 	if (reset_flags &&
9154 	    !test_bit(__I40E_DOWN, pf->state) &&
9155 	    !test_bit(__I40E_CONFIG_BUSY, pf->state)) {
9156 		i40e_do_reset(pf, reset_flags, false);
9157 	}
9158 }
9159 
9160 /**
9161  * i40e_handle_link_event - Handle link event
9162  * @pf: board private structure
9163  * @e: event info posted on ARQ
9164  **/
9165 static void i40e_handle_link_event(struct i40e_pf *pf,
9166 				   struct i40e_arq_event_info *e)
9167 {
9168 	struct i40e_aqc_get_link_status *status =
9169 		(struct i40e_aqc_get_link_status *)&e->desc.params.raw;
9170 
9171 	/* Do a new status request to re-enable LSE reporting
9172 	 * and load new status information into the hw struct
9173 	 * This completely ignores any state information
9174 	 * in the ARQ event info, instead choosing to always
9175 	 * issue the AQ update link status command.
9176 	 */
9177 	i40e_link_event(pf);
9178 
9179 	/* Check if module meets thermal requirements */
9180 	if (status->phy_type == I40E_PHY_TYPE_NOT_SUPPORTED_HIGH_TEMP) {
9181 		dev_err(&pf->pdev->dev,
9182 			"Rx/Tx is disabled on this device because the module does not meet thermal requirements.\n");
9183 		dev_err(&pf->pdev->dev,
9184 			"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9185 	} else {
9186 		/* check for unqualified module, if link is down, suppress
9187 		 * the message if link was forced to be down.
9188 		 */
9189 		if ((status->link_info & I40E_AQ_MEDIA_AVAILABLE) &&
9190 		    (!(status->an_info & I40E_AQ_QUALIFIED_MODULE)) &&
9191 		    (!(status->link_info & I40E_AQ_LINK_UP)) &&
9192 		    (!(pf->flags & I40E_FLAG_LINK_DOWN_ON_CLOSE_ENABLED))) {
9193 			dev_err(&pf->pdev->dev,
9194 				"Rx/Tx is disabled on this device because an unsupported SFP module type was detected.\n");
9195 			dev_err(&pf->pdev->dev,
9196 				"Refer to the Intel(R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
9197 		}
9198 	}
9199 }
9200 
9201 /**
9202  * i40e_clean_adminq_subtask - Clean the AdminQ rings
9203  * @pf: board private structure
9204  **/
9205 static void i40e_clean_adminq_subtask(struct i40e_pf *pf)
9206 {
9207 	struct i40e_arq_event_info event;
9208 	struct i40e_hw *hw = &pf->hw;
9209 	u16 pending, i = 0;
9210 	i40e_status ret;
9211 	u16 opcode;
9212 	u32 oldval;
9213 	u32 val;
9214 
9215 	/* Do not run clean AQ when PF reset fails */
9216 	if (test_bit(__I40E_RESET_FAILED, pf->state))
9217 		return;
9218 
9219 	/* check for error indications */
9220 	val = rd32(&pf->hw, pf->hw.aq.arq.len);
9221 	oldval = val;
9222 	if (val & I40E_PF_ARQLEN_ARQVFE_MASK) {
9223 		if (hw->debug_mask & I40E_DEBUG_AQ)
9224 			dev_info(&pf->pdev->dev, "ARQ VF Error detected\n");
9225 		val &= ~I40E_PF_ARQLEN_ARQVFE_MASK;
9226 	}
9227 	if (val & I40E_PF_ARQLEN_ARQOVFL_MASK) {
9228 		if (hw->debug_mask & I40E_DEBUG_AQ)
9229 			dev_info(&pf->pdev->dev, "ARQ Overflow Error detected\n");
9230 		val &= ~I40E_PF_ARQLEN_ARQOVFL_MASK;
9231 		pf->arq_overflows++;
9232 	}
9233 	if (val & I40E_PF_ARQLEN_ARQCRIT_MASK) {
9234 		if (hw->debug_mask & I40E_DEBUG_AQ)
9235 			dev_info(&pf->pdev->dev, "ARQ Critical Error detected\n");
9236 		val &= ~I40E_PF_ARQLEN_ARQCRIT_MASK;
9237 	}
9238 	if (oldval != val)
9239 		wr32(&pf->hw, pf->hw.aq.arq.len, val);
9240 
9241 	val = rd32(&pf->hw, pf->hw.aq.asq.len);
9242 	oldval = val;
9243 	if (val & I40E_PF_ATQLEN_ATQVFE_MASK) {
9244 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9245 			dev_info(&pf->pdev->dev, "ASQ VF Error detected\n");
9246 		val &= ~I40E_PF_ATQLEN_ATQVFE_MASK;
9247 	}
9248 	if (val & I40E_PF_ATQLEN_ATQOVFL_MASK) {
9249 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9250 			dev_info(&pf->pdev->dev, "ASQ Overflow Error detected\n");
9251 		val &= ~I40E_PF_ATQLEN_ATQOVFL_MASK;
9252 	}
9253 	if (val & I40E_PF_ATQLEN_ATQCRIT_MASK) {
9254 		if (pf->hw.debug_mask & I40E_DEBUG_AQ)
9255 			dev_info(&pf->pdev->dev, "ASQ Critical Error detected\n");
9256 		val &= ~I40E_PF_ATQLEN_ATQCRIT_MASK;
9257 	}
9258 	if (oldval != val)
9259 		wr32(&pf->hw, pf->hw.aq.asq.len, val);
9260 
9261 	event.buf_len = I40E_MAX_AQ_BUF_SIZE;
9262 	event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
9263 	if (!event.msg_buf)
9264 		return;
9265 
9266 	do {
9267 		ret = i40e_clean_arq_element(hw, &event, &pending);
9268 		if (ret == I40E_ERR_ADMIN_QUEUE_NO_WORK)
9269 			break;
9270 		else if (ret) {
9271 			dev_info(&pf->pdev->dev, "ARQ event error %d\n", ret);
9272 			break;
9273 		}
9274 
9275 		opcode = le16_to_cpu(event.desc.opcode);
9276 		switch (opcode) {
9277 
9278 		case i40e_aqc_opc_get_link_status:
9279 			i40e_handle_link_event(pf, &event);
9280 			break;
9281 		case i40e_aqc_opc_send_msg_to_pf:
9282 			ret = i40e_vc_process_vf_msg(pf,
9283 					le16_to_cpu(event.desc.retval),
9284 					le32_to_cpu(event.desc.cookie_high),
9285 					le32_to_cpu(event.desc.cookie_low),
9286 					event.msg_buf,
9287 					event.msg_len);
9288 			break;
9289 		case i40e_aqc_opc_lldp_update_mib:
9290 			dev_dbg(&pf->pdev->dev, "ARQ: Update LLDP MIB event received\n");
9291 #ifdef CONFIG_I40E_DCB
9292 			rtnl_lock();
9293 			ret = i40e_handle_lldp_event(pf, &event);
9294 			rtnl_unlock();
9295 #endif /* CONFIG_I40E_DCB */
9296 			break;
9297 		case i40e_aqc_opc_event_lan_overflow:
9298 			dev_dbg(&pf->pdev->dev, "ARQ LAN queue overflow event received\n");
9299 			i40e_handle_lan_overflow_event(pf, &event);
9300 			break;
9301 		case i40e_aqc_opc_send_msg_to_peer:
9302 			dev_info(&pf->pdev->dev, "ARQ: Msg from other pf\n");
9303 			break;
9304 		case i40e_aqc_opc_nvm_erase:
9305 		case i40e_aqc_opc_nvm_update:
9306 		case i40e_aqc_opc_oem_post_update:
9307 			i40e_debug(&pf->hw, I40E_DEBUG_NVM,
9308 				   "ARQ NVM operation 0x%04x completed\n",
9309 				   opcode);
9310 			break;
9311 		default:
9312 			dev_info(&pf->pdev->dev,
9313 				 "ARQ: Unknown event 0x%04x ignored\n",
9314 				 opcode);
9315 			break;
9316 		}
9317 	} while (i++ < pf->adminq_work_limit);
9318 
9319 	if (i < pf->adminq_work_limit)
9320 		clear_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state);
9321 
9322 	/* re-enable Admin queue interrupt cause */
9323 	val = rd32(hw, I40E_PFINT_ICR0_ENA);
9324 	val |=  I40E_PFINT_ICR0_ENA_ADMINQ_MASK;
9325 	wr32(hw, I40E_PFINT_ICR0_ENA, val);
9326 	i40e_flush(hw);
9327 
9328 	kfree(event.msg_buf);
9329 }
9330 
9331 /**
9332  * i40e_verify_eeprom - make sure eeprom is good to use
9333  * @pf: board private structure
9334  **/
9335 static void i40e_verify_eeprom(struct i40e_pf *pf)
9336 {
9337 	int err;
9338 
9339 	err = i40e_diag_eeprom_test(&pf->hw);
9340 	if (err) {
9341 		/* retry in case of garbage read */
9342 		err = i40e_diag_eeprom_test(&pf->hw);
9343 		if (err) {
9344 			dev_info(&pf->pdev->dev, "eeprom check failed (%d), Tx/Rx traffic disabled\n",
9345 				 err);
9346 			set_bit(__I40E_BAD_EEPROM, pf->state);
9347 		}
9348 	}
9349 
9350 	if (!err && test_bit(__I40E_BAD_EEPROM, pf->state)) {
9351 		dev_info(&pf->pdev->dev, "eeprom check passed, Tx/Rx traffic enabled\n");
9352 		clear_bit(__I40E_BAD_EEPROM, pf->state);
9353 	}
9354 }
9355 
9356 /**
9357  * i40e_enable_pf_switch_lb
9358  * @pf: pointer to the PF structure
9359  *
9360  * enable switch loop back or die - no point in a return value
9361  **/
9362 static void i40e_enable_pf_switch_lb(struct i40e_pf *pf)
9363 {
9364 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9365 	struct i40e_vsi_context ctxt;
9366 	int ret;
9367 
9368 	ctxt.seid = pf->main_vsi_seid;
9369 	ctxt.pf_num = pf->hw.pf_id;
9370 	ctxt.vf_num = 0;
9371 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
9372 	if (ret) {
9373 		dev_info(&pf->pdev->dev,
9374 			 "couldn't get PF vsi config, err %s aq_err %s\n",
9375 			 i40e_stat_str(&pf->hw, ret),
9376 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9377 		return;
9378 	}
9379 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9380 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9381 	ctxt.info.switch_id |= cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9382 
9383 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
9384 	if (ret) {
9385 		dev_info(&pf->pdev->dev,
9386 			 "update vsi switch failed, err %s aq_err %s\n",
9387 			 i40e_stat_str(&pf->hw, ret),
9388 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9389 	}
9390 }
9391 
9392 /**
9393  * i40e_disable_pf_switch_lb
9394  * @pf: pointer to the PF structure
9395  *
9396  * disable switch loop back or die - no point in a return value
9397  **/
9398 static void i40e_disable_pf_switch_lb(struct i40e_pf *pf)
9399 {
9400 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9401 	struct i40e_vsi_context ctxt;
9402 	int ret;
9403 
9404 	ctxt.seid = pf->main_vsi_seid;
9405 	ctxt.pf_num = pf->hw.pf_id;
9406 	ctxt.vf_num = 0;
9407 	ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
9408 	if (ret) {
9409 		dev_info(&pf->pdev->dev,
9410 			 "couldn't get PF vsi config, err %s aq_err %s\n",
9411 			 i40e_stat_str(&pf->hw, ret),
9412 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9413 		return;
9414 	}
9415 	ctxt.flags = I40E_AQ_VSI_TYPE_PF;
9416 	ctxt.info.valid_sections = cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
9417 	ctxt.info.switch_id &= ~cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
9418 
9419 	ret = i40e_aq_update_vsi_params(&vsi->back->hw, &ctxt, NULL);
9420 	if (ret) {
9421 		dev_info(&pf->pdev->dev,
9422 			 "update vsi switch failed, err %s aq_err %s\n",
9423 			 i40e_stat_str(&pf->hw, ret),
9424 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9425 	}
9426 }
9427 
9428 /**
9429  * i40e_config_bridge_mode - Configure the HW bridge mode
9430  * @veb: pointer to the bridge instance
9431  *
9432  * Configure the loop back mode for the LAN VSI that is downlink to the
9433  * specified HW bridge instance. It is expected this function is called
9434  * when a new HW bridge is instantiated.
9435  **/
9436 static void i40e_config_bridge_mode(struct i40e_veb *veb)
9437 {
9438 	struct i40e_pf *pf = veb->pf;
9439 
9440 	if (pf->hw.debug_mask & I40E_DEBUG_LAN)
9441 		dev_info(&pf->pdev->dev, "enabling bridge mode: %s\n",
9442 			 veb->bridge_mode == BRIDGE_MODE_VEPA ? "VEPA" : "VEB");
9443 	if (veb->bridge_mode & BRIDGE_MODE_VEPA)
9444 		i40e_disable_pf_switch_lb(pf);
9445 	else
9446 		i40e_enable_pf_switch_lb(pf);
9447 }
9448 
9449 /**
9450  * i40e_reconstitute_veb - rebuild the VEB and anything connected to it
9451  * @veb: pointer to the VEB instance
9452  *
9453  * This is a recursive function that first builds the attached VSIs then
9454  * recurses in to build the next layer of VEB.  We track the connections
9455  * through our own index numbers because the seid's from the HW could
9456  * change across the reset.
9457  **/
9458 static int i40e_reconstitute_veb(struct i40e_veb *veb)
9459 {
9460 	struct i40e_vsi *ctl_vsi = NULL;
9461 	struct i40e_pf *pf = veb->pf;
9462 	int v, veb_idx;
9463 	int ret;
9464 
9465 	/* build VSI that owns this VEB, temporarily attached to base VEB */
9466 	for (v = 0; v < pf->num_alloc_vsi && !ctl_vsi; v++) {
9467 		if (pf->vsi[v] &&
9468 		    pf->vsi[v]->veb_idx == veb->idx &&
9469 		    pf->vsi[v]->flags & I40E_VSI_FLAG_VEB_OWNER) {
9470 			ctl_vsi = pf->vsi[v];
9471 			break;
9472 		}
9473 	}
9474 	if (!ctl_vsi) {
9475 		dev_info(&pf->pdev->dev,
9476 			 "missing owner VSI for veb_idx %d\n", veb->idx);
9477 		ret = -ENOENT;
9478 		goto end_reconstitute;
9479 	}
9480 	if (ctl_vsi != pf->vsi[pf->lan_vsi])
9481 		ctl_vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
9482 	ret = i40e_add_vsi(ctl_vsi);
9483 	if (ret) {
9484 		dev_info(&pf->pdev->dev,
9485 			 "rebuild of veb_idx %d owner VSI failed: %d\n",
9486 			 veb->idx, ret);
9487 		goto end_reconstitute;
9488 	}
9489 	i40e_vsi_reset_stats(ctl_vsi);
9490 
9491 	/* create the VEB in the switch and move the VSI onto the VEB */
9492 	ret = i40e_add_veb(veb, ctl_vsi);
9493 	if (ret)
9494 		goto end_reconstitute;
9495 
9496 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
9497 		veb->bridge_mode = BRIDGE_MODE_VEB;
9498 	else
9499 		veb->bridge_mode = BRIDGE_MODE_VEPA;
9500 	i40e_config_bridge_mode(veb);
9501 
9502 	/* create the remaining VSIs attached to this VEB */
9503 	for (v = 0; v < pf->num_alloc_vsi; v++) {
9504 		if (!pf->vsi[v] || pf->vsi[v] == ctl_vsi)
9505 			continue;
9506 
9507 		if (pf->vsi[v]->veb_idx == veb->idx) {
9508 			struct i40e_vsi *vsi = pf->vsi[v];
9509 
9510 			vsi->uplink_seid = veb->seid;
9511 			ret = i40e_add_vsi(vsi);
9512 			if (ret) {
9513 				dev_info(&pf->pdev->dev,
9514 					 "rebuild of vsi_idx %d failed: %d\n",
9515 					 v, ret);
9516 				goto end_reconstitute;
9517 			}
9518 			i40e_vsi_reset_stats(vsi);
9519 		}
9520 	}
9521 
9522 	/* create any VEBs attached to this VEB - RECURSION */
9523 	for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
9524 		if (pf->veb[veb_idx] && pf->veb[veb_idx]->veb_idx == veb->idx) {
9525 			pf->veb[veb_idx]->uplink_seid = veb->seid;
9526 			ret = i40e_reconstitute_veb(pf->veb[veb_idx]);
9527 			if (ret)
9528 				break;
9529 		}
9530 	}
9531 
9532 end_reconstitute:
9533 	return ret;
9534 }
9535 
9536 /**
9537  * i40e_get_capabilities - get info about the HW
9538  * @pf: the PF struct
9539  **/
9540 static int i40e_get_capabilities(struct i40e_pf *pf,
9541 				 enum i40e_admin_queue_opc list_type)
9542 {
9543 	struct i40e_aqc_list_capabilities_element_resp *cap_buf;
9544 	u16 data_size;
9545 	int buf_len;
9546 	int err;
9547 
9548 	buf_len = 40 * sizeof(struct i40e_aqc_list_capabilities_element_resp);
9549 	do {
9550 		cap_buf = kzalloc(buf_len, GFP_KERNEL);
9551 		if (!cap_buf)
9552 			return -ENOMEM;
9553 
9554 		/* this loads the data into the hw struct for us */
9555 		err = i40e_aq_discover_capabilities(&pf->hw, cap_buf, buf_len,
9556 						    &data_size, list_type,
9557 						    NULL);
9558 		/* data loaded, buffer no longer needed */
9559 		kfree(cap_buf);
9560 
9561 		if (pf->hw.aq.asq_last_status == I40E_AQ_RC_ENOMEM) {
9562 			/* retry with a larger buffer */
9563 			buf_len = data_size;
9564 		} else if (pf->hw.aq.asq_last_status != I40E_AQ_RC_OK) {
9565 			dev_info(&pf->pdev->dev,
9566 				 "capability discovery failed, err %s aq_err %s\n",
9567 				 i40e_stat_str(&pf->hw, err),
9568 				 i40e_aq_str(&pf->hw,
9569 					     pf->hw.aq.asq_last_status));
9570 			return -ENODEV;
9571 		}
9572 	} while (err);
9573 
9574 	if (pf->hw.debug_mask & I40E_DEBUG_USER) {
9575 		if (list_type == i40e_aqc_opc_list_func_capabilities) {
9576 			dev_info(&pf->pdev->dev,
9577 				 "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",
9578 				 pf->hw.pf_id, pf->hw.func_caps.num_vfs,
9579 				 pf->hw.func_caps.num_msix_vectors,
9580 				 pf->hw.func_caps.num_msix_vectors_vf,
9581 				 pf->hw.func_caps.fd_filters_guaranteed,
9582 				 pf->hw.func_caps.fd_filters_best_effort,
9583 				 pf->hw.func_caps.num_tx_qp,
9584 				 pf->hw.func_caps.num_vsis);
9585 		} else if (list_type == i40e_aqc_opc_list_dev_capabilities) {
9586 			dev_info(&pf->pdev->dev,
9587 				 "switch_mode=0x%04x, function_valid=0x%08x\n",
9588 				 pf->hw.dev_caps.switch_mode,
9589 				 pf->hw.dev_caps.valid_functions);
9590 			dev_info(&pf->pdev->dev,
9591 				 "SR-IOV=%d, num_vfs for all function=%u\n",
9592 				 pf->hw.dev_caps.sr_iov_1_1,
9593 				 pf->hw.dev_caps.num_vfs);
9594 			dev_info(&pf->pdev->dev,
9595 				 "num_vsis=%u, num_rx:%u, num_tx=%u\n",
9596 				 pf->hw.dev_caps.num_vsis,
9597 				 pf->hw.dev_caps.num_rx_qp,
9598 				 pf->hw.dev_caps.num_tx_qp);
9599 		}
9600 	}
9601 	if (list_type == i40e_aqc_opc_list_func_capabilities) {
9602 #define DEF_NUM_VSI (1 + (pf->hw.func_caps.fcoe ? 1 : 0) \
9603 		       + pf->hw.func_caps.num_vfs)
9604 		if (pf->hw.revision_id == 0 &&
9605 		    pf->hw.func_caps.num_vsis < DEF_NUM_VSI) {
9606 			dev_info(&pf->pdev->dev,
9607 				 "got num_vsis %d, setting num_vsis to %d\n",
9608 				 pf->hw.func_caps.num_vsis, DEF_NUM_VSI);
9609 			pf->hw.func_caps.num_vsis = DEF_NUM_VSI;
9610 		}
9611 	}
9612 	return 0;
9613 }
9614 
9615 static int i40e_vsi_clear(struct i40e_vsi *vsi);
9616 
9617 /**
9618  * i40e_fdir_sb_setup - initialize the Flow Director resources for Sideband
9619  * @pf: board private structure
9620  **/
9621 static void i40e_fdir_sb_setup(struct i40e_pf *pf)
9622 {
9623 	struct i40e_vsi *vsi;
9624 
9625 	/* quick workaround for an NVM issue that leaves a critical register
9626 	 * uninitialized
9627 	 */
9628 	if (!rd32(&pf->hw, I40E_GLQF_HKEY(0))) {
9629 		static const u32 hkey[] = {
9630 			0xe640d33f, 0xcdfe98ab, 0x73fa7161, 0x0d7a7d36,
9631 			0xeacb7d61, 0xaa4f05b6, 0x9c5c89ed, 0xfc425ddb,
9632 			0xa4654832, 0xfc7461d4, 0x8f827619, 0xf5c63c21,
9633 			0x95b3a76d};
9634 		int i;
9635 
9636 		for (i = 0; i <= I40E_GLQF_HKEY_MAX_INDEX; i++)
9637 			wr32(&pf->hw, I40E_GLQF_HKEY(i), hkey[i]);
9638 	}
9639 
9640 	if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
9641 		return;
9642 
9643 	/* find existing VSI and see if it needs configuring */
9644 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
9645 
9646 	/* create a new VSI if none exists */
9647 	if (!vsi) {
9648 		vsi = i40e_vsi_setup(pf, I40E_VSI_FDIR,
9649 				     pf->vsi[pf->lan_vsi]->seid, 0);
9650 		if (!vsi) {
9651 			dev_info(&pf->pdev->dev, "Couldn't create FDir VSI\n");
9652 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
9653 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
9654 			return;
9655 		}
9656 	}
9657 
9658 	i40e_vsi_setup_irqhandler(vsi, i40e_fdir_clean_ring);
9659 }
9660 
9661 /**
9662  * i40e_fdir_teardown - release the Flow Director resources
9663  * @pf: board private structure
9664  **/
9665 static void i40e_fdir_teardown(struct i40e_pf *pf)
9666 {
9667 	struct i40e_vsi *vsi;
9668 
9669 	i40e_fdir_filter_exit(pf);
9670 	vsi = i40e_find_vsi_by_type(pf, I40E_VSI_FDIR);
9671 	if (vsi)
9672 		i40e_vsi_release(vsi);
9673 }
9674 
9675 /**
9676  * i40e_rebuild_cloud_filters - Rebuilds cloud filters for VSIs
9677  * @vsi: PF main vsi
9678  * @seid: seid of main or channel VSIs
9679  *
9680  * Rebuilds cloud filters associated with main VSI and channel VSIs if they
9681  * existed before reset
9682  **/
9683 static int i40e_rebuild_cloud_filters(struct i40e_vsi *vsi, u16 seid)
9684 {
9685 	struct i40e_cloud_filter *cfilter;
9686 	struct i40e_pf *pf = vsi->back;
9687 	struct hlist_node *node;
9688 	i40e_status ret;
9689 
9690 	/* Add cloud filters back if they exist */
9691 	hlist_for_each_entry_safe(cfilter, node, &pf->cloud_filter_list,
9692 				  cloud_node) {
9693 		if (cfilter->seid != seid)
9694 			continue;
9695 
9696 		if (cfilter->dst_port)
9697 			ret = i40e_add_del_cloud_filter_big_buf(vsi, cfilter,
9698 								true);
9699 		else
9700 			ret = i40e_add_del_cloud_filter(vsi, cfilter, true);
9701 
9702 		if (ret) {
9703 			dev_dbg(&pf->pdev->dev,
9704 				"Failed to rebuild cloud filter, err %s aq_err %s\n",
9705 				i40e_stat_str(&pf->hw, ret),
9706 				i40e_aq_str(&pf->hw,
9707 					    pf->hw.aq.asq_last_status));
9708 			return ret;
9709 		}
9710 	}
9711 	return 0;
9712 }
9713 
9714 /**
9715  * i40e_rebuild_channels - Rebuilds channel VSIs if they existed before reset
9716  * @vsi: PF main vsi
9717  *
9718  * Rebuilds channel VSIs if they existed before reset
9719  **/
9720 static int i40e_rebuild_channels(struct i40e_vsi *vsi)
9721 {
9722 	struct i40e_channel *ch, *ch_tmp;
9723 	i40e_status ret;
9724 
9725 	if (list_empty(&vsi->ch_list))
9726 		return 0;
9727 
9728 	list_for_each_entry_safe(ch, ch_tmp, &vsi->ch_list, list) {
9729 		if (!ch->initialized)
9730 			break;
9731 		/* Proceed with creation of channel (VMDq2) VSI */
9732 		ret = i40e_add_channel(vsi->back, vsi->uplink_seid, ch);
9733 		if (ret) {
9734 			dev_info(&vsi->back->pdev->dev,
9735 				 "failed to rebuild channels using uplink_seid %u\n",
9736 				 vsi->uplink_seid);
9737 			return ret;
9738 		}
9739 		/* Reconfigure TX queues using QTX_CTL register */
9740 		ret = i40e_channel_config_tx_ring(vsi->back, vsi, ch);
9741 		if (ret) {
9742 			dev_info(&vsi->back->pdev->dev,
9743 				 "failed to configure TX rings for channel %u\n",
9744 				 ch->seid);
9745 			return ret;
9746 		}
9747 		/* update 'next_base_queue' */
9748 		vsi->next_base_queue = vsi->next_base_queue +
9749 							ch->num_queue_pairs;
9750 		if (ch->max_tx_rate) {
9751 			u64 credits = ch->max_tx_rate;
9752 
9753 			if (i40e_set_bw_limit(vsi, ch->seid,
9754 					      ch->max_tx_rate))
9755 				return -EINVAL;
9756 
9757 			do_div(credits, I40E_BW_CREDIT_DIVISOR);
9758 			dev_dbg(&vsi->back->pdev->dev,
9759 				"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
9760 				ch->max_tx_rate,
9761 				credits,
9762 				ch->seid);
9763 		}
9764 		ret = i40e_rebuild_cloud_filters(vsi, ch->seid);
9765 		if (ret) {
9766 			dev_dbg(&vsi->back->pdev->dev,
9767 				"Failed to rebuild cloud filters for channel VSI %u\n",
9768 				ch->seid);
9769 			return ret;
9770 		}
9771 	}
9772 	return 0;
9773 }
9774 
9775 /**
9776  * i40e_prep_for_reset - prep for the core to reset
9777  * @pf: board private structure
9778  * @lock_acquired: indicates whether or not the lock has been acquired
9779  * before this function was called.
9780  *
9781  * Close up the VFs and other things in prep for PF Reset.
9782   **/
9783 static void i40e_prep_for_reset(struct i40e_pf *pf, bool lock_acquired)
9784 {
9785 	struct i40e_hw *hw = &pf->hw;
9786 	i40e_status ret = 0;
9787 	u32 v;
9788 
9789 	clear_bit(__I40E_RESET_INTR_RECEIVED, pf->state);
9790 	if (test_and_set_bit(__I40E_RESET_RECOVERY_PENDING, pf->state))
9791 		return;
9792 	if (i40e_check_asq_alive(&pf->hw))
9793 		i40e_vc_notify_reset(pf);
9794 
9795 	dev_dbg(&pf->pdev->dev, "Tearing down internal switch for reset\n");
9796 
9797 	/* quiesce the VSIs and their queues that are not already DOWN */
9798 	/* pf_quiesce_all_vsi modifies netdev structures -rtnl_lock needed */
9799 	if (!lock_acquired)
9800 		rtnl_lock();
9801 	i40e_pf_quiesce_all_vsi(pf);
9802 	if (!lock_acquired)
9803 		rtnl_unlock();
9804 
9805 	for (v = 0; v < pf->num_alloc_vsi; v++) {
9806 		if (pf->vsi[v])
9807 			pf->vsi[v]->seid = 0;
9808 	}
9809 
9810 	i40e_shutdown_adminq(&pf->hw);
9811 
9812 	/* call shutdown HMC */
9813 	if (hw->hmc.hmc_obj) {
9814 		ret = i40e_shutdown_lan_hmc(hw);
9815 		if (ret)
9816 			dev_warn(&pf->pdev->dev,
9817 				 "shutdown_lan_hmc failed: %d\n", ret);
9818 	}
9819 
9820 	/* Save the current PTP time so that we can restore the time after the
9821 	 * reset completes.
9822 	 */
9823 	i40e_ptp_save_hw_time(pf);
9824 }
9825 
9826 /**
9827  * i40e_send_version - update firmware with driver version
9828  * @pf: PF struct
9829  */
9830 static void i40e_send_version(struct i40e_pf *pf)
9831 {
9832 	struct i40e_driver_version dv;
9833 
9834 	dv.major_version = DRV_VERSION_MAJOR;
9835 	dv.minor_version = DRV_VERSION_MINOR;
9836 	dv.build_version = DRV_VERSION_BUILD;
9837 	dv.subbuild_version = 0;
9838 	strlcpy(dv.driver_string, DRV_VERSION, sizeof(dv.driver_string));
9839 	i40e_aq_send_driver_version(&pf->hw, &dv, NULL);
9840 }
9841 
9842 /**
9843  * i40e_get_oem_version - get OEM specific version information
9844  * @hw: pointer to the hardware structure
9845  **/
9846 static void i40e_get_oem_version(struct i40e_hw *hw)
9847 {
9848 	u16 block_offset = 0xffff;
9849 	u16 block_length = 0;
9850 	u16 capabilities = 0;
9851 	u16 gen_snap = 0;
9852 	u16 release = 0;
9853 
9854 #define I40E_SR_NVM_OEM_VERSION_PTR		0x1B
9855 #define I40E_NVM_OEM_LENGTH_OFFSET		0x00
9856 #define I40E_NVM_OEM_CAPABILITIES_OFFSET	0x01
9857 #define I40E_NVM_OEM_GEN_OFFSET			0x02
9858 #define I40E_NVM_OEM_RELEASE_OFFSET		0x03
9859 #define I40E_NVM_OEM_CAPABILITIES_MASK		0x000F
9860 #define I40E_NVM_OEM_LENGTH			3
9861 
9862 	/* Check if pointer to OEM version block is valid. */
9863 	i40e_read_nvm_word(hw, I40E_SR_NVM_OEM_VERSION_PTR, &block_offset);
9864 	if (block_offset == 0xffff)
9865 		return;
9866 
9867 	/* Check if OEM version block has correct length. */
9868 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_LENGTH_OFFSET,
9869 			   &block_length);
9870 	if (block_length < I40E_NVM_OEM_LENGTH)
9871 		return;
9872 
9873 	/* Check if OEM version format is as expected. */
9874 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_CAPABILITIES_OFFSET,
9875 			   &capabilities);
9876 	if ((capabilities & I40E_NVM_OEM_CAPABILITIES_MASK) != 0)
9877 		return;
9878 
9879 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_GEN_OFFSET,
9880 			   &gen_snap);
9881 	i40e_read_nvm_word(hw, block_offset + I40E_NVM_OEM_RELEASE_OFFSET,
9882 			   &release);
9883 	hw->nvm.oem_ver = (gen_snap << I40E_OEM_SNAP_SHIFT) | release;
9884 	hw->nvm.eetrack = I40E_OEM_EETRACK_ID;
9885 }
9886 
9887 /**
9888  * i40e_reset - wait for core reset to finish reset, reset pf if corer not seen
9889  * @pf: board private structure
9890  **/
9891 static int i40e_reset(struct i40e_pf *pf)
9892 {
9893 	struct i40e_hw *hw = &pf->hw;
9894 	i40e_status ret;
9895 
9896 	ret = i40e_pf_reset(hw);
9897 	if (ret) {
9898 		dev_info(&pf->pdev->dev, "PF reset failed, %d\n", ret);
9899 		set_bit(__I40E_RESET_FAILED, pf->state);
9900 		clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
9901 	} else {
9902 		pf->pfr_count++;
9903 	}
9904 	return ret;
9905 }
9906 
9907 /**
9908  * i40e_rebuild - rebuild using a saved config
9909  * @pf: board private structure
9910  * @reinit: if the Main VSI needs to re-initialized.
9911  * @lock_acquired: indicates whether or not the lock has been acquired
9912  * before this function was called.
9913  **/
9914 static void i40e_rebuild(struct i40e_pf *pf, bool reinit, bool lock_acquired)
9915 {
9916 	int old_recovery_mode_bit = test_bit(__I40E_RECOVERY_MODE, pf->state);
9917 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
9918 	struct i40e_hw *hw = &pf->hw;
9919 	u8 set_fc_aq_fail = 0;
9920 	i40e_status ret;
9921 	u32 val;
9922 	int v;
9923 
9924 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
9925 	    i40e_check_recovery_mode(pf)) {
9926 		i40e_set_ethtool_ops(pf->vsi[pf->lan_vsi]->netdev);
9927 	}
9928 
9929 	if (test_bit(__I40E_DOWN, pf->state) &&
9930 	    !test_bit(__I40E_RECOVERY_MODE, pf->state) &&
9931 	    !old_recovery_mode_bit)
9932 		goto clear_recovery;
9933 	dev_dbg(&pf->pdev->dev, "Rebuilding internal switch\n");
9934 
9935 	/* rebuild the basics for the AdminQ, HMC, and initial HW switch */
9936 	ret = i40e_init_adminq(&pf->hw);
9937 	if (ret) {
9938 		dev_info(&pf->pdev->dev, "Rebuild AdminQ failed, err %s aq_err %s\n",
9939 			 i40e_stat_str(&pf->hw, ret),
9940 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
9941 		goto clear_recovery;
9942 	}
9943 	i40e_get_oem_version(&pf->hw);
9944 
9945 	if (test_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state) &&
9946 	    ((hw->aq.fw_maj_ver == 4 && hw->aq.fw_min_ver <= 33) ||
9947 	     hw->aq.fw_maj_ver < 4) && hw->mac.type == I40E_MAC_XL710) {
9948 		/* The following delay is necessary for 4.33 firmware and older
9949 		 * to recover after EMP reset. 200 ms should suffice but we
9950 		 * put here 300 ms to be sure that FW is ready to operate
9951 		 * after reset.
9952 		 */
9953 		mdelay(300);
9954 	}
9955 
9956 	/* re-verify the eeprom if we just had an EMP reset */
9957 	if (test_and_clear_bit(__I40E_EMP_RESET_INTR_RECEIVED, pf->state))
9958 		i40e_verify_eeprom(pf);
9959 
9960 	/* if we are going out of or into recovery mode we have to act
9961 	 * accordingly with regard to resources initialization
9962 	 * and deinitialization
9963 	 */
9964 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) ||
9965 	    old_recovery_mode_bit) {
9966 		if (i40e_get_capabilities(pf,
9967 					  i40e_aqc_opc_list_func_capabilities))
9968 			goto end_unlock;
9969 
9970 		if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
9971 			/* we're staying in recovery mode so we'll reinitialize
9972 			 * misc vector here
9973 			 */
9974 			if (i40e_setup_misc_vector_for_recovery_mode(pf))
9975 				goto end_unlock;
9976 		} else {
9977 			if (!lock_acquired)
9978 				rtnl_lock();
9979 			/* we're going out of recovery mode so we'll free
9980 			 * the IRQ allocated specifically for recovery mode
9981 			 * and restore the interrupt scheme
9982 			 */
9983 			free_irq(pf->pdev->irq, pf);
9984 			i40e_clear_interrupt_scheme(pf);
9985 			if (i40e_restore_interrupt_scheme(pf))
9986 				goto end_unlock;
9987 		}
9988 
9989 		/* tell the firmware that we're starting */
9990 		i40e_send_version(pf);
9991 
9992 		/* bail out in case recovery mode was detected, as there is
9993 		 * no need for further configuration.
9994 		 */
9995 		goto end_unlock;
9996 	}
9997 
9998 	i40e_clear_pxe_mode(hw);
9999 	ret = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
10000 	if (ret)
10001 		goto end_core_reset;
10002 
10003 	ret = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
10004 				hw->func_caps.num_rx_qp, 0, 0);
10005 	if (ret) {
10006 		dev_info(&pf->pdev->dev, "init_lan_hmc failed: %d\n", ret);
10007 		goto end_core_reset;
10008 	}
10009 	ret = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
10010 	if (ret) {
10011 		dev_info(&pf->pdev->dev, "configure_lan_hmc failed: %d\n", ret);
10012 		goto end_core_reset;
10013 	}
10014 
10015 	/* Enable FW to write a default DCB config on link-up */
10016 	i40e_aq_set_dcb_parameters(hw, true, NULL);
10017 
10018 #ifdef CONFIG_I40E_DCB
10019 	ret = i40e_init_pf_dcb(pf);
10020 	if (ret) {
10021 		dev_info(&pf->pdev->dev, "DCB init failed %d, disabled\n", ret);
10022 		pf->flags &= ~I40E_FLAG_DCB_CAPABLE;
10023 		/* Continue without DCB enabled */
10024 	}
10025 #endif /* CONFIG_I40E_DCB */
10026 	/* do basic switch setup */
10027 	if (!lock_acquired)
10028 		rtnl_lock();
10029 	ret = i40e_setup_pf_switch(pf, reinit);
10030 	if (ret)
10031 		goto end_unlock;
10032 
10033 	/* The driver only wants link up/down and module qualification
10034 	 * reports from firmware.  Note the negative logic.
10035 	 */
10036 	ret = i40e_aq_set_phy_int_mask(&pf->hw,
10037 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
10038 					 I40E_AQ_EVENT_MEDIA_NA |
10039 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
10040 	if (ret)
10041 		dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
10042 			 i40e_stat_str(&pf->hw, ret),
10043 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10044 
10045 	/* make sure our flow control settings are restored */
10046 	ret = i40e_set_fc(&pf->hw, &set_fc_aq_fail, true);
10047 	if (ret)
10048 		dev_dbg(&pf->pdev->dev, "setting flow control: ret = %s last_status = %s\n",
10049 			i40e_stat_str(&pf->hw, ret),
10050 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10051 
10052 	/* Rebuild the VSIs and VEBs that existed before reset.
10053 	 * They are still in our local switch element arrays, so only
10054 	 * need to rebuild the switch model in the HW.
10055 	 *
10056 	 * If there were VEBs but the reconstitution failed, we'll try
10057 	 * try to recover minimal use by getting the basic PF VSI working.
10058 	 */
10059 	if (vsi->uplink_seid != pf->mac_seid) {
10060 		dev_dbg(&pf->pdev->dev, "attempting to rebuild switch\n");
10061 		/* find the one VEB connected to the MAC, and find orphans */
10062 		for (v = 0; v < I40E_MAX_VEB; v++) {
10063 			if (!pf->veb[v])
10064 				continue;
10065 
10066 			if (pf->veb[v]->uplink_seid == pf->mac_seid ||
10067 			    pf->veb[v]->uplink_seid == 0) {
10068 				ret = i40e_reconstitute_veb(pf->veb[v]);
10069 
10070 				if (!ret)
10071 					continue;
10072 
10073 				/* If Main VEB failed, we're in deep doodoo,
10074 				 * so give up rebuilding the switch and set up
10075 				 * for minimal rebuild of PF VSI.
10076 				 * If orphan failed, we'll report the error
10077 				 * but try to keep going.
10078 				 */
10079 				if (pf->veb[v]->uplink_seid == pf->mac_seid) {
10080 					dev_info(&pf->pdev->dev,
10081 						 "rebuild of switch failed: %d, will try to set up simple PF connection\n",
10082 						 ret);
10083 					vsi->uplink_seid = pf->mac_seid;
10084 					break;
10085 				} else if (pf->veb[v]->uplink_seid == 0) {
10086 					dev_info(&pf->pdev->dev,
10087 						 "rebuild of orphan VEB failed: %d\n",
10088 						 ret);
10089 				}
10090 			}
10091 		}
10092 	}
10093 
10094 	if (vsi->uplink_seid == pf->mac_seid) {
10095 		dev_dbg(&pf->pdev->dev, "attempting to rebuild PF VSI\n");
10096 		/* no VEB, so rebuild only the Main VSI */
10097 		ret = i40e_add_vsi(vsi);
10098 		if (ret) {
10099 			dev_info(&pf->pdev->dev,
10100 				 "rebuild of Main VSI failed: %d\n", ret);
10101 			goto end_unlock;
10102 		}
10103 	}
10104 
10105 	if (vsi->mqprio_qopt.max_rate[0]) {
10106 		u64 max_tx_rate = vsi->mqprio_qopt.max_rate[0];
10107 		u64 credits = 0;
10108 
10109 		do_div(max_tx_rate, I40E_BW_MBPS_DIVISOR);
10110 		ret = i40e_set_bw_limit(vsi, vsi->seid, max_tx_rate);
10111 		if (ret)
10112 			goto end_unlock;
10113 
10114 		credits = max_tx_rate;
10115 		do_div(credits, I40E_BW_CREDIT_DIVISOR);
10116 		dev_dbg(&vsi->back->pdev->dev,
10117 			"Set tx rate of %llu Mbps (count of 50Mbps %llu) for vsi->seid %u\n",
10118 			max_tx_rate,
10119 			credits,
10120 			vsi->seid);
10121 	}
10122 
10123 	ret = i40e_rebuild_cloud_filters(vsi, vsi->seid);
10124 	if (ret)
10125 		goto end_unlock;
10126 
10127 	/* PF Main VSI is rebuild by now, go ahead and rebuild channel VSIs
10128 	 * for this main VSI if they exist
10129 	 */
10130 	ret = i40e_rebuild_channels(vsi);
10131 	if (ret)
10132 		goto end_unlock;
10133 
10134 	/* Reconfigure hardware for allowing smaller MSS in the case
10135 	 * of TSO, so that we avoid the MDD being fired and causing
10136 	 * a reset in the case of small MSS+TSO.
10137 	 */
10138 #define I40E_REG_MSS          0x000E64DC
10139 #define I40E_REG_MSS_MIN_MASK 0x3FF0000
10140 #define I40E_64BYTE_MSS       0x400000
10141 	val = rd32(hw, I40E_REG_MSS);
10142 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
10143 		val &= ~I40E_REG_MSS_MIN_MASK;
10144 		val |= I40E_64BYTE_MSS;
10145 		wr32(hw, I40E_REG_MSS, val);
10146 	}
10147 
10148 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
10149 		msleep(75);
10150 		ret = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
10151 		if (ret)
10152 			dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
10153 				 i40e_stat_str(&pf->hw, ret),
10154 				 i40e_aq_str(&pf->hw,
10155 					     pf->hw.aq.asq_last_status));
10156 	}
10157 	/* reinit the misc interrupt */
10158 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
10159 		ret = i40e_setup_misc_vector(pf);
10160 
10161 	/* Add a filter to drop all Flow control frames from any VSI from being
10162 	 * transmitted. By doing so we stop a malicious VF from sending out
10163 	 * PAUSE or PFC frames and potentially controlling traffic for other
10164 	 * PF/VF VSIs.
10165 	 * The FW can still send Flow control frames if enabled.
10166 	 */
10167 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
10168 						       pf->main_vsi_seid);
10169 
10170 	/* restart the VSIs that were rebuilt and running before the reset */
10171 	i40e_pf_unquiesce_all_vsi(pf);
10172 
10173 	/* Release the RTNL lock before we start resetting VFs */
10174 	if (!lock_acquired)
10175 		rtnl_unlock();
10176 
10177 	/* Restore promiscuous settings */
10178 	ret = i40e_set_promiscuous(pf, pf->cur_promisc);
10179 	if (ret)
10180 		dev_warn(&pf->pdev->dev,
10181 			 "Failed to restore promiscuous setting: %s, err %s aq_err %s\n",
10182 			 pf->cur_promisc ? "on" : "off",
10183 			 i40e_stat_str(&pf->hw, ret),
10184 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
10185 
10186 	i40e_reset_all_vfs(pf, true);
10187 
10188 	/* tell the firmware that we're starting */
10189 	i40e_send_version(pf);
10190 
10191 	/* We've already released the lock, so don't do it again */
10192 	goto end_core_reset;
10193 
10194 end_unlock:
10195 	if (!lock_acquired)
10196 		rtnl_unlock();
10197 end_core_reset:
10198 	clear_bit(__I40E_RESET_FAILED, pf->state);
10199 clear_recovery:
10200 	clear_bit(__I40E_RESET_RECOVERY_PENDING, pf->state);
10201 	clear_bit(__I40E_TIMEOUT_RECOVERY_PENDING, pf->state);
10202 }
10203 
10204 /**
10205  * i40e_reset_and_rebuild - reset and rebuild using a saved config
10206  * @pf: board private structure
10207  * @reinit: if the Main VSI needs to re-initialized.
10208  * @lock_acquired: indicates whether or not the lock has been acquired
10209  * before this function was called.
10210  **/
10211 static void i40e_reset_and_rebuild(struct i40e_pf *pf, bool reinit,
10212 				   bool lock_acquired)
10213 {
10214 	int ret;
10215 	/* Now we wait for GRST to settle out.
10216 	 * We don't have to delete the VEBs or VSIs from the hw switch
10217 	 * because the reset will make them disappear.
10218 	 */
10219 	ret = i40e_reset(pf);
10220 	if (!ret)
10221 		i40e_rebuild(pf, reinit, lock_acquired);
10222 }
10223 
10224 /**
10225  * i40e_handle_reset_warning - prep for the PF to reset, reset and rebuild
10226  * @pf: board private structure
10227  *
10228  * Close up the VFs and other things in prep for a Core Reset,
10229  * then get ready to rebuild the world.
10230  * @lock_acquired: indicates whether or not the lock has been acquired
10231  * before this function was called.
10232  **/
10233 static void i40e_handle_reset_warning(struct i40e_pf *pf, bool lock_acquired)
10234 {
10235 	i40e_prep_for_reset(pf, lock_acquired);
10236 	i40e_reset_and_rebuild(pf, false, lock_acquired);
10237 }
10238 
10239 /**
10240  * i40e_handle_mdd_event
10241  * @pf: pointer to the PF structure
10242  *
10243  * Called from the MDD irq handler to identify possibly malicious vfs
10244  **/
10245 static void i40e_handle_mdd_event(struct i40e_pf *pf)
10246 {
10247 	struct i40e_hw *hw = &pf->hw;
10248 	bool mdd_detected = false;
10249 	struct i40e_vf *vf;
10250 	u32 reg;
10251 	int i;
10252 
10253 	if (!test_bit(__I40E_MDD_EVENT_PENDING, pf->state))
10254 		return;
10255 
10256 	/* find what triggered the MDD event */
10257 	reg = rd32(hw, I40E_GL_MDET_TX);
10258 	if (reg & I40E_GL_MDET_TX_VALID_MASK) {
10259 		u8 pf_num = (reg & I40E_GL_MDET_TX_PF_NUM_MASK) >>
10260 				I40E_GL_MDET_TX_PF_NUM_SHIFT;
10261 		u16 vf_num = (reg & I40E_GL_MDET_TX_VF_NUM_MASK) >>
10262 				I40E_GL_MDET_TX_VF_NUM_SHIFT;
10263 		u8 event = (reg & I40E_GL_MDET_TX_EVENT_MASK) >>
10264 				I40E_GL_MDET_TX_EVENT_SHIFT;
10265 		u16 queue = ((reg & I40E_GL_MDET_TX_QUEUE_MASK) >>
10266 				I40E_GL_MDET_TX_QUEUE_SHIFT) -
10267 				pf->hw.func_caps.base_queue;
10268 		if (netif_msg_tx_err(pf))
10269 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on TX queue %d PF number 0x%02x VF number 0x%02x\n",
10270 				 event, queue, pf_num, vf_num);
10271 		wr32(hw, I40E_GL_MDET_TX, 0xffffffff);
10272 		mdd_detected = true;
10273 	}
10274 	reg = rd32(hw, I40E_GL_MDET_RX);
10275 	if (reg & I40E_GL_MDET_RX_VALID_MASK) {
10276 		u8 func = (reg & I40E_GL_MDET_RX_FUNCTION_MASK) >>
10277 				I40E_GL_MDET_RX_FUNCTION_SHIFT;
10278 		u8 event = (reg & I40E_GL_MDET_RX_EVENT_MASK) >>
10279 				I40E_GL_MDET_RX_EVENT_SHIFT;
10280 		u16 queue = ((reg & I40E_GL_MDET_RX_QUEUE_MASK) >>
10281 				I40E_GL_MDET_RX_QUEUE_SHIFT) -
10282 				pf->hw.func_caps.base_queue;
10283 		if (netif_msg_rx_err(pf))
10284 			dev_info(&pf->pdev->dev, "Malicious Driver Detection event 0x%02x on RX queue %d of function 0x%02x\n",
10285 				 event, queue, func);
10286 		wr32(hw, I40E_GL_MDET_RX, 0xffffffff);
10287 		mdd_detected = true;
10288 	}
10289 
10290 	if (mdd_detected) {
10291 		reg = rd32(hw, I40E_PF_MDET_TX);
10292 		if (reg & I40E_PF_MDET_TX_VALID_MASK) {
10293 			wr32(hw, I40E_PF_MDET_TX, 0xFFFF);
10294 			dev_dbg(&pf->pdev->dev, "TX driver issue detected on PF\n");
10295 		}
10296 		reg = rd32(hw, I40E_PF_MDET_RX);
10297 		if (reg & I40E_PF_MDET_RX_VALID_MASK) {
10298 			wr32(hw, I40E_PF_MDET_RX, 0xFFFF);
10299 			dev_dbg(&pf->pdev->dev, "RX driver issue detected on PF\n");
10300 		}
10301 	}
10302 
10303 	/* see if one of the VFs needs its hand slapped */
10304 	for (i = 0; i < pf->num_alloc_vfs && mdd_detected; i++) {
10305 		vf = &(pf->vf[i]);
10306 		reg = rd32(hw, I40E_VP_MDET_TX(i));
10307 		if (reg & I40E_VP_MDET_TX_VALID_MASK) {
10308 			wr32(hw, I40E_VP_MDET_TX(i), 0xFFFF);
10309 			vf->num_mdd_events++;
10310 			dev_info(&pf->pdev->dev, "TX driver issue detected on VF %d\n",
10311 				 i);
10312 			dev_info(&pf->pdev->dev,
10313 				 "Use PF Control I/F to re-enable the VF\n");
10314 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
10315 		}
10316 
10317 		reg = rd32(hw, I40E_VP_MDET_RX(i));
10318 		if (reg & I40E_VP_MDET_RX_VALID_MASK) {
10319 			wr32(hw, I40E_VP_MDET_RX(i), 0xFFFF);
10320 			vf->num_mdd_events++;
10321 			dev_info(&pf->pdev->dev, "RX driver issue detected on VF %d\n",
10322 				 i);
10323 			dev_info(&pf->pdev->dev,
10324 				 "Use PF Control I/F to re-enable the VF\n");
10325 			set_bit(I40E_VF_STATE_DISABLED, &vf->vf_states);
10326 		}
10327 	}
10328 
10329 	/* re-enable mdd interrupt cause */
10330 	clear_bit(__I40E_MDD_EVENT_PENDING, pf->state);
10331 	reg = rd32(hw, I40E_PFINT_ICR0_ENA);
10332 	reg |=  I40E_PFINT_ICR0_ENA_MAL_DETECT_MASK;
10333 	wr32(hw, I40E_PFINT_ICR0_ENA, reg);
10334 	i40e_flush(hw);
10335 }
10336 
10337 static const char *i40e_tunnel_name(u8 type)
10338 {
10339 	switch (type) {
10340 	case UDP_TUNNEL_TYPE_VXLAN:
10341 		return "vxlan";
10342 	case UDP_TUNNEL_TYPE_GENEVE:
10343 		return "geneve";
10344 	default:
10345 		return "unknown";
10346 	}
10347 }
10348 
10349 /**
10350  * i40e_sync_udp_filters - Trigger a sync event for existing UDP filters
10351  * @pf: board private structure
10352  **/
10353 static void i40e_sync_udp_filters(struct i40e_pf *pf)
10354 {
10355 	int i;
10356 
10357 	/* loop through and set pending bit for all active UDP filters */
10358 	for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
10359 		if (pf->udp_ports[i].port)
10360 			pf->pending_udp_bitmap |= BIT_ULL(i);
10361 	}
10362 
10363 	set_bit(__I40E_UDP_FILTER_SYNC_PENDING, pf->state);
10364 }
10365 
10366 /**
10367  * i40e_sync_udp_filters_subtask - Sync the VSI filter list with HW
10368  * @pf: board private structure
10369  **/
10370 static void i40e_sync_udp_filters_subtask(struct i40e_pf *pf)
10371 {
10372 	struct i40e_hw *hw = &pf->hw;
10373 	u8 filter_index, type;
10374 	u16 port;
10375 	int i;
10376 
10377 	if (!test_and_clear_bit(__I40E_UDP_FILTER_SYNC_PENDING, pf->state))
10378 		return;
10379 
10380 	/* acquire RTNL to maintain state of flags and port requests */
10381 	rtnl_lock();
10382 
10383 	for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
10384 		if (pf->pending_udp_bitmap & BIT_ULL(i)) {
10385 			struct i40e_udp_port_config *udp_port;
10386 			i40e_status ret = 0;
10387 
10388 			udp_port = &pf->udp_ports[i];
10389 			pf->pending_udp_bitmap &= ~BIT_ULL(i);
10390 
10391 			port = READ_ONCE(udp_port->port);
10392 			type = READ_ONCE(udp_port->type);
10393 			filter_index = READ_ONCE(udp_port->filter_index);
10394 
10395 			/* release RTNL while we wait on AQ command */
10396 			rtnl_unlock();
10397 
10398 			if (port)
10399 				ret = i40e_aq_add_udp_tunnel(hw, port,
10400 							     type,
10401 							     &filter_index,
10402 							     NULL);
10403 			else if (filter_index != I40E_UDP_PORT_INDEX_UNUSED)
10404 				ret = i40e_aq_del_udp_tunnel(hw, filter_index,
10405 							     NULL);
10406 
10407 			/* reacquire RTNL so we can update filter_index */
10408 			rtnl_lock();
10409 
10410 			if (ret) {
10411 				dev_info(&pf->pdev->dev,
10412 					 "%s %s port %d, index %d failed, err %s aq_err %s\n",
10413 					 i40e_tunnel_name(type),
10414 					 port ? "add" : "delete",
10415 					 port,
10416 					 filter_index,
10417 					 i40e_stat_str(&pf->hw, ret),
10418 					 i40e_aq_str(&pf->hw,
10419 						     pf->hw.aq.asq_last_status));
10420 				if (port) {
10421 					/* failed to add, just reset port,
10422 					 * drop pending bit for any deletion
10423 					 */
10424 					udp_port->port = 0;
10425 					pf->pending_udp_bitmap &= ~BIT_ULL(i);
10426 				}
10427 			} else if (port) {
10428 				/* record filter index on success */
10429 				udp_port->filter_index = filter_index;
10430 			}
10431 		}
10432 	}
10433 
10434 	rtnl_unlock();
10435 }
10436 
10437 /**
10438  * i40e_service_task - Run the driver's async subtasks
10439  * @work: pointer to work_struct containing our data
10440  **/
10441 static void i40e_service_task(struct work_struct *work)
10442 {
10443 	struct i40e_pf *pf = container_of(work,
10444 					  struct i40e_pf,
10445 					  service_task);
10446 	unsigned long start_time = jiffies;
10447 
10448 	/* don't bother with service tasks if a reset is in progress */
10449 	if (test_bit(__I40E_RESET_RECOVERY_PENDING, pf->state) ||
10450 	    test_bit(__I40E_SUSPENDED, pf->state))
10451 		return;
10452 
10453 	if (test_and_set_bit(__I40E_SERVICE_SCHED, pf->state))
10454 		return;
10455 
10456 	if (!test_bit(__I40E_RECOVERY_MODE, pf->state)) {
10457 		i40e_detect_recover_hung(pf->vsi[pf->lan_vsi]);
10458 		i40e_sync_filters_subtask(pf);
10459 		i40e_reset_subtask(pf);
10460 		i40e_handle_mdd_event(pf);
10461 		i40e_vc_process_vflr_event(pf);
10462 		i40e_watchdog_subtask(pf);
10463 		i40e_fdir_reinit_subtask(pf);
10464 		if (test_and_clear_bit(__I40E_CLIENT_RESET, pf->state)) {
10465 			/* Client subtask will reopen next time through. */
10466 			i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi],
10467 							   true);
10468 		} else {
10469 			i40e_client_subtask(pf);
10470 			if (test_and_clear_bit(__I40E_CLIENT_L2_CHANGE,
10471 					       pf->state))
10472 				i40e_notify_client_of_l2_param_changes(
10473 								pf->vsi[pf->lan_vsi]);
10474 		}
10475 		i40e_sync_filters_subtask(pf);
10476 		i40e_sync_udp_filters_subtask(pf);
10477 	} else {
10478 		i40e_reset_subtask(pf);
10479 	}
10480 
10481 	i40e_clean_adminq_subtask(pf);
10482 
10483 	/* flush memory to make sure state is correct before next watchdog */
10484 	smp_mb__before_atomic();
10485 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
10486 
10487 	/* If the tasks have taken longer than one timer cycle or there
10488 	 * is more work to be done, reschedule the service task now
10489 	 * rather than wait for the timer to tick again.
10490 	 */
10491 	if (time_after(jiffies, (start_time + pf->service_timer_period)) ||
10492 	    test_bit(__I40E_ADMINQ_EVENT_PENDING, pf->state)		 ||
10493 	    test_bit(__I40E_MDD_EVENT_PENDING, pf->state)		 ||
10494 	    test_bit(__I40E_VFLR_EVENT_PENDING, pf->state))
10495 		i40e_service_event_schedule(pf);
10496 }
10497 
10498 /**
10499  * i40e_service_timer - timer callback
10500  * @data: pointer to PF struct
10501  **/
10502 static void i40e_service_timer(struct timer_list *t)
10503 {
10504 	struct i40e_pf *pf = from_timer(pf, t, service_timer);
10505 
10506 	mod_timer(&pf->service_timer,
10507 		  round_jiffies(jiffies + pf->service_timer_period));
10508 	i40e_service_event_schedule(pf);
10509 }
10510 
10511 /**
10512  * i40e_set_num_rings_in_vsi - Determine number of rings in the VSI
10513  * @vsi: the VSI being configured
10514  **/
10515 static int i40e_set_num_rings_in_vsi(struct i40e_vsi *vsi)
10516 {
10517 	struct i40e_pf *pf = vsi->back;
10518 
10519 	switch (vsi->type) {
10520 	case I40E_VSI_MAIN:
10521 		vsi->alloc_queue_pairs = pf->num_lan_qps;
10522 		if (!vsi->num_tx_desc)
10523 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10524 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
10525 		if (!vsi->num_rx_desc)
10526 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10527 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
10528 		if (pf->flags & I40E_FLAG_MSIX_ENABLED)
10529 			vsi->num_q_vectors = pf->num_lan_msix;
10530 		else
10531 			vsi->num_q_vectors = 1;
10532 
10533 		break;
10534 
10535 	case I40E_VSI_FDIR:
10536 		vsi->alloc_queue_pairs = 1;
10537 		vsi->num_tx_desc = ALIGN(I40E_FDIR_RING_COUNT,
10538 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
10539 		vsi->num_rx_desc = ALIGN(I40E_FDIR_RING_COUNT,
10540 					 I40E_REQ_DESCRIPTOR_MULTIPLE);
10541 		vsi->num_q_vectors = pf->num_fdsb_msix;
10542 		break;
10543 
10544 	case I40E_VSI_VMDQ2:
10545 		vsi->alloc_queue_pairs = pf->num_vmdq_qps;
10546 		if (!vsi->num_tx_desc)
10547 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10548 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
10549 		if (!vsi->num_rx_desc)
10550 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10551 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
10552 		vsi->num_q_vectors = pf->num_vmdq_msix;
10553 		break;
10554 
10555 	case I40E_VSI_SRIOV:
10556 		vsi->alloc_queue_pairs = pf->num_vf_qps;
10557 		if (!vsi->num_tx_desc)
10558 			vsi->num_tx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10559 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
10560 		if (!vsi->num_rx_desc)
10561 			vsi->num_rx_desc = ALIGN(I40E_DEFAULT_NUM_DESCRIPTORS,
10562 						 I40E_REQ_DESCRIPTOR_MULTIPLE);
10563 		break;
10564 
10565 	default:
10566 		WARN_ON(1);
10567 		return -ENODATA;
10568 	}
10569 
10570 	return 0;
10571 }
10572 
10573 /**
10574  * i40e_vsi_alloc_arrays - Allocate queue and vector pointer arrays for the vsi
10575  * @vsi: VSI pointer
10576  * @alloc_qvectors: a bool to specify if q_vectors need to be allocated.
10577  *
10578  * On error: returns error code (negative)
10579  * On success: returns 0
10580  **/
10581 static int i40e_vsi_alloc_arrays(struct i40e_vsi *vsi, bool alloc_qvectors)
10582 {
10583 	struct i40e_ring **next_rings;
10584 	int size;
10585 	int ret = 0;
10586 
10587 	/* allocate memory for both Tx, XDP Tx and Rx ring pointers */
10588 	size = sizeof(struct i40e_ring *) * vsi->alloc_queue_pairs *
10589 	       (i40e_enabled_xdp_vsi(vsi) ? 3 : 2);
10590 	vsi->tx_rings = kzalloc(size, GFP_KERNEL);
10591 	if (!vsi->tx_rings)
10592 		return -ENOMEM;
10593 	next_rings = vsi->tx_rings + vsi->alloc_queue_pairs;
10594 	if (i40e_enabled_xdp_vsi(vsi)) {
10595 		vsi->xdp_rings = next_rings;
10596 		next_rings += vsi->alloc_queue_pairs;
10597 	}
10598 	vsi->rx_rings = next_rings;
10599 
10600 	if (alloc_qvectors) {
10601 		/* allocate memory for q_vector pointers */
10602 		size = sizeof(struct i40e_q_vector *) * vsi->num_q_vectors;
10603 		vsi->q_vectors = kzalloc(size, GFP_KERNEL);
10604 		if (!vsi->q_vectors) {
10605 			ret = -ENOMEM;
10606 			goto err_vectors;
10607 		}
10608 	}
10609 	return ret;
10610 
10611 err_vectors:
10612 	kfree(vsi->tx_rings);
10613 	return ret;
10614 }
10615 
10616 /**
10617  * i40e_vsi_mem_alloc - Allocates the next available struct vsi in the PF
10618  * @pf: board private structure
10619  * @type: type of VSI
10620  *
10621  * On error: returns error code (negative)
10622  * On success: returns vsi index in PF (positive)
10623  **/
10624 static int i40e_vsi_mem_alloc(struct i40e_pf *pf, enum i40e_vsi_type type)
10625 {
10626 	int ret = -ENODEV;
10627 	struct i40e_vsi *vsi;
10628 	int vsi_idx;
10629 	int i;
10630 
10631 	/* Need to protect the allocation of the VSIs at the PF level */
10632 	mutex_lock(&pf->switch_mutex);
10633 
10634 	/* VSI list may be fragmented if VSI creation/destruction has
10635 	 * been happening.  We can afford to do a quick scan to look
10636 	 * for any free VSIs in the list.
10637 	 *
10638 	 * find next empty vsi slot, looping back around if necessary
10639 	 */
10640 	i = pf->next_vsi;
10641 	while (i < pf->num_alloc_vsi && pf->vsi[i])
10642 		i++;
10643 	if (i >= pf->num_alloc_vsi) {
10644 		i = 0;
10645 		while (i < pf->next_vsi && pf->vsi[i])
10646 			i++;
10647 	}
10648 
10649 	if (i < pf->num_alloc_vsi && !pf->vsi[i]) {
10650 		vsi_idx = i;             /* Found one! */
10651 	} else {
10652 		ret = -ENODEV;
10653 		goto unlock_pf;  /* out of VSI slots! */
10654 	}
10655 	pf->next_vsi = ++i;
10656 
10657 	vsi = kzalloc(sizeof(*vsi), GFP_KERNEL);
10658 	if (!vsi) {
10659 		ret = -ENOMEM;
10660 		goto unlock_pf;
10661 	}
10662 	vsi->type = type;
10663 	vsi->back = pf;
10664 	set_bit(__I40E_VSI_DOWN, vsi->state);
10665 	vsi->flags = 0;
10666 	vsi->idx = vsi_idx;
10667 	vsi->int_rate_limit = 0;
10668 	vsi->rss_table_size = (vsi->type == I40E_VSI_MAIN) ?
10669 				pf->rss_table_size : 64;
10670 	vsi->netdev_registered = false;
10671 	vsi->work_limit = I40E_DEFAULT_IRQ_WORK;
10672 	hash_init(vsi->mac_filter_hash);
10673 	vsi->irqs_ready = false;
10674 
10675 	if (type == I40E_VSI_MAIN) {
10676 		vsi->af_xdp_zc_qps = bitmap_zalloc(pf->num_lan_qps, GFP_KERNEL);
10677 		if (!vsi->af_xdp_zc_qps)
10678 			goto err_rings;
10679 	}
10680 
10681 	ret = i40e_set_num_rings_in_vsi(vsi);
10682 	if (ret)
10683 		goto err_rings;
10684 
10685 	ret = i40e_vsi_alloc_arrays(vsi, true);
10686 	if (ret)
10687 		goto err_rings;
10688 
10689 	/* Setup default MSIX irq handler for VSI */
10690 	i40e_vsi_setup_irqhandler(vsi, i40e_msix_clean_rings);
10691 
10692 	/* Initialize VSI lock */
10693 	spin_lock_init(&vsi->mac_filter_hash_lock);
10694 	pf->vsi[vsi_idx] = vsi;
10695 	ret = vsi_idx;
10696 	goto unlock_pf;
10697 
10698 err_rings:
10699 	bitmap_free(vsi->af_xdp_zc_qps);
10700 	pf->next_vsi = i - 1;
10701 	kfree(vsi);
10702 unlock_pf:
10703 	mutex_unlock(&pf->switch_mutex);
10704 	return ret;
10705 }
10706 
10707 /**
10708  * i40e_vsi_free_arrays - Free queue and vector pointer arrays for the VSI
10709  * @vsi: VSI pointer
10710  * @free_qvectors: a bool to specify if q_vectors need to be freed.
10711  *
10712  * On error: returns error code (negative)
10713  * On success: returns 0
10714  **/
10715 static void i40e_vsi_free_arrays(struct i40e_vsi *vsi, bool free_qvectors)
10716 {
10717 	/* free the ring and vector containers */
10718 	if (free_qvectors) {
10719 		kfree(vsi->q_vectors);
10720 		vsi->q_vectors = NULL;
10721 	}
10722 	kfree(vsi->tx_rings);
10723 	vsi->tx_rings = NULL;
10724 	vsi->rx_rings = NULL;
10725 	vsi->xdp_rings = NULL;
10726 }
10727 
10728 /**
10729  * i40e_clear_rss_config_user - clear the user configured RSS hash keys
10730  * and lookup table
10731  * @vsi: Pointer to VSI structure
10732  */
10733 static void i40e_clear_rss_config_user(struct i40e_vsi *vsi)
10734 {
10735 	if (!vsi)
10736 		return;
10737 
10738 	kfree(vsi->rss_hkey_user);
10739 	vsi->rss_hkey_user = NULL;
10740 
10741 	kfree(vsi->rss_lut_user);
10742 	vsi->rss_lut_user = NULL;
10743 }
10744 
10745 /**
10746  * i40e_vsi_clear - Deallocate the VSI provided
10747  * @vsi: the VSI being un-configured
10748  **/
10749 static int i40e_vsi_clear(struct i40e_vsi *vsi)
10750 {
10751 	struct i40e_pf *pf;
10752 
10753 	if (!vsi)
10754 		return 0;
10755 
10756 	if (!vsi->back)
10757 		goto free_vsi;
10758 	pf = vsi->back;
10759 
10760 	mutex_lock(&pf->switch_mutex);
10761 	if (!pf->vsi[vsi->idx]) {
10762 		dev_err(&pf->pdev->dev, "pf->vsi[%d] is NULL, just free vsi[%d](type %d)\n",
10763 			vsi->idx, vsi->idx, vsi->type);
10764 		goto unlock_vsi;
10765 	}
10766 
10767 	if (pf->vsi[vsi->idx] != vsi) {
10768 		dev_err(&pf->pdev->dev,
10769 			"pf->vsi[%d](type %d) != vsi[%d](type %d): no free!\n",
10770 			pf->vsi[vsi->idx]->idx,
10771 			pf->vsi[vsi->idx]->type,
10772 			vsi->idx, vsi->type);
10773 		goto unlock_vsi;
10774 	}
10775 
10776 	/* updates the PF for this cleared vsi */
10777 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
10778 	i40e_put_lump(pf->irq_pile, vsi->base_vector, vsi->idx);
10779 
10780 	bitmap_free(vsi->af_xdp_zc_qps);
10781 	i40e_vsi_free_arrays(vsi, true);
10782 	i40e_clear_rss_config_user(vsi);
10783 
10784 	pf->vsi[vsi->idx] = NULL;
10785 	if (vsi->idx < pf->next_vsi)
10786 		pf->next_vsi = vsi->idx;
10787 
10788 unlock_vsi:
10789 	mutex_unlock(&pf->switch_mutex);
10790 free_vsi:
10791 	kfree(vsi);
10792 
10793 	return 0;
10794 }
10795 
10796 /**
10797  * i40e_vsi_clear_rings - Deallocates the Rx and Tx rings for the provided VSI
10798  * @vsi: the VSI being cleaned
10799  **/
10800 static void i40e_vsi_clear_rings(struct i40e_vsi *vsi)
10801 {
10802 	int i;
10803 
10804 	if (vsi->tx_rings && vsi->tx_rings[0]) {
10805 		for (i = 0; i < vsi->alloc_queue_pairs; i++) {
10806 			kfree_rcu(vsi->tx_rings[i], rcu);
10807 			vsi->tx_rings[i] = NULL;
10808 			vsi->rx_rings[i] = NULL;
10809 			if (vsi->xdp_rings)
10810 				vsi->xdp_rings[i] = NULL;
10811 		}
10812 	}
10813 }
10814 
10815 /**
10816  * i40e_alloc_rings - Allocates the Rx and Tx rings for the provided VSI
10817  * @vsi: the VSI being configured
10818  **/
10819 static int i40e_alloc_rings(struct i40e_vsi *vsi)
10820 {
10821 	int i, qpv = i40e_enabled_xdp_vsi(vsi) ? 3 : 2;
10822 	struct i40e_pf *pf = vsi->back;
10823 	struct i40e_ring *ring;
10824 
10825 	/* Set basic values in the rings to be used later during open() */
10826 	for (i = 0; i < vsi->alloc_queue_pairs; i++) {
10827 		/* allocate space for both Tx and Rx in one shot */
10828 		ring = kcalloc(qpv, sizeof(struct i40e_ring), GFP_KERNEL);
10829 		if (!ring)
10830 			goto err_out;
10831 
10832 		ring->queue_index = i;
10833 		ring->reg_idx = vsi->base_queue + i;
10834 		ring->ring_active = false;
10835 		ring->vsi = vsi;
10836 		ring->netdev = vsi->netdev;
10837 		ring->dev = &pf->pdev->dev;
10838 		ring->count = vsi->num_tx_desc;
10839 		ring->size = 0;
10840 		ring->dcb_tc = 0;
10841 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
10842 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
10843 		ring->itr_setting = pf->tx_itr_default;
10844 		vsi->tx_rings[i] = ring++;
10845 
10846 		if (!i40e_enabled_xdp_vsi(vsi))
10847 			goto setup_rx;
10848 
10849 		ring->queue_index = vsi->alloc_queue_pairs + i;
10850 		ring->reg_idx = vsi->base_queue + ring->queue_index;
10851 		ring->ring_active = false;
10852 		ring->vsi = vsi;
10853 		ring->netdev = NULL;
10854 		ring->dev = &pf->pdev->dev;
10855 		ring->count = vsi->num_tx_desc;
10856 		ring->size = 0;
10857 		ring->dcb_tc = 0;
10858 		if (vsi->back->hw_features & I40E_HW_WB_ON_ITR_CAPABLE)
10859 			ring->flags = I40E_TXR_FLAGS_WB_ON_ITR;
10860 		set_ring_xdp(ring);
10861 		ring->itr_setting = pf->tx_itr_default;
10862 		vsi->xdp_rings[i] = ring++;
10863 
10864 setup_rx:
10865 		ring->queue_index = i;
10866 		ring->reg_idx = vsi->base_queue + i;
10867 		ring->ring_active = false;
10868 		ring->vsi = vsi;
10869 		ring->netdev = vsi->netdev;
10870 		ring->dev = &pf->pdev->dev;
10871 		ring->count = vsi->num_rx_desc;
10872 		ring->size = 0;
10873 		ring->dcb_tc = 0;
10874 		ring->itr_setting = pf->rx_itr_default;
10875 		vsi->rx_rings[i] = ring;
10876 	}
10877 
10878 	return 0;
10879 
10880 err_out:
10881 	i40e_vsi_clear_rings(vsi);
10882 	return -ENOMEM;
10883 }
10884 
10885 /**
10886  * i40e_reserve_msix_vectors - Reserve MSI-X vectors in the kernel
10887  * @pf: board private structure
10888  * @vectors: the number of MSI-X vectors to request
10889  *
10890  * Returns the number of vectors reserved, or error
10891  **/
10892 static int i40e_reserve_msix_vectors(struct i40e_pf *pf, int vectors)
10893 {
10894 	vectors = pci_enable_msix_range(pf->pdev, pf->msix_entries,
10895 					I40E_MIN_MSIX, vectors);
10896 	if (vectors < 0) {
10897 		dev_info(&pf->pdev->dev,
10898 			 "MSI-X vector reservation failed: %d\n", vectors);
10899 		vectors = 0;
10900 	}
10901 
10902 	return vectors;
10903 }
10904 
10905 /**
10906  * i40e_init_msix - Setup the MSIX capability
10907  * @pf: board private structure
10908  *
10909  * Work with the OS to set up the MSIX vectors needed.
10910  *
10911  * Returns the number of vectors reserved or negative on failure
10912  **/
10913 static int i40e_init_msix(struct i40e_pf *pf)
10914 {
10915 	struct i40e_hw *hw = &pf->hw;
10916 	int cpus, extra_vectors;
10917 	int vectors_left;
10918 	int v_budget, i;
10919 	int v_actual;
10920 	int iwarp_requested = 0;
10921 
10922 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
10923 		return -ENODEV;
10924 
10925 	/* The number of vectors we'll request will be comprised of:
10926 	 *   - Add 1 for "other" cause for Admin Queue events, etc.
10927 	 *   - The number of LAN queue pairs
10928 	 *	- Queues being used for RSS.
10929 	 *		We don't need as many as max_rss_size vectors.
10930 	 *		use rss_size instead in the calculation since that
10931 	 *		is governed by number of cpus in the system.
10932 	 *	- assumes symmetric Tx/Rx pairing
10933 	 *   - The number of VMDq pairs
10934 	 *   - The CPU count within the NUMA node if iWARP is enabled
10935 	 * Once we count this up, try the request.
10936 	 *
10937 	 * If we can't get what we want, we'll simplify to nearly nothing
10938 	 * and try again.  If that still fails, we punt.
10939 	 */
10940 	vectors_left = hw->func_caps.num_msix_vectors;
10941 	v_budget = 0;
10942 
10943 	/* reserve one vector for miscellaneous handler */
10944 	if (vectors_left) {
10945 		v_budget++;
10946 		vectors_left--;
10947 	}
10948 
10949 	/* reserve some vectors for the main PF traffic queues. Initially we
10950 	 * only reserve at most 50% of the available vectors, in the case that
10951 	 * the number of online CPUs is large. This ensures that we can enable
10952 	 * extra features as well. Once we've enabled the other features, we
10953 	 * will use any remaining vectors to reach as close as we can to the
10954 	 * number of online CPUs.
10955 	 */
10956 	cpus = num_online_cpus();
10957 	pf->num_lan_msix = min_t(int, cpus, vectors_left / 2);
10958 	vectors_left -= pf->num_lan_msix;
10959 
10960 	/* reserve one vector for sideband flow director */
10961 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
10962 		if (vectors_left) {
10963 			pf->num_fdsb_msix = 1;
10964 			v_budget++;
10965 			vectors_left--;
10966 		} else {
10967 			pf->num_fdsb_msix = 0;
10968 		}
10969 	}
10970 
10971 	/* can we reserve enough for iWARP? */
10972 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
10973 		iwarp_requested = pf->num_iwarp_msix;
10974 
10975 		if (!vectors_left)
10976 			pf->num_iwarp_msix = 0;
10977 		else if (vectors_left < pf->num_iwarp_msix)
10978 			pf->num_iwarp_msix = 1;
10979 		v_budget += pf->num_iwarp_msix;
10980 		vectors_left -= pf->num_iwarp_msix;
10981 	}
10982 
10983 	/* any vectors left over go for VMDq support */
10984 	if (pf->flags & I40E_FLAG_VMDQ_ENABLED) {
10985 		if (!vectors_left) {
10986 			pf->num_vmdq_msix = 0;
10987 			pf->num_vmdq_qps = 0;
10988 		} else {
10989 			int vmdq_vecs_wanted =
10990 				pf->num_vmdq_vsis * pf->num_vmdq_qps;
10991 			int vmdq_vecs =
10992 				min_t(int, vectors_left, vmdq_vecs_wanted);
10993 
10994 			/* if we're short on vectors for what's desired, we limit
10995 			 * the queues per vmdq.  If this is still more than are
10996 			 * available, the user will need to change the number of
10997 			 * queues/vectors used by the PF later with the ethtool
10998 			 * channels command
10999 			 */
11000 			if (vectors_left < vmdq_vecs_wanted) {
11001 				pf->num_vmdq_qps = 1;
11002 				vmdq_vecs_wanted = pf->num_vmdq_vsis;
11003 				vmdq_vecs = min_t(int,
11004 						  vectors_left,
11005 						  vmdq_vecs_wanted);
11006 			}
11007 			pf->num_vmdq_msix = pf->num_vmdq_qps;
11008 
11009 			v_budget += vmdq_vecs;
11010 			vectors_left -= vmdq_vecs;
11011 		}
11012 	}
11013 
11014 	/* On systems with a large number of SMP cores, we previously limited
11015 	 * the number of vectors for num_lan_msix to be at most 50% of the
11016 	 * available vectors, to allow for other features. Now, we add back
11017 	 * the remaining vectors. However, we ensure that the total
11018 	 * num_lan_msix will not exceed num_online_cpus(). To do this, we
11019 	 * calculate the number of vectors we can add without going over the
11020 	 * cap of CPUs. For systems with a small number of CPUs this will be
11021 	 * zero.
11022 	 */
11023 	extra_vectors = min_t(int, cpus - pf->num_lan_msix, vectors_left);
11024 	pf->num_lan_msix += extra_vectors;
11025 	vectors_left -= extra_vectors;
11026 
11027 	WARN(vectors_left < 0,
11028 	     "Calculation of remaining vectors underflowed. This is an accounting bug when determining total MSI-X vectors.\n");
11029 
11030 	v_budget += pf->num_lan_msix;
11031 	pf->msix_entries = kcalloc(v_budget, sizeof(struct msix_entry),
11032 				   GFP_KERNEL);
11033 	if (!pf->msix_entries)
11034 		return -ENOMEM;
11035 
11036 	for (i = 0; i < v_budget; i++)
11037 		pf->msix_entries[i].entry = i;
11038 	v_actual = i40e_reserve_msix_vectors(pf, v_budget);
11039 
11040 	if (v_actual < I40E_MIN_MSIX) {
11041 		pf->flags &= ~I40E_FLAG_MSIX_ENABLED;
11042 		kfree(pf->msix_entries);
11043 		pf->msix_entries = NULL;
11044 		pci_disable_msix(pf->pdev);
11045 		return -ENODEV;
11046 
11047 	} else if (v_actual == I40E_MIN_MSIX) {
11048 		/* Adjust for minimal MSIX use */
11049 		pf->num_vmdq_vsis = 0;
11050 		pf->num_vmdq_qps = 0;
11051 		pf->num_lan_qps = 1;
11052 		pf->num_lan_msix = 1;
11053 
11054 	} else if (v_actual != v_budget) {
11055 		/* If we have limited resources, we will start with no vectors
11056 		 * for the special features and then allocate vectors to some
11057 		 * of these features based on the policy and at the end disable
11058 		 * the features that did not get any vectors.
11059 		 */
11060 		int vec;
11061 
11062 		dev_info(&pf->pdev->dev,
11063 			 "MSI-X vector limit reached with %d, wanted %d, attempting to redistribute vectors\n",
11064 			 v_actual, v_budget);
11065 		/* reserve the misc vector */
11066 		vec = v_actual - 1;
11067 
11068 		/* Scale vector usage down */
11069 		pf->num_vmdq_msix = 1;    /* force VMDqs to only one vector */
11070 		pf->num_vmdq_vsis = 1;
11071 		pf->num_vmdq_qps = 1;
11072 
11073 		/* partition out the remaining vectors */
11074 		switch (vec) {
11075 		case 2:
11076 			pf->num_lan_msix = 1;
11077 			break;
11078 		case 3:
11079 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11080 				pf->num_lan_msix = 1;
11081 				pf->num_iwarp_msix = 1;
11082 			} else {
11083 				pf->num_lan_msix = 2;
11084 			}
11085 			break;
11086 		default:
11087 			if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
11088 				pf->num_iwarp_msix = min_t(int, (vec / 3),
11089 						 iwarp_requested);
11090 				pf->num_vmdq_vsis = min_t(int, (vec / 3),
11091 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11092 			} else {
11093 				pf->num_vmdq_vsis = min_t(int, (vec / 2),
11094 						  I40E_DEFAULT_NUM_VMDQ_VSI);
11095 			}
11096 			if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
11097 				pf->num_fdsb_msix = 1;
11098 				vec--;
11099 			}
11100 			pf->num_lan_msix = min_t(int,
11101 			       (vec - (pf->num_iwarp_msix + pf->num_vmdq_vsis)),
11102 							      pf->num_lan_msix);
11103 			pf->num_lan_qps = pf->num_lan_msix;
11104 			break;
11105 		}
11106 	}
11107 
11108 	if ((pf->flags & I40E_FLAG_FD_SB_ENABLED) &&
11109 	    (pf->num_fdsb_msix == 0)) {
11110 		dev_info(&pf->pdev->dev, "Sideband Flowdir disabled, not enough MSI-X vectors\n");
11111 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
11112 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11113 	}
11114 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
11115 	    (pf->num_vmdq_msix == 0)) {
11116 		dev_info(&pf->pdev->dev, "VMDq disabled, not enough MSI-X vectors\n");
11117 		pf->flags &= ~I40E_FLAG_VMDQ_ENABLED;
11118 	}
11119 
11120 	if ((pf->flags & I40E_FLAG_IWARP_ENABLED) &&
11121 	    (pf->num_iwarp_msix == 0)) {
11122 		dev_info(&pf->pdev->dev, "IWARP disabled, not enough MSI-X vectors\n");
11123 		pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
11124 	}
11125 	i40e_debug(&pf->hw, I40E_DEBUG_INIT,
11126 		   "MSI-X vector distribution: PF %d, VMDq %d, FDSB %d, iWARP %d\n",
11127 		   pf->num_lan_msix,
11128 		   pf->num_vmdq_msix * pf->num_vmdq_vsis,
11129 		   pf->num_fdsb_msix,
11130 		   pf->num_iwarp_msix);
11131 
11132 	return v_actual;
11133 }
11134 
11135 /**
11136  * i40e_vsi_alloc_q_vector - Allocate memory for a single interrupt vector
11137  * @vsi: the VSI being configured
11138  * @v_idx: index of the vector in the vsi struct
11139  * @cpu: cpu to be used on affinity_mask
11140  *
11141  * We allocate one q_vector.  If allocation fails we return -ENOMEM.
11142  **/
11143 static int i40e_vsi_alloc_q_vector(struct i40e_vsi *vsi, int v_idx, int cpu)
11144 {
11145 	struct i40e_q_vector *q_vector;
11146 
11147 	/* allocate q_vector */
11148 	q_vector = kzalloc(sizeof(struct i40e_q_vector), GFP_KERNEL);
11149 	if (!q_vector)
11150 		return -ENOMEM;
11151 
11152 	q_vector->vsi = vsi;
11153 	q_vector->v_idx = v_idx;
11154 	cpumask_copy(&q_vector->affinity_mask, cpu_possible_mask);
11155 
11156 	if (vsi->netdev)
11157 		netif_napi_add(vsi->netdev, &q_vector->napi,
11158 			       i40e_napi_poll, NAPI_POLL_WEIGHT);
11159 
11160 	/* tie q_vector and vsi together */
11161 	vsi->q_vectors[v_idx] = q_vector;
11162 
11163 	return 0;
11164 }
11165 
11166 /**
11167  * i40e_vsi_alloc_q_vectors - Allocate memory for interrupt vectors
11168  * @vsi: the VSI being configured
11169  *
11170  * We allocate one q_vector per queue interrupt.  If allocation fails we
11171  * return -ENOMEM.
11172  **/
11173 static int i40e_vsi_alloc_q_vectors(struct i40e_vsi *vsi)
11174 {
11175 	struct i40e_pf *pf = vsi->back;
11176 	int err, v_idx, num_q_vectors, current_cpu;
11177 
11178 	/* if not MSIX, give the one vector only to the LAN VSI */
11179 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
11180 		num_q_vectors = vsi->num_q_vectors;
11181 	else if (vsi == pf->vsi[pf->lan_vsi])
11182 		num_q_vectors = 1;
11183 	else
11184 		return -EINVAL;
11185 
11186 	current_cpu = cpumask_first(cpu_online_mask);
11187 
11188 	for (v_idx = 0; v_idx < num_q_vectors; v_idx++) {
11189 		err = i40e_vsi_alloc_q_vector(vsi, v_idx, current_cpu);
11190 		if (err)
11191 			goto err_out;
11192 		current_cpu = cpumask_next(current_cpu, cpu_online_mask);
11193 		if (unlikely(current_cpu >= nr_cpu_ids))
11194 			current_cpu = cpumask_first(cpu_online_mask);
11195 	}
11196 
11197 	return 0;
11198 
11199 err_out:
11200 	while (v_idx--)
11201 		i40e_free_q_vector(vsi, v_idx);
11202 
11203 	return err;
11204 }
11205 
11206 /**
11207  * i40e_init_interrupt_scheme - Determine proper interrupt scheme
11208  * @pf: board private structure to initialize
11209  **/
11210 static int i40e_init_interrupt_scheme(struct i40e_pf *pf)
11211 {
11212 	int vectors = 0;
11213 	ssize_t size;
11214 
11215 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11216 		vectors = i40e_init_msix(pf);
11217 		if (vectors < 0) {
11218 			pf->flags &= ~(I40E_FLAG_MSIX_ENABLED	|
11219 				       I40E_FLAG_IWARP_ENABLED	|
11220 				       I40E_FLAG_RSS_ENABLED	|
11221 				       I40E_FLAG_DCB_CAPABLE	|
11222 				       I40E_FLAG_DCB_ENABLED	|
11223 				       I40E_FLAG_SRIOV_ENABLED	|
11224 				       I40E_FLAG_FD_SB_ENABLED	|
11225 				       I40E_FLAG_FD_ATR_ENABLED	|
11226 				       I40E_FLAG_VMDQ_ENABLED);
11227 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
11228 
11229 			/* rework the queue expectations without MSIX */
11230 			i40e_determine_queue_usage(pf);
11231 		}
11232 	}
11233 
11234 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED) &&
11235 	    (pf->flags & I40E_FLAG_MSI_ENABLED)) {
11236 		dev_info(&pf->pdev->dev, "MSI-X not available, trying MSI\n");
11237 		vectors = pci_enable_msi(pf->pdev);
11238 		if (vectors < 0) {
11239 			dev_info(&pf->pdev->dev, "MSI init failed - %d\n",
11240 				 vectors);
11241 			pf->flags &= ~I40E_FLAG_MSI_ENABLED;
11242 		}
11243 		vectors = 1;  /* one MSI or Legacy vector */
11244 	}
11245 
11246 	if (!(pf->flags & (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED)))
11247 		dev_info(&pf->pdev->dev, "MSI-X and MSI not available, falling back to Legacy IRQ\n");
11248 
11249 	/* set up vector assignment tracking */
11250 	size = sizeof(struct i40e_lump_tracking) + (sizeof(u16) * vectors);
11251 	pf->irq_pile = kzalloc(size, GFP_KERNEL);
11252 	if (!pf->irq_pile)
11253 		return -ENOMEM;
11254 
11255 	pf->irq_pile->num_entries = vectors;
11256 	pf->irq_pile->search_hint = 0;
11257 
11258 	/* track first vector for misc interrupts, ignore return */
11259 	(void)i40e_get_lump(pf, pf->irq_pile, 1, I40E_PILE_VALID_BIT - 1);
11260 
11261 	return 0;
11262 }
11263 
11264 /**
11265  * i40e_restore_interrupt_scheme - Restore the interrupt scheme
11266  * @pf: private board data structure
11267  *
11268  * Restore the interrupt scheme that was cleared when we suspended the
11269  * device. This should be called during resume to re-allocate the q_vectors
11270  * and reacquire IRQs.
11271  */
11272 static int i40e_restore_interrupt_scheme(struct i40e_pf *pf)
11273 {
11274 	int err, i;
11275 
11276 	/* We cleared the MSI and MSI-X flags when disabling the old interrupt
11277 	 * scheme. We need to re-enabled them here in order to attempt to
11278 	 * re-acquire the MSI or MSI-X vectors
11279 	 */
11280 	pf->flags |= (I40E_FLAG_MSIX_ENABLED | I40E_FLAG_MSI_ENABLED);
11281 
11282 	err = i40e_init_interrupt_scheme(pf);
11283 	if (err)
11284 		return err;
11285 
11286 	/* Now that we've re-acquired IRQs, we need to remap the vectors and
11287 	 * rings together again.
11288 	 */
11289 	for (i = 0; i < pf->num_alloc_vsi; i++) {
11290 		if (pf->vsi[i]) {
11291 			err = i40e_vsi_alloc_q_vectors(pf->vsi[i]);
11292 			if (err)
11293 				goto err_unwind;
11294 			i40e_vsi_map_rings_to_vectors(pf->vsi[i]);
11295 		}
11296 	}
11297 
11298 	err = i40e_setup_misc_vector(pf);
11299 	if (err)
11300 		goto err_unwind;
11301 
11302 	if (pf->flags & I40E_FLAG_IWARP_ENABLED)
11303 		i40e_client_update_msix_info(pf);
11304 
11305 	return 0;
11306 
11307 err_unwind:
11308 	while (i--) {
11309 		if (pf->vsi[i])
11310 			i40e_vsi_free_q_vectors(pf->vsi[i]);
11311 	}
11312 
11313 	return err;
11314 }
11315 
11316 /**
11317  * i40e_setup_misc_vector_for_recovery_mode - Setup the misc vector to handle
11318  * non queue events in recovery mode
11319  * @pf: board private structure
11320  *
11321  * This sets up the handler for MSIX 0 or MSI/legacy, which is used to manage
11322  * the non-queue interrupts, e.g. AdminQ and errors in recovery mode.
11323  * This is handled differently than in recovery mode since no Tx/Rx resources
11324  * are being allocated.
11325  **/
11326 static int i40e_setup_misc_vector_for_recovery_mode(struct i40e_pf *pf)
11327 {
11328 	int err;
11329 
11330 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
11331 		err = i40e_setup_misc_vector(pf);
11332 
11333 		if (err) {
11334 			dev_info(&pf->pdev->dev,
11335 				 "MSI-X misc vector request failed, error %d\n",
11336 				 err);
11337 			return err;
11338 		}
11339 	} else {
11340 		u32 flags = pf->flags & I40E_FLAG_MSI_ENABLED ? 0 : IRQF_SHARED;
11341 
11342 		err = request_irq(pf->pdev->irq, i40e_intr, flags,
11343 				  pf->int_name, pf);
11344 
11345 		if (err) {
11346 			dev_info(&pf->pdev->dev,
11347 				 "MSI/legacy misc vector request failed, error %d\n",
11348 				 err);
11349 			return err;
11350 		}
11351 		i40e_enable_misc_int_causes(pf);
11352 		i40e_irq_dynamic_enable_icr0(pf);
11353 	}
11354 
11355 	return 0;
11356 }
11357 
11358 /**
11359  * i40e_setup_misc_vector - Setup the misc vector to handle non queue events
11360  * @pf: board private structure
11361  *
11362  * This sets up the handler for MSIX 0, which is used to manage the
11363  * non-queue interrupts, e.g. AdminQ and errors.  This is not used
11364  * when in MSI or Legacy interrupt mode.
11365  **/
11366 static int i40e_setup_misc_vector(struct i40e_pf *pf)
11367 {
11368 	struct i40e_hw *hw = &pf->hw;
11369 	int err = 0;
11370 
11371 	/* Only request the IRQ once, the first time through. */
11372 	if (!test_and_set_bit(__I40E_MISC_IRQ_REQUESTED, pf->state)) {
11373 		err = request_irq(pf->msix_entries[0].vector,
11374 				  i40e_intr, 0, pf->int_name, pf);
11375 		if (err) {
11376 			clear_bit(__I40E_MISC_IRQ_REQUESTED, pf->state);
11377 			dev_info(&pf->pdev->dev,
11378 				 "request_irq for %s failed: %d\n",
11379 				 pf->int_name, err);
11380 			return -EFAULT;
11381 		}
11382 	}
11383 
11384 	i40e_enable_misc_int_causes(pf);
11385 
11386 	/* associate no queues to the misc vector */
11387 	wr32(hw, I40E_PFINT_LNKLST0, I40E_QUEUE_END_OF_LIST);
11388 	wr32(hw, I40E_PFINT_ITR0(I40E_RX_ITR), I40E_ITR_8K);
11389 
11390 	i40e_flush(hw);
11391 
11392 	i40e_irq_dynamic_enable_icr0(pf);
11393 
11394 	return err;
11395 }
11396 
11397 /**
11398  * i40e_get_rss_aq - Get RSS keys and lut by using AQ commands
11399  * @vsi: Pointer to vsi structure
11400  * @seed: Buffter to store the hash keys
11401  * @lut: Buffer to store the lookup table entries
11402  * @lut_size: Size of buffer to store the lookup table entries
11403  *
11404  * Return 0 on success, negative on failure
11405  */
11406 static int i40e_get_rss_aq(struct i40e_vsi *vsi, const u8 *seed,
11407 			   u8 *lut, u16 lut_size)
11408 {
11409 	struct i40e_pf *pf = vsi->back;
11410 	struct i40e_hw *hw = &pf->hw;
11411 	int ret = 0;
11412 
11413 	if (seed) {
11414 		ret = i40e_aq_get_rss_key(hw, vsi->id,
11415 			(struct i40e_aqc_get_set_rss_key_data *)seed);
11416 		if (ret) {
11417 			dev_info(&pf->pdev->dev,
11418 				 "Cannot get RSS key, err %s aq_err %s\n",
11419 				 i40e_stat_str(&pf->hw, ret),
11420 				 i40e_aq_str(&pf->hw,
11421 					     pf->hw.aq.asq_last_status));
11422 			return ret;
11423 		}
11424 	}
11425 
11426 	if (lut) {
11427 		bool pf_lut = vsi->type == I40E_VSI_MAIN ? true : false;
11428 
11429 		ret = i40e_aq_get_rss_lut(hw, vsi->id, pf_lut, lut, lut_size);
11430 		if (ret) {
11431 			dev_info(&pf->pdev->dev,
11432 				 "Cannot get RSS lut, err %s aq_err %s\n",
11433 				 i40e_stat_str(&pf->hw, ret),
11434 				 i40e_aq_str(&pf->hw,
11435 					     pf->hw.aq.asq_last_status));
11436 			return ret;
11437 		}
11438 	}
11439 
11440 	return ret;
11441 }
11442 
11443 /**
11444  * i40e_config_rss_reg - Configure RSS keys and lut by writing registers
11445  * @vsi: Pointer to vsi structure
11446  * @seed: RSS hash seed
11447  * @lut: Lookup table
11448  * @lut_size: Lookup table size
11449  *
11450  * Returns 0 on success, negative on failure
11451  **/
11452 static int i40e_config_rss_reg(struct i40e_vsi *vsi, const u8 *seed,
11453 			       const u8 *lut, u16 lut_size)
11454 {
11455 	struct i40e_pf *pf = vsi->back;
11456 	struct i40e_hw *hw = &pf->hw;
11457 	u16 vf_id = vsi->vf_id;
11458 	u8 i;
11459 
11460 	/* Fill out hash function seed */
11461 	if (seed) {
11462 		u32 *seed_dw = (u32 *)seed;
11463 
11464 		if (vsi->type == I40E_VSI_MAIN) {
11465 			for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
11466 				wr32(hw, I40E_PFQF_HKEY(i), seed_dw[i]);
11467 		} else if (vsi->type == I40E_VSI_SRIOV) {
11468 			for (i = 0; i <= I40E_VFQF_HKEY1_MAX_INDEX; i++)
11469 				wr32(hw, I40E_VFQF_HKEY1(i, vf_id), seed_dw[i]);
11470 		} else {
11471 			dev_err(&pf->pdev->dev, "Cannot set RSS seed - invalid VSI type\n");
11472 		}
11473 	}
11474 
11475 	if (lut) {
11476 		u32 *lut_dw = (u32 *)lut;
11477 
11478 		if (vsi->type == I40E_VSI_MAIN) {
11479 			if (lut_size != I40E_HLUT_ARRAY_SIZE)
11480 				return -EINVAL;
11481 			for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
11482 				wr32(hw, I40E_PFQF_HLUT(i), lut_dw[i]);
11483 		} else if (vsi->type == I40E_VSI_SRIOV) {
11484 			if (lut_size != I40E_VF_HLUT_ARRAY_SIZE)
11485 				return -EINVAL;
11486 			for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
11487 				wr32(hw, I40E_VFQF_HLUT1(i, vf_id), lut_dw[i]);
11488 		} else {
11489 			dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
11490 		}
11491 	}
11492 	i40e_flush(hw);
11493 
11494 	return 0;
11495 }
11496 
11497 /**
11498  * i40e_get_rss_reg - Get the RSS keys and lut by reading registers
11499  * @vsi: Pointer to VSI structure
11500  * @seed: Buffer to store the keys
11501  * @lut: Buffer to store the lookup table entries
11502  * @lut_size: Size of buffer to store the lookup table entries
11503  *
11504  * Returns 0 on success, negative on failure
11505  */
11506 static int i40e_get_rss_reg(struct i40e_vsi *vsi, u8 *seed,
11507 			    u8 *lut, u16 lut_size)
11508 {
11509 	struct i40e_pf *pf = vsi->back;
11510 	struct i40e_hw *hw = &pf->hw;
11511 	u16 i;
11512 
11513 	if (seed) {
11514 		u32 *seed_dw = (u32 *)seed;
11515 
11516 		for (i = 0; i <= I40E_PFQF_HKEY_MAX_INDEX; i++)
11517 			seed_dw[i] = i40e_read_rx_ctl(hw, I40E_PFQF_HKEY(i));
11518 	}
11519 	if (lut) {
11520 		u32 *lut_dw = (u32 *)lut;
11521 
11522 		if (lut_size != I40E_HLUT_ARRAY_SIZE)
11523 			return -EINVAL;
11524 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
11525 			lut_dw[i] = rd32(hw, I40E_PFQF_HLUT(i));
11526 	}
11527 
11528 	return 0;
11529 }
11530 
11531 /**
11532  * i40e_config_rss - Configure RSS keys and lut
11533  * @vsi: Pointer to VSI structure
11534  * @seed: RSS hash seed
11535  * @lut: Lookup table
11536  * @lut_size: Lookup table size
11537  *
11538  * Returns 0 on success, negative on failure
11539  */
11540 int i40e_config_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
11541 {
11542 	struct i40e_pf *pf = vsi->back;
11543 
11544 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
11545 		return i40e_config_rss_aq(vsi, seed, lut, lut_size);
11546 	else
11547 		return i40e_config_rss_reg(vsi, seed, lut, lut_size);
11548 }
11549 
11550 /**
11551  * i40e_get_rss - Get RSS keys and lut
11552  * @vsi: Pointer to VSI structure
11553  * @seed: Buffer to store the keys
11554  * @lut: Buffer to store the lookup table entries
11555  * @lut_size: Size of buffer to store the lookup table entries
11556  *
11557  * Returns 0 on success, negative on failure
11558  */
11559 int i40e_get_rss(struct i40e_vsi *vsi, u8 *seed, u8 *lut, u16 lut_size)
11560 {
11561 	struct i40e_pf *pf = vsi->back;
11562 
11563 	if (pf->hw_features & I40E_HW_RSS_AQ_CAPABLE)
11564 		return i40e_get_rss_aq(vsi, seed, lut, lut_size);
11565 	else
11566 		return i40e_get_rss_reg(vsi, seed, lut, lut_size);
11567 }
11568 
11569 /**
11570  * i40e_fill_rss_lut - Fill the RSS lookup table with default values
11571  * @pf: Pointer to board private structure
11572  * @lut: Lookup table
11573  * @rss_table_size: Lookup table size
11574  * @rss_size: Range of queue number for hashing
11575  */
11576 void i40e_fill_rss_lut(struct i40e_pf *pf, u8 *lut,
11577 		       u16 rss_table_size, u16 rss_size)
11578 {
11579 	u16 i;
11580 
11581 	for (i = 0; i < rss_table_size; i++)
11582 		lut[i] = i % rss_size;
11583 }
11584 
11585 /**
11586  * i40e_pf_config_rss - Prepare for RSS if used
11587  * @pf: board private structure
11588  **/
11589 static int i40e_pf_config_rss(struct i40e_pf *pf)
11590 {
11591 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
11592 	u8 seed[I40E_HKEY_ARRAY_SIZE];
11593 	u8 *lut;
11594 	struct i40e_hw *hw = &pf->hw;
11595 	u32 reg_val;
11596 	u64 hena;
11597 	int ret;
11598 
11599 	/* By default we enable TCP/UDP with IPv4/IPv6 ptypes */
11600 	hena = (u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(0)) |
11601 		((u64)i40e_read_rx_ctl(hw, I40E_PFQF_HENA(1)) << 32);
11602 	hena |= i40e_pf_get_default_rss_hena(pf);
11603 
11604 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), (u32)hena);
11605 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), (u32)(hena >> 32));
11606 
11607 	/* Determine the RSS table size based on the hardware capabilities */
11608 	reg_val = i40e_read_rx_ctl(hw, I40E_PFQF_CTL_0);
11609 	reg_val = (pf->rss_table_size == 512) ?
11610 			(reg_val | I40E_PFQF_CTL_0_HASHLUTSIZE_512) :
11611 			(reg_val & ~I40E_PFQF_CTL_0_HASHLUTSIZE_512);
11612 	i40e_write_rx_ctl(hw, I40E_PFQF_CTL_0, reg_val);
11613 
11614 	/* Determine the RSS size of the VSI */
11615 	if (!vsi->rss_size) {
11616 		u16 qcount;
11617 		/* If the firmware does something weird during VSI init, we
11618 		 * could end up with zero TCs. Check for that to avoid
11619 		 * divide-by-zero. It probably won't pass traffic, but it also
11620 		 * won't panic.
11621 		 */
11622 		qcount = vsi->num_queue_pairs /
11623 			 (vsi->tc_config.numtc ? vsi->tc_config.numtc : 1);
11624 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
11625 	}
11626 	if (!vsi->rss_size)
11627 		return -EINVAL;
11628 
11629 	lut = kzalloc(vsi->rss_table_size, GFP_KERNEL);
11630 	if (!lut)
11631 		return -ENOMEM;
11632 
11633 	/* Use user configured lut if there is one, otherwise use default */
11634 	if (vsi->rss_lut_user)
11635 		memcpy(lut, vsi->rss_lut_user, vsi->rss_table_size);
11636 	else
11637 		i40e_fill_rss_lut(pf, lut, vsi->rss_table_size, vsi->rss_size);
11638 
11639 	/* Use user configured hash key if there is one, otherwise
11640 	 * use default.
11641 	 */
11642 	if (vsi->rss_hkey_user)
11643 		memcpy(seed, vsi->rss_hkey_user, I40E_HKEY_ARRAY_SIZE);
11644 	else
11645 		netdev_rss_key_fill((void *)seed, I40E_HKEY_ARRAY_SIZE);
11646 	ret = i40e_config_rss(vsi, seed, lut, vsi->rss_table_size);
11647 	kfree(lut);
11648 
11649 	return ret;
11650 }
11651 
11652 /**
11653  * i40e_reconfig_rss_queues - change number of queues for rss and rebuild
11654  * @pf: board private structure
11655  * @queue_count: the requested queue count for rss.
11656  *
11657  * returns 0 if rss is not enabled, if enabled returns the final rss queue
11658  * count which may be different from the requested queue count.
11659  * Note: expects to be called while under rtnl_lock()
11660  **/
11661 int i40e_reconfig_rss_queues(struct i40e_pf *pf, int queue_count)
11662 {
11663 	struct i40e_vsi *vsi = pf->vsi[pf->lan_vsi];
11664 	int new_rss_size;
11665 
11666 	if (!(pf->flags & I40E_FLAG_RSS_ENABLED))
11667 		return 0;
11668 
11669 	queue_count = min_t(int, queue_count, num_online_cpus());
11670 	new_rss_size = min_t(int, queue_count, pf->rss_size_max);
11671 
11672 	if (queue_count != vsi->num_queue_pairs) {
11673 		u16 qcount;
11674 
11675 		vsi->req_queue_pairs = queue_count;
11676 		i40e_prep_for_reset(pf, true);
11677 
11678 		pf->alloc_rss_size = new_rss_size;
11679 
11680 		i40e_reset_and_rebuild(pf, true, true);
11681 
11682 		/* Discard the user configured hash keys and lut, if less
11683 		 * queues are enabled.
11684 		 */
11685 		if (queue_count < vsi->rss_size) {
11686 			i40e_clear_rss_config_user(vsi);
11687 			dev_dbg(&pf->pdev->dev,
11688 				"discard user configured hash keys and lut\n");
11689 		}
11690 
11691 		/* Reset vsi->rss_size, as number of enabled queues changed */
11692 		qcount = vsi->num_queue_pairs / vsi->tc_config.numtc;
11693 		vsi->rss_size = min_t(int, pf->alloc_rss_size, qcount);
11694 
11695 		i40e_pf_config_rss(pf);
11696 	}
11697 	dev_info(&pf->pdev->dev, "User requested queue count/HW max RSS count:  %d/%d\n",
11698 		 vsi->req_queue_pairs, pf->rss_size_max);
11699 	return pf->alloc_rss_size;
11700 }
11701 
11702 /**
11703  * i40e_get_partition_bw_setting - Retrieve BW settings for this PF partition
11704  * @pf: board private structure
11705  **/
11706 i40e_status i40e_get_partition_bw_setting(struct i40e_pf *pf)
11707 {
11708 	i40e_status status;
11709 	bool min_valid, max_valid;
11710 	u32 max_bw, min_bw;
11711 
11712 	status = i40e_read_bw_from_alt_ram(&pf->hw, &max_bw, &min_bw,
11713 					   &min_valid, &max_valid);
11714 
11715 	if (!status) {
11716 		if (min_valid)
11717 			pf->min_bw = min_bw;
11718 		if (max_valid)
11719 			pf->max_bw = max_bw;
11720 	}
11721 
11722 	return status;
11723 }
11724 
11725 /**
11726  * i40e_set_partition_bw_setting - Set BW settings for this PF partition
11727  * @pf: board private structure
11728  **/
11729 i40e_status i40e_set_partition_bw_setting(struct i40e_pf *pf)
11730 {
11731 	struct i40e_aqc_configure_partition_bw_data bw_data;
11732 	i40e_status status;
11733 
11734 	/* Set the valid bit for this PF */
11735 	bw_data.pf_valid_bits = cpu_to_le16(BIT(pf->hw.pf_id));
11736 	bw_data.max_bw[pf->hw.pf_id] = pf->max_bw & I40E_ALT_BW_VALUE_MASK;
11737 	bw_data.min_bw[pf->hw.pf_id] = pf->min_bw & I40E_ALT_BW_VALUE_MASK;
11738 
11739 	/* Set the new bandwidths */
11740 	status = i40e_aq_configure_partition_bw(&pf->hw, &bw_data, NULL);
11741 
11742 	return status;
11743 }
11744 
11745 /**
11746  * i40e_commit_partition_bw_setting - Commit BW settings for this PF partition
11747  * @pf: board private structure
11748  **/
11749 i40e_status i40e_commit_partition_bw_setting(struct i40e_pf *pf)
11750 {
11751 	/* Commit temporary BW setting to permanent NVM image */
11752 	enum i40e_admin_queue_err last_aq_status;
11753 	i40e_status ret;
11754 	u16 nvm_word;
11755 
11756 	if (pf->hw.partition_id != 1) {
11757 		dev_info(&pf->pdev->dev,
11758 			 "Commit BW only works on partition 1! This is partition %d",
11759 			 pf->hw.partition_id);
11760 		ret = I40E_NOT_SUPPORTED;
11761 		goto bw_commit_out;
11762 	}
11763 
11764 	/* Acquire NVM for read access */
11765 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_READ);
11766 	last_aq_status = pf->hw.aq.asq_last_status;
11767 	if (ret) {
11768 		dev_info(&pf->pdev->dev,
11769 			 "Cannot acquire NVM for read access, err %s aq_err %s\n",
11770 			 i40e_stat_str(&pf->hw, ret),
11771 			 i40e_aq_str(&pf->hw, last_aq_status));
11772 		goto bw_commit_out;
11773 	}
11774 
11775 	/* Read word 0x10 of NVM - SW compatibility word 1 */
11776 	ret = i40e_aq_read_nvm(&pf->hw,
11777 			       I40E_SR_NVM_CONTROL_WORD,
11778 			       0x10, sizeof(nvm_word), &nvm_word,
11779 			       false, NULL);
11780 	/* Save off last admin queue command status before releasing
11781 	 * the NVM
11782 	 */
11783 	last_aq_status = pf->hw.aq.asq_last_status;
11784 	i40e_release_nvm(&pf->hw);
11785 	if (ret) {
11786 		dev_info(&pf->pdev->dev, "NVM read error, err %s aq_err %s\n",
11787 			 i40e_stat_str(&pf->hw, ret),
11788 			 i40e_aq_str(&pf->hw, last_aq_status));
11789 		goto bw_commit_out;
11790 	}
11791 
11792 	/* Wait a bit for NVM release to complete */
11793 	msleep(50);
11794 
11795 	/* Acquire NVM for write access */
11796 	ret = i40e_acquire_nvm(&pf->hw, I40E_RESOURCE_WRITE);
11797 	last_aq_status = pf->hw.aq.asq_last_status;
11798 	if (ret) {
11799 		dev_info(&pf->pdev->dev,
11800 			 "Cannot acquire NVM for write access, err %s aq_err %s\n",
11801 			 i40e_stat_str(&pf->hw, ret),
11802 			 i40e_aq_str(&pf->hw, last_aq_status));
11803 		goto bw_commit_out;
11804 	}
11805 	/* Write it back out unchanged to initiate update NVM,
11806 	 * which will force a write of the shadow (alt) RAM to
11807 	 * the NVM - thus storing the bandwidth values permanently.
11808 	 */
11809 	ret = i40e_aq_update_nvm(&pf->hw,
11810 				 I40E_SR_NVM_CONTROL_WORD,
11811 				 0x10, sizeof(nvm_word),
11812 				 &nvm_word, true, 0, NULL);
11813 	/* Save off last admin queue command status before releasing
11814 	 * the NVM
11815 	 */
11816 	last_aq_status = pf->hw.aq.asq_last_status;
11817 	i40e_release_nvm(&pf->hw);
11818 	if (ret)
11819 		dev_info(&pf->pdev->dev,
11820 			 "BW settings NOT SAVED, err %s aq_err %s\n",
11821 			 i40e_stat_str(&pf->hw, ret),
11822 			 i40e_aq_str(&pf->hw, last_aq_status));
11823 bw_commit_out:
11824 
11825 	return ret;
11826 }
11827 
11828 /**
11829  * i40e_sw_init - Initialize general software structures (struct i40e_pf)
11830  * @pf: board private structure to initialize
11831  *
11832  * i40e_sw_init initializes the Adapter private data structure.
11833  * Fields are initialized based on PCI device information and
11834  * OS network device settings (MTU size).
11835  **/
11836 static int i40e_sw_init(struct i40e_pf *pf)
11837 {
11838 	int err = 0;
11839 	int size;
11840 
11841 	/* Set default capability flags */
11842 	pf->flags = I40E_FLAG_RX_CSUM_ENABLED |
11843 		    I40E_FLAG_MSI_ENABLED     |
11844 		    I40E_FLAG_MSIX_ENABLED;
11845 
11846 	/* Set default ITR */
11847 	pf->rx_itr_default = I40E_ITR_RX_DEF;
11848 	pf->tx_itr_default = I40E_ITR_TX_DEF;
11849 
11850 	/* Depending on PF configurations, it is possible that the RSS
11851 	 * maximum might end up larger than the available queues
11852 	 */
11853 	pf->rss_size_max = BIT(pf->hw.func_caps.rss_table_entry_width);
11854 	pf->alloc_rss_size = 1;
11855 	pf->rss_table_size = pf->hw.func_caps.rss_table_size;
11856 	pf->rss_size_max = min_t(int, pf->rss_size_max,
11857 				 pf->hw.func_caps.num_tx_qp);
11858 	if (pf->hw.func_caps.rss) {
11859 		pf->flags |= I40E_FLAG_RSS_ENABLED;
11860 		pf->alloc_rss_size = min_t(int, pf->rss_size_max,
11861 					   num_online_cpus());
11862 	}
11863 
11864 	/* MFP mode enabled */
11865 	if (pf->hw.func_caps.npar_enable || pf->hw.func_caps.flex10_enable) {
11866 		pf->flags |= I40E_FLAG_MFP_ENABLED;
11867 		dev_info(&pf->pdev->dev, "MFP mode Enabled\n");
11868 		if (i40e_get_partition_bw_setting(pf)) {
11869 			dev_warn(&pf->pdev->dev,
11870 				 "Could not get partition bw settings\n");
11871 		} else {
11872 			dev_info(&pf->pdev->dev,
11873 				 "Partition BW Min = %8.8x, Max = %8.8x\n",
11874 				 pf->min_bw, pf->max_bw);
11875 
11876 			/* nudge the Tx scheduler */
11877 			i40e_set_partition_bw_setting(pf);
11878 		}
11879 	}
11880 
11881 	if ((pf->hw.func_caps.fd_filters_guaranteed > 0) ||
11882 	    (pf->hw.func_caps.fd_filters_best_effort > 0)) {
11883 		pf->flags |= I40E_FLAG_FD_ATR_ENABLED;
11884 		pf->atr_sample_rate = I40E_DEFAULT_ATR_SAMPLE_RATE;
11885 		if (pf->flags & I40E_FLAG_MFP_ENABLED &&
11886 		    pf->hw.num_partitions > 1)
11887 			dev_info(&pf->pdev->dev,
11888 				 "Flow Director Sideband mode Disabled in MFP mode\n");
11889 		else
11890 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
11891 		pf->fdir_pf_filter_count =
11892 				 pf->hw.func_caps.fd_filters_guaranteed;
11893 		pf->hw.fdir_shared_filter_count =
11894 				 pf->hw.func_caps.fd_filters_best_effort;
11895 	}
11896 
11897 	if (pf->hw.mac.type == I40E_MAC_X722) {
11898 		pf->hw_features |= (I40E_HW_RSS_AQ_CAPABLE |
11899 				    I40E_HW_128_QP_RSS_CAPABLE |
11900 				    I40E_HW_ATR_EVICT_CAPABLE |
11901 				    I40E_HW_WB_ON_ITR_CAPABLE |
11902 				    I40E_HW_MULTIPLE_TCP_UDP_RSS_PCTYPE |
11903 				    I40E_HW_NO_PCI_LINK_CHECK |
11904 				    I40E_HW_USE_SET_LLDP_MIB |
11905 				    I40E_HW_GENEVE_OFFLOAD_CAPABLE |
11906 				    I40E_HW_PTP_L4_CAPABLE |
11907 				    I40E_HW_WOL_MC_MAGIC_PKT_WAKE |
11908 				    I40E_HW_OUTER_UDP_CSUM_CAPABLE);
11909 
11910 #define I40E_FDEVICT_PCTYPE_DEFAULT 0xc03
11911 		if (rd32(&pf->hw, I40E_GLQF_FDEVICTENA(1)) !=
11912 		    I40E_FDEVICT_PCTYPE_DEFAULT) {
11913 			dev_warn(&pf->pdev->dev,
11914 				 "FD EVICT PCTYPES are not right, disable FD HW EVICT\n");
11915 			pf->hw_features &= ~I40E_HW_ATR_EVICT_CAPABLE;
11916 		}
11917 	} else if ((pf->hw.aq.api_maj_ver > 1) ||
11918 		   ((pf->hw.aq.api_maj_ver == 1) &&
11919 		    (pf->hw.aq.api_min_ver > 4))) {
11920 		/* Supported in FW API version higher than 1.4 */
11921 		pf->hw_features |= I40E_HW_GENEVE_OFFLOAD_CAPABLE;
11922 	}
11923 
11924 	/* Enable HW ATR eviction if possible */
11925 	if (pf->hw_features & I40E_HW_ATR_EVICT_CAPABLE)
11926 		pf->flags |= I40E_FLAG_HW_ATR_EVICT_ENABLED;
11927 
11928 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
11929 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 33)) ||
11930 	    (pf->hw.aq.fw_maj_ver < 4))) {
11931 		pf->hw_features |= I40E_HW_RESTART_AUTONEG;
11932 		/* No DCB support  for FW < v4.33 */
11933 		pf->hw_features |= I40E_HW_NO_DCB_SUPPORT;
11934 	}
11935 
11936 	/* Disable FW LLDP if FW < v4.3 */
11937 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
11938 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver < 3)) ||
11939 	    (pf->hw.aq.fw_maj_ver < 4)))
11940 		pf->hw_features |= I40E_HW_STOP_FW_LLDP;
11941 
11942 	/* Use the FW Set LLDP MIB API if FW > v4.40 */
11943 	if ((pf->hw.mac.type == I40E_MAC_XL710) &&
11944 	    (((pf->hw.aq.fw_maj_ver == 4) && (pf->hw.aq.fw_min_ver >= 40)) ||
11945 	    (pf->hw.aq.fw_maj_ver >= 5)))
11946 		pf->hw_features |= I40E_HW_USE_SET_LLDP_MIB;
11947 
11948 	/* Enable PTP L4 if FW > v6.0 */
11949 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
11950 	    pf->hw.aq.fw_maj_ver >= 6)
11951 		pf->hw_features |= I40E_HW_PTP_L4_CAPABLE;
11952 
11953 	if (pf->hw.func_caps.vmdq && num_online_cpus() != 1) {
11954 		pf->num_vmdq_vsis = I40E_DEFAULT_NUM_VMDQ_VSI;
11955 		pf->flags |= I40E_FLAG_VMDQ_ENABLED;
11956 		pf->num_vmdq_qps = i40e_default_queues_per_vmdq(pf);
11957 	}
11958 
11959 	if (pf->hw.func_caps.iwarp && num_online_cpus() != 1) {
11960 		pf->flags |= I40E_FLAG_IWARP_ENABLED;
11961 		/* IWARP needs one extra vector for CQP just like MISC.*/
11962 		pf->num_iwarp_msix = (int)num_online_cpus() + 1;
11963 	}
11964 	/* Stopping FW LLDP engine is supported on XL710 and X722
11965 	 * starting from FW versions determined in i40e_init_adminq.
11966 	 * Stopping the FW LLDP engine is not supported on XL710
11967 	 * if NPAR is functioning so unset this hw flag in this case.
11968 	 */
11969 	if (pf->hw.mac.type == I40E_MAC_XL710 &&
11970 	    pf->hw.func_caps.npar_enable &&
11971 	    (pf->hw.flags & I40E_HW_FLAG_FW_LLDP_STOPPABLE))
11972 		pf->hw.flags &= ~I40E_HW_FLAG_FW_LLDP_STOPPABLE;
11973 
11974 #ifdef CONFIG_PCI_IOV
11975 	if (pf->hw.func_caps.num_vfs && pf->hw.partition_id == 1) {
11976 		pf->num_vf_qps = I40E_DEFAULT_QUEUES_PER_VF;
11977 		pf->flags |= I40E_FLAG_SRIOV_ENABLED;
11978 		pf->num_req_vfs = min_t(int,
11979 					pf->hw.func_caps.num_vfs,
11980 					I40E_MAX_VF_COUNT);
11981 	}
11982 #endif /* CONFIG_PCI_IOV */
11983 	pf->eeprom_version = 0xDEAD;
11984 	pf->lan_veb = I40E_NO_VEB;
11985 	pf->lan_vsi = I40E_NO_VSI;
11986 
11987 	/* By default FW has this off for performance reasons */
11988 	pf->flags &= ~I40E_FLAG_VEB_STATS_ENABLED;
11989 
11990 	/* set up queue assignment tracking */
11991 	size = sizeof(struct i40e_lump_tracking)
11992 		+ (sizeof(u16) * pf->hw.func_caps.num_tx_qp);
11993 	pf->qp_pile = kzalloc(size, GFP_KERNEL);
11994 	if (!pf->qp_pile) {
11995 		err = -ENOMEM;
11996 		goto sw_init_done;
11997 	}
11998 	pf->qp_pile->num_entries = pf->hw.func_caps.num_tx_qp;
11999 	pf->qp_pile->search_hint = 0;
12000 
12001 	pf->tx_timeout_recovery_level = 1;
12002 
12003 	mutex_init(&pf->switch_mutex);
12004 
12005 sw_init_done:
12006 	return err;
12007 }
12008 
12009 /**
12010  * i40e_set_ntuple - set the ntuple feature flag and take action
12011  * @pf: board private structure to initialize
12012  * @features: the feature set that the stack is suggesting
12013  *
12014  * returns a bool to indicate if reset needs to happen
12015  **/
12016 bool i40e_set_ntuple(struct i40e_pf *pf, netdev_features_t features)
12017 {
12018 	bool need_reset = false;
12019 
12020 	/* Check if Flow Director n-tuple support was enabled or disabled.  If
12021 	 * the state changed, we need to reset.
12022 	 */
12023 	if (features & NETIF_F_NTUPLE) {
12024 		/* Enable filters and mark for reset */
12025 		if (!(pf->flags & I40E_FLAG_FD_SB_ENABLED))
12026 			need_reset = true;
12027 		/* enable FD_SB only if there is MSI-X vector and no cloud
12028 		 * filters exist
12029 		 */
12030 		if (pf->num_fdsb_msix > 0 && !pf->num_cloud_filters) {
12031 			pf->flags |= I40E_FLAG_FD_SB_ENABLED;
12032 			pf->flags &= ~I40E_FLAG_FD_SB_INACTIVE;
12033 		}
12034 	} else {
12035 		/* turn off filters, mark for reset and clear SW filter list */
12036 		if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
12037 			need_reset = true;
12038 			i40e_fdir_filter_exit(pf);
12039 		}
12040 		pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
12041 		clear_bit(__I40E_FD_SB_AUTO_DISABLED, pf->state);
12042 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
12043 
12044 		/* reset fd counters */
12045 		pf->fd_add_err = 0;
12046 		pf->fd_atr_cnt = 0;
12047 		/* if ATR was auto disabled it can be re-enabled. */
12048 		if (test_and_clear_bit(__I40E_FD_ATR_AUTO_DISABLED, pf->state))
12049 			if ((pf->flags & I40E_FLAG_FD_ATR_ENABLED) &&
12050 			    (I40E_DEBUG_FD & pf->hw.debug_mask))
12051 				dev_info(&pf->pdev->dev, "ATR re-enabled.\n");
12052 	}
12053 	return need_reset;
12054 }
12055 
12056 /**
12057  * i40e_clear_rss_lut - clear the rx hash lookup table
12058  * @vsi: the VSI being configured
12059  **/
12060 static void i40e_clear_rss_lut(struct i40e_vsi *vsi)
12061 {
12062 	struct i40e_pf *pf = vsi->back;
12063 	struct i40e_hw *hw = &pf->hw;
12064 	u16 vf_id = vsi->vf_id;
12065 	u8 i;
12066 
12067 	if (vsi->type == I40E_VSI_MAIN) {
12068 		for (i = 0; i <= I40E_PFQF_HLUT_MAX_INDEX; i++)
12069 			wr32(hw, I40E_PFQF_HLUT(i), 0);
12070 	} else if (vsi->type == I40E_VSI_SRIOV) {
12071 		for (i = 0; i <= I40E_VFQF_HLUT_MAX_INDEX; i++)
12072 			i40e_write_rx_ctl(hw, I40E_VFQF_HLUT1(i, vf_id), 0);
12073 	} else {
12074 		dev_err(&pf->pdev->dev, "Cannot set RSS LUT - invalid VSI type\n");
12075 	}
12076 }
12077 
12078 /**
12079  * i40e_set_features - set the netdev feature flags
12080  * @netdev: ptr to the netdev being adjusted
12081  * @features: the feature set that the stack is suggesting
12082  * Note: expects to be called while under rtnl_lock()
12083  **/
12084 static int i40e_set_features(struct net_device *netdev,
12085 			     netdev_features_t features)
12086 {
12087 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12088 	struct i40e_vsi *vsi = np->vsi;
12089 	struct i40e_pf *pf = vsi->back;
12090 	bool need_reset;
12091 
12092 	if (features & NETIF_F_RXHASH && !(netdev->features & NETIF_F_RXHASH))
12093 		i40e_pf_config_rss(pf);
12094 	else if (!(features & NETIF_F_RXHASH) &&
12095 		 netdev->features & NETIF_F_RXHASH)
12096 		i40e_clear_rss_lut(vsi);
12097 
12098 	if (features & NETIF_F_HW_VLAN_CTAG_RX)
12099 		i40e_vlan_stripping_enable(vsi);
12100 	else
12101 		i40e_vlan_stripping_disable(vsi);
12102 
12103 	if (!(features & NETIF_F_HW_TC) && pf->num_cloud_filters) {
12104 		dev_err(&pf->pdev->dev,
12105 			"Offloaded tc filters active, can't turn hw_tc_offload off");
12106 		return -EINVAL;
12107 	}
12108 
12109 	if (!(features & NETIF_F_HW_L2FW_DOFFLOAD) && vsi->macvlan_cnt)
12110 		i40e_del_all_macvlans(vsi);
12111 
12112 	need_reset = i40e_set_ntuple(pf, features);
12113 
12114 	if (need_reset)
12115 		i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12116 
12117 	return 0;
12118 }
12119 
12120 /**
12121  * i40e_get_udp_port_idx - Lookup a possibly offloaded for Rx UDP port
12122  * @pf: board private structure
12123  * @port: The UDP port to look up
12124  *
12125  * Returns the index number or I40E_MAX_PF_UDP_OFFLOAD_PORTS if port not found
12126  **/
12127 static u8 i40e_get_udp_port_idx(struct i40e_pf *pf, u16 port)
12128 {
12129 	u8 i;
12130 
12131 	for (i = 0; i < I40E_MAX_PF_UDP_OFFLOAD_PORTS; i++) {
12132 		/* Do not report ports with pending deletions as
12133 		 * being available.
12134 		 */
12135 		if (!port && (pf->pending_udp_bitmap & BIT_ULL(i)))
12136 			continue;
12137 		if (pf->udp_ports[i].port == port)
12138 			return i;
12139 	}
12140 
12141 	return i;
12142 }
12143 
12144 /**
12145  * i40e_udp_tunnel_add - Get notifications about UDP tunnel ports that come up
12146  * @netdev: This physical port's netdev
12147  * @ti: Tunnel endpoint information
12148  **/
12149 static void i40e_udp_tunnel_add(struct net_device *netdev,
12150 				struct udp_tunnel_info *ti)
12151 {
12152 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12153 	struct i40e_vsi *vsi = np->vsi;
12154 	struct i40e_pf *pf = vsi->back;
12155 	u16 port = ntohs(ti->port);
12156 	u8 next_idx;
12157 	u8 idx;
12158 
12159 	idx = i40e_get_udp_port_idx(pf, port);
12160 
12161 	/* Check if port already exists */
12162 	if (idx < I40E_MAX_PF_UDP_OFFLOAD_PORTS) {
12163 		netdev_info(netdev, "port %d already offloaded\n", port);
12164 		return;
12165 	}
12166 
12167 	/* Now check if there is space to add the new port */
12168 	next_idx = i40e_get_udp_port_idx(pf, 0);
12169 
12170 	if (next_idx == I40E_MAX_PF_UDP_OFFLOAD_PORTS) {
12171 		netdev_info(netdev, "maximum number of offloaded UDP ports reached, not adding port %d\n",
12172 			    port);
12173 		return;
12174 	}
12175 
12176 	switch (ti->type) {
12177 	case UDP_TUNNEL_TYPE_VXLAN:
12178 		pf->udp_ports[next_idx].type = I40E_AQC_TUNNEL_TYPE_VXLAN;
12179 		break;
12180 	case UDP_TUNNEL_TYPE_GENEVE:
12181 		if (!(pf->hw_features & I40E_HW_GENEVE_OFFLOAD_CAPABLE))
12182 			return;
12183 		pf->udp_ports[next_idx].type = I40E_AQC_TUNNEL_TYPE_NGE;
12184 		break;
12185 	default:
12186 		return;
12187 	}
12188 
12189 	/* New port: add it and mark its index in the bitmap */
12190 	pf->udp_ports[next_idx].port = port;
12191 	pf->udp_ports[next_idx].filter_index = I40E_UDP_PORT_INDEX_UNUSED;
12192 	pf->pending_udp_bitmap |= BIT_ULL(next_idx);
12193 	set_bit(__I40E_UDP_FILTER_SYNC_PENDING, pf->state);
12194 }
12195 
12196 /**
12197  * i40e_udp_tunnel_del - Get notifications about UDP tunnel ports that go away
12198  * @netdev: This physical port's netdev
12199  * @ti: Tunnel endpoint information
12200  **/
12201 static void i40e_udp_tunnel_del(struct net_device *netdev,
12202 				struct udp_tunnel_info *ti)
12203 {
12204 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12205 	struct i40e_vsi *vsi = np->vsi;
12206 	struct i40e_pf *pf = vsi->back;
12207 	u16 port = ntohs(ti->port);
12208 	u8 idx;
12209 
12210 	idx = i40e_get_udp_port_idx(pf, port);
12211 
12212 	/* Check if port already exists */
12213 	if (idx >= I40E_MAX_PF_UDP_OFFLOAD_PORTS)
12214 		goto not_found;
12215 
12216 	switch (ti->type) {
12217 	case UDP_TUNNEL_TYPE_VXLAN:
12218 		if (pf->udp_ports[idx].type != I40E_AQC_TUNNEL_TYPE_VXLAN)
12219 			goto not_found;
12220 		break;
12221 	case UDP_TUNNEL_TYPE_GENEVE:
12222 		if (pf->udp_ports[idx].type != I40E_AQC_TUNNEL_TYPE_NGE)
12223 			goto not_found;
12224 		break;
12225 	default:
12226 		goto not_found;
12227 	}
12228 
12229 	/* if port exists, set it to 0 (mark for deletion)
12230 	 * and make it pending
12231 	 */
12232 	pf->udp_ports[idx].port = 0;
12233 
12234 	/* Toggle pending bit instead of setting it. This way if we are
12235 	 * deleting a port that has yet to be added we just clear the pending
12236 	 * bit and don't have to worry about it.
12237 	 */
12238 	pf->pending_udp_bitmap ^= BIT_ULL(idx);
12239 	set_bit(__I40E_UDP_FILTER_SYNC_PENDING, pf->state);
12240 
12241 	return;
12242 not_found:
12243 	netdev_warn(netdev, "UDP port %d was not found, not deleting\n",
12244 		    port);
12245 }
12246 
12247 static int i40e_get_phys_port_id(struct net_device *netdev,
12248 				 struct netdev_phys_item_id *ppid)
12249 {
12250 	struct i40e_netdev_priv *np = netdev_priv(netdev);
12251 	struct i40e_pf *pf = np->vsi->back;
12252 	struct i40e_hw *hw = &pf->hw;
12253 
12254 	if (!(pf->hw_features & I40E_HW_PORT_ID_VALID))
12255 		return -EOPNOTSUPP;
12256 
12257 	ppid->id_len = min_t(int, sizeof(hw->mac.port_addr), sizeof(ppid->id));
12258 	memcpy(ppid->id, hw->mac.port_addr, ppid->id_len);
12259 
12260 	return 0;
12261 }
12262 
12263 /**
12264  * i40e_ndo_fdb_add - add an entry to the hardware database
12265  * @ndm: the input from the stack
12266  * @tb: pointer to array of nladdr (unused)
12267  * @dev: the net device pointer
12268  * @addr: the MAC address entry being added
12269  * @vid: VLAN ID
12270  * @flags: instructions from stack about fdb operation
12271  */
12272 static int i40e_ndo_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
12273 			    struct net_device *dev,
12274 			    const unsigned char *addr, u16 vid,
12275 			    u16 flags,
12276 			    struct netlink_ext_ack *extack)
12277 {
12278 	struct i40e_netdev_priv *np = netdev_priv(dev);
12279 	struct i40e_pf *pf = np->vsi->back;
12280 	int err = 0;
12281 
12282 	if (!(pf->flags & I40E_FLAG_SRIOV_ENABLED))
12283 		return -EOPNOTSUPP;
12284 
12285 	if (vid) {
12286 		pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name);
12287 		return -EINVAL;
12288 	}
12289 
12290 	/* Hardware does not support aging addresses so if a
12291 	 * ndm_state is given only allow permanent addresses
12292 	 */
12293 	if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) {
12294 		netdev_info(dev, "FDB only supports static addresses\n");
12295 		return -EINVAL;
12296 	}
12297 
12298 	if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr))
12299 		err = dev_uc_add_excl(dev, addr);
12300 	else if (is_multicast_ether_addr(addr))
12301 		err = dev_mc_add_excl(dev, addr);
12302 	else
12303 		err = -EINVAL;
12304 
12305 	/* Only return duplicate errors if NLM_F_EXCL is set */
12306 	if (err == -EEXIST && !(flags & NLM_F_EXCL))
12307 		err = 0;
12308 
12309 	return err;
12310 }
12311 
12312 /**
12313  * i40e_ndo_bridge_setlink - Set the hardware bridge mode
12314  * @dev: the netdev being configured
12315  * @nlh: RTNL message
12316  * @flags: bridge flags
12317  * @extack: netlink extended ack
12318  *
12319  * Inserts a new hardware bridge if not already created and
12320  * enables the bridging mode requested (VEB or VEPA). If the
12321  * hardware bridge has already been inserted and the request
12322  * is to change the mode then that requires a PF reset to
12323  * allow rebuild of the components with required hardware
12324  * bridge mode enabled.
12325  *
12326  * Note: expects to be called while under rtnl_lock()
12327  **/
12328 static int i40e_ndo_bridge_setlink(struct net_device *dev,
12329 				   struct nlmsghdr *nlh,
12330 				   u16 flags,
12331 				   struct netlink_ext_ack *extack)
12332 {
12333 	struct i40e_netdev_priv *np = netdev_priv(dev);
12334 	struct i40e_vsi *vsi = np->vsi;
12335 	struct i40e_pf *pf = vsi->back;
12336 	struct i40e_veb *veb = NULL;
12337 	struct nlattr *attr, *br_spec;
12338 	int i, rem;
12339 
12340 	/* Only for PF VSI for now */
12341 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
12342 		return -EOPNOTSUPP;
12343 
12344 	/* Find the HW bridge for PF VSI */
12345 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
12346 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
12347 			veb = pf->veb[i];
12348 	}
12349 
12350 	br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC);
12351 
12352 	nla_for_each_nested(attr, br_spec, rem) {
12353 		__u16 mode;
12354 
12355 		if (nla_type(attr) != IFLA_BRIDGE_MODE)
12356 			continue;
12357 
12358 		mode = nla_get_u16(attr);
12359 		if ((mode != BRIDGE_MODE_VEPA) &&
12360 		    (mode != BRIDGE_MODE_VEB))
12361 			return -EINVAL;
12362 
12363 		/* Insert a new HW bridge */
12364 		if (!veb) {
12365 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
12366 					     vsi->tc_config.enabled_tc);
12367 			if (veb) {
12368 				veb->bridge_mode = mode;
12369 				i40e_config_bridge_mode(veb);
12370 			} else {
12371 				/* No Bridge HW offload available */
12372 				return -ENOENT;
12373 			}
12374 			break;
12375 		} else if (mode != veb->bridge_mode) {
12376 			/* Existing HW bridge but different mode needs reset */
12377 			veb->bridge_mode = mode;
12378 			/* TODO: If no VFs or VMDq VSIs, disallow VEB mode */
12379 			if (mode == BRIDGE_MODE_VEB)
12380 				pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
12381 			else
12382 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
12383 			i40e_do_reset(pf, I40E_PF_RESET_FLAG, true);
12384 			break;
12385 		}
12386 	}
12387 
12388 	return 0;
12389 }
12390 
12391 /**
12392  * i40e_ndo_bridge_getlink - Get the hardware bridge mode
12393  * @skb: skb buff
12394  * @pid: process id
12395  * @seq: RTNL message seq #
12396  * @dev: the netdev being configured
12397  * @filter_mask: unused
12398  * @nlflags: netlink flags passed in
12399  *
12400  * Return the mode in which the hardware bridge is operating in
12401  * i.e VEB or VEPA.
12402  **/
12403 static int i40e_ndo_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq,
12404 				   struct net_device *dev,
12405 				   u32 __always_unused filter_mask,
12406 				   int nlflags)
12407 {
12408 	struct i40e_netdev_priv *np = netdev_priv(dev);
12409 	struct i40e_vsi *vsi = np->vsi;
12410 	struct i40e_pf *pf = vsi->back;
12411 	struct i40e_veb *veb = NULL;
12412 	int i;
12413 
12414 	/* Only for PF VSI for now */
12415 	if (vsi->seid != pf->vsi[pf->lan_vsi]->seid)
12416 		return -EOPNOTSUPP;
12417 
12418 	/* Find the HW bridge for the PF VSI */
12419 	for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
12420 		if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
12421 			veb = pf->veb[i];
12422 	}
12423 
12424 	if (!veb)
12425 		return 0;
12426 
12427 	return ndo_dflt_bridge_getlink(skb, pid, seq, dev, veb->bridge_mode,
12428 				       0, 0, nlflags, filter_mask, NULL);
12429 }
12430 
12431 /**
12432  * i40e_features_check - Validate encapsulated packet conforms to limits
12433  * @skb: skb buff
12434  * @dev: This physical port's netdev
12435  * @features: Offload features that the stack believes apply
12436  **/
12437 static netdev_features_t i40e_features_check(struct sk_buff *skb,
12438 					     struct net_device *dev,
12439 					     netdev_features_t features)
12440 {
12441 	size_t len;
12442 
12443 	/* No point in doing any of this if neither checksum nor GSO are
12444 	 * being requested for this frame.  We can rule out both by just
12445 	 * checking for CHECKSUM_PARTIAL
12446 	 */
12447 	if (skb->ip_summed != CHECKSUM_PARTIAL)
12448 		return features;
12449 
12450 	/* We cannot support GSO if the MSS is going to be less than
12451 	 * 64 bytes.  If it is then we need to drop support for GSO.
12452 	 */
12453 	if (skb_is_gso(skb) && (skb_shinfo(skb)->gso_size < 64))
12454 		features &= ~NETIF_F_GSO_MASK;
12455 
12456 	/* MACLEN can support at most 63 words */
12457 	len = skb_network_header(skb) - skb->data;
12458 	if (len & ~(63 * 2))
12459 		goto out_err;
12460 
12461 	/* IPLEN and EIPLEN can support at most 127 dwords */
12462 	len = skb_transport_header(skb) - skb_network_header(skb);
12463 	if (len & ~(127 * 4))
12464 		goto out_err;
12465 
12466 	if (skb->encapsulation) {
12467 		/* L4TUNLEN can support 127 words */
12468 		len = skb_inner_network_header(skb) - skb_transport_header(skb);
12469 		if (len & ~(127 * 2))
12470 			goto out_err;
12471 
12472 		/* IPLEN can support at most 127 dwords */
12473 		len = skb_inner_transport_header(skb) -
12474 		      skb_inner_network_header(skb);
12475 		if (len & ~(127 * 4))
12476 			goto out_err;
12477 	}
12478 
12479 	/* No need to validate L4LEN as TCP is the only protocol with a
12480 	 * a flexible value and we support all possible values supported
12481 	 * by TCP, which is at most 15 dwords
12482 	 */
12483 
12484 	return features;
12485 out_err:
12486 	return features & ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
12487 }
12488 
12489 /**
12490  * i40e_xdp_setup - add/remove an XDP program
12491  * @vsi: VSI to changed
12492  * @prog: XDP program
12493  **/
12494 static int i40e_xdp_setup(struct i40e_vsi *vsi,
12495 			  struct bpf_prog *prog)
12496 {
12497 	int frame_size = vsi->netdev->mtu + ETH_HLEN + ETH_FCS_LEN + VLAN_HLEN;
12498 	struct i40e_pf *pf = vsi->back;
12499 	struct bpf_prog *old_prog;
12500 	bool need_reset;
12501 	int i;
12502 
12503 	/* Don't allow frames that span over multiple buffers */
12504 	if (frame_size > vsi->rx_buf_len)
12505 		return -EINVAL;
12506 
12507 	if (!i40e_enabled_xdp_vsi(vsi) && !prog)
12508 		return 0;
12509 
12510 	/* When turning XDP on->off/off->on we reset and rebuild the rings. */
12511 	need_reset = (i40e_enabled_xdp_vsi(vsi) != !!prog);
12512 
12513 	if (need_reset)
12514 		i40e_prep_for_reset(pf, true);
12515 
12516 	old_prog = xchg(&vsi->xdp_prog, prog);
12517 
12518 	if (need_reset)
12519 		i40e_reset_and_rebuild(pf, true, true);
12520 
12521 	for (i = 0; i < vsi->num_queue_pairs; i++)
12522 		WRITE_ONCE(vsi->rx_rings[i]->xdp_prog, vsi->xdp_prog);
12523 
12524 	if (old_prog)
12525 		bpf_prog_put(old_prog);
12526 
12527 	/* Kick start the NAPI context if there is an AF_XDP socket open
12528 	 * on that queue id. This so that receiving will start.
12529 	 */
12530 	if (need_reset && prog)
12531 		for (i = 0; i < vsi->num_queue_pairs; i++)
12532 			if (vsi->xdp_rings[i]->xsk_umem)
12533 				(void)i40e_xsk_wakeup(vsi->netdev, i,
12534 						      XDP_WAKEUP_RX);
12535 
12536 	return 0;
12537 }
12538 
12539 /**
12540  * i40e_enter_busy_conf - Enters busy config state
12541  * @vsi: vsi
12542  *
12543  * Returns 0 on success, <0 for failure.
12544  **/
12545 static int i40e_enter_busy_conf(struct i40e_vsi *vsi)
12546 {
12547 	struct i40e_pf *pf = vsi->back;
12548 	int timeout = 50;
12549 
12550 	while (test_and_set_bit(__I40E_CONFIG_BUSY, pf->state)) {
12551 		timeout--;
12552 		if (!timeout)
12553 			return -EBUSY;
12554 		usleep_range(1000, 2000);
12555 	}
12556 
12557 	return 0;
12558 }
12559 
12560 /**
12561  * i40e_exit_busy_conf - Exits busy config state
12562  * @vsi: vsi
12563  **/
12564 static void i40e_exit_busy_conf(struct i40e_vsi *vsi)
12565 {
12566 	struct i40e_pf *pf = vsi->back;
12567 
12568 	clear_bit(__I40E_CONFIG_BUSY, pf->state);
12569 }
12570 
12571 /**
12572  * i40e_queue_pair_reset_stats - Resets all statistics for a queue pair
12573  * @vsi: vsi
12574  * @queue_pair: queue pair
12575  **/
12576 static void i40e_queue_pair_reset_stats(struct i40e_vsi *vsi, int queue_pair)
12577 {
12578 	memset(&vsi->rx_rings[queue_pair]->rx_stats, 0,
12579 	       sizeof(vsi->rx_rings[queue_pair]->rx_stats));
12580 	memset(&vsi->tx_rings[queue_pair]->stats, 0,
12581 	       sizeof(vsi->tx_rings[queue_pair]->stats));
12582 	if (i40e_enabled_xdp_vsi(vsi)) {
12583 		memset(&vsi->xdp_rings[queue_pair]->stats, 0,
12584 		       sizeof(vsi->xdp_rings[queue_pair]->stats));
12585 	}
12586 }
12587 
12588 /**
12589  * i40e_queue_pair_clean_rings - Cleans all the rings of a queue pair
12590  * @vsi: vsi
12591  * @queue_pair: queue pair
12592  **/
12593 static void i40e_queue_pair_clean_rings(struct i40e_vsi *vsi, int queue_pair)
12594 {
12595 	i40e_clean_tx_ring(vsi->tx_rings[queue_pair]);
12596 	if (i40e_enabled_xdp_vsi(vsi)) {
12597 		/* Make sure that in-progress ndo_xdp_xmit calls are
12598 		 * completed.
12599 		 */
12600 		synchronize_rcu();
12601 		i40e_clean_tx_ring(vsi->xdp_rings[queue_pair]);
12602 	}
12603 	i40e_clean_rx_ring(vsi->rx_rings[queue_pair]);
12604 }
12605 
12606 /**
12607  * i40e_queue_pair_toggle_napi - Enables/disables NAPI for a queue pair
12608  * @vsi: vsi
12609  * @queue_pair: queue pair
12610  * @enable: true for enable, false for disable
12611  **/
12612 static void i40e_queue_pair_toggle_napi(struct i40e_vsi *vsi, int queue_pair,
12613 					bool enable)
12614 {
12615 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
12616 	struct i40e_q_vector *q_vector = rxr->q_vector;
12617 
12618 	if (!vsi->netdev)
12619 		return;
12620 
12621 	/* All rings in a qp belong to the same qvector. */
12622 	if (q_vector->rx.ring || q_vector->tx.ring) {
12623 		if (enable)
12624 			napi_enable(&q_vector->napi);
12625 		else
12626 			napi_disable(&q_vector->napi);
12627 	}
12628 }
12629 
12630 /**
12631  * i40e_queue_pair_toggle_rings - Enables/disables all rings for a queue pair
12632  * @vsi: vsi
12633  * @queue_pair: queue pair
12634  * @enable: true for enable, false for disable
12635  *
12636  * Returns 0 on success, <0 on failure.
12637  **/
12638 static int i40e_queue_pair_toggle_rings(struct i40e_vsi *vsi, int queue_pair,
12639 					bool enable)
12640 {
12641 	struct i40e_pf *pf = vsi->back;
12642 	int pf_q, ret = 0;
12643 
12644 	pf_q = vsi->base_queue + queue_pair;
12645 	ret = i40e_control_wait_tx_q(vsi->seid, pf, pf_q,
12646 				     false /*is xdp*/, enable);
12647 	if (ret) {
12648 		dev_info(&pf->pdev->dev,
12649 			 "VSI seid %d Tx ring %d %sable timeout\n",
12650 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
12651 		return ret;
12652 	}
12653 
12654 	i40e_control_rx_q(pf, pf_q, enable);
12655 	ret = i40e_pf_rxq_wait(pf, pf_q, enable);
12656 	if (ret) {
12657 		dev_info(&pf->pdev->dev,
12658 			 "VSI seid %d Rx ring %d %sable timeout\n",
12659 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
12660 		return ret;
12661 	}
12662 
12663 	/* Due to HW errata, on Rx disable only, the register can
12664 	 * indicate done before it really is. Needs 50ms to be sure
12665 	 */
12666 	if (!enable)
12667 		mdelay(50);
12668 
12669 	if (!i40e_enabled_xdp_vsi(vsi))
12670 		return ret;
12671 
12672 	ret = i40e_control_wait_tx_q(vsi->seid, pf,
12673 				     pf_q + vsi->alloc_queue_pairs,
12674 				     true /*is xdp*/, enable);
12675 	if (ret) {
12676 		dev_info(&pf->pdev->dev,
12677 			 "VSI seid %d XDP Tx ring %d %sable timeout\n",
12678 			 vsi->seid, pf_q, (enable ? "en" : "dis"));
12679 	}
12680 
12681 	return ret;
12682 }
12683 
12684 /**
12685  * i40e_queue_pair_enable_irq - Enables interrupts for a queue pair
12686  * @vsi: vsi
12687  * @queue_pair: queue_pair
12688  **/
12689 static void i40e_queue_pair_enable_irq(struct i40e_vsi *vsi, int queue_pair)
12690 {
12691 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
12692 	struct i40e_pf *pf = vsi->back;
12693 	struct i40e_hw *hw = &pf->hw;
12694 
12695 	/* All rings in a qp belong to the same qvector. */
12696 	if (pf->flags & I40E_FLAG_MSIX_ENABLED)
12697 		i40e_irq_dynamic_enable(vsi, rxr->q_vector->v_idx);
12698 	else
12699 		i40e_irq_dynamic_enable_icr0(pf);
12700 
12701 	i40e_flush(hw);
12702 }
12703 
12704 /**
12705  * i40e_queue_pair_disable_irq - Disables interrupts for a queue pair
12706  * @vsi: vsi
12707  * @queue_pair: queue_pair
12708  **/
12709 static void i40e_queue_pair_disable_irq(struct i40e_vsi *vsi, int queue_pair)
12710 {
12711 	struct i40e_ring *rxr = vsi->rx_rings[queue_pair];
12712 	struct i40e_pf *pf = vsi->back;
12713 	struct i40e_hw *hw = &pf->hw;
12714 
12715 	/* For simplicity, instead of removing the qp interrupt causes
12716 	 * from the interrupt linked list, we simply disable the interrupt, and
12717 	 * leave the list intact.
12718 	 *
12719 	 * All rings in a qp belong to the same qvector.
12720 	 */
12721 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
12722 		u32 intpf = vsi->base_vector + rxr->q_vector->v_idx;
12723 
12724 		wr32(hw, I40E_PFINT_DYN_CTLN(intpf - 1), 0);
12725 		i40e_flush(hw);
12726 		synchronize_irq(pf->msix_entries[intpf].vector);
12727 	} else {
12728 		/* Legacy and MSI mode - this stops all interrupt handling */
12729 		wr32(hw, I40E_PFINT_ICR0_ENA, 0);
12730 		wr32(hw, I40E_PFINT_DYN_CTL0, 0);
12731 		i40e_flush(hw);
12732 		synchronize_irq(pf->pdev->irq);
12733 	}
12734 }
12735 
12736 /**
12737  * i40e_queue_pair_disable - Disables a queue pair
12738  * @vsi: vsi
12739  * @queue_pair: queue pair
12740  *
12741  * Returns 0 on success, <0 on failure.
12742  **/
12743 int i40e_queue_pair_disable(struct i40e_vsi *vsi, int queue_pair)
12744 {
12745 	int err;
12746 
12747 	err = i40e_enter_busy_conf(vsi);
12748 	if (err)
12749 		return err;
12750 
12751 	i40e_queue_pair_disable_irq(vsi, queue_pair);
12752 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, false /* off */);
12753 	i40e_queue_pair_toggle_napi(vsi, queue_pair, false /* off */);
12754 	i40e_queue_pair_clean_rings(vsi, queue_pair);
12755 	i40e_queue_pair_reset_stats(vsi, queue_pair);
12756 
12757 	return err;
12758 }
12759 
12760 /**
12761  * i40e_queue_pair_enable - Enables a queue pair
12762  * @vsi: vsi
12763  * @queue_pair: queue pair
12764  *
12765  * Returns 0 on success, <0 on failure.
12766  **/
12767 int i40e_queue_pair_enable(struct i40e_vsi *vsi, int queue_pair)
12768 {
12769 	int err;
12770 
12771 	err = i40e_configure_tx_ring(vsi->tx_rings[queue_pair]);
12772 	if (err)
12773 		return err;
12774 
12775 	if (i40e_enabled_xdp_vsi(vsi)) {
12776 		err = i40e_configure_tx_ring(vsi->xdp_rings[queue_pair]);
12777 		if (err)
12778 			return err;
12779 	}
12780 
12781 	err = i40e_configure_rx_ring(vsi->rx_rings[queue_pair]);
12782 	if (err)
12783 		return err;
12784 
12785 	err = i40e_queue_pair_toggle_rings(vsi, queue_pair, true /* on */);
12786 	i40e_queue_pair_toggle_napi(vsi, queue_pair, true /* on */);
12787 	i40e_queue_pair_enable_irq(vsi, queue_pair);
12788 
12789 	i40e_exit_busy_conf(vsi);
12790 
12791 	return err;
12792 }
12793 
12794 /**
12795  * i40e_xdp - implements ndo_bpf for i40e
12796  * @dev: netdevice
12797  * @xdp: XDP command
12798  **/
12799 static int i40e_xdp(struct net_device *dev,
12800 		    struct netdev_bpf *xdp)
12801 {
12802 	struct i40e_netdev_priv *np = netdev_priv(dev);
12803 	struct i40e_vsi *vsi = np->vsi;
12804 
12805 	if (vsi->type != I40E_VSI_MAIN)
12806 		return -EINVAL;
12807 
12808 	switch (xdp->command) {
12809 	case XDP_SETUP_PROG:
12810 		return i40e_xdp_setup(vsi, xdp->prog);
12811 	case XDP_QUERY_PROG:
12812 		xdp->prog_id = vsi->xdp_prog ? vsi->xdp_prog->aux->id : 0;
12813 		return 0;
12814 	case XDP_SETUP_XSK_UMEM:
12815 		return i40e_xsk_umem_setup(vsi, xdp->xsk.umem,
12816 					   xdp->xsk.queue_id);
12817 	default:
12818 		return -EINVAL;
12819 	}
12820 }
12821 
12822 static const struct net_device_ops i40e_netdev_ops = {
12823 	.ndo_open		= i40e_open,
12824 	.ndo_stop		= i40e_close,
12825 	.ndo_start_xmit		= i40e_lan_xmit_frame,
12826 	.ndo_get_stats64	= i40e_get_netdev_stats_struct,
12827 	.ndo_set_rx_mode	= i40e_set_rx_mode,
12828 	.ndo_validate_addr	= eth_validate_addr,
12829 	.ndo_set_mac_address	= i40e_set_mac,
12830 	.ndo_change_mtu		= i40e_change_mtu,
12831 	.ndo_do_ioctl		= i40e_ioctl,
12832 	.ndo_tx_timeout		= i40e_tx_timeout,
12833 	.ndo_vlan_rx_add_vid	= i40e_vlan_rx_add_vid,
12834 	.ndo_vlan_rx_kill_vid	= i40e_vlan_rx_kill_vid,
12835 #ifdef CONFIG_NET_POLL_CONTROLLER
12836 	.ndo_poll_controller	= i40e_netpoll,
12837 #endif
12838 	.ndo_setup_tc		= __i40e_setup_tc,
12839 	.ndo_set_features	= i40e_set_features,
12840 	.ndo_set_vf_mac		= i40e_ndo_set_vf_mac,
12841 	.ndo_set_vf_vlan	= i40e_ndo_set_vf_port_vlan,
12842 	.ndo_set_vf_rate	= i40e_ndo_set_vf_bw,
12843 	.ndo_get_vf_config	= i40e_ndo_get_vf_config,
12844 	.ndo_set_vf_link_state	= i40e_ndo_set_vf_link_state,
12845 	.ndo_set_vf_spoofchk	= i40e_ndo_set_vf_spoofchk,
12846 	.ndo_set_vf_trust	= i40e_ndo_set_vf_trust,
12847 	.ndo_udp_tunnel_add	= i40e_udp_tunnel_add,
12848 	.ndo_udp_tunnel_del	= i40e_udp_tunnel_del,
12849 	.ndo_get_phys_port_id	= i40e_get_phys_port_id,
12850 	.ndo_fdb_add		= i40e_ndo_fdb_add,
12851 	.ndo_features_check	= i40e_features_check,
12852 	.ndo_bridge_getlink	= i40e_ndo_bridge_getlink,
12853 	.ndo_bridge_setlink	= i40e_ndo_bridge_setlink,
12854 	.ndo_bpf		= i40e_xdp,
12855 	.ndo_xdp_xmit		= i40e_xdp_xmit,
12856 	.ndo_xsk_wakeup	        = i40e_xsk_wakeup,
12857 	.ndo_dfwd_add_station	= i40e_fwd_add,
12858 	.ndo_dfwd_del_station	= i40e_fwd_del,
12859 };
12860 
12861 /**
12862  * i40e_config_netdev - Setup the netdev flags
12863  * @vsi: the VSI being configured
12864  *
12865  * Returns 0 on success, negative value on failure
12866  **/
12867 static int i40e_config_netdev(struct i40e_vsi *vsi)
12868 {
12869 	struct i40e_pf *pf = vsi->back;
12870 	struct i40e_hw *hw = &pf->hw;
12871 	struct i40e_netdev_priv *np;
12872 	struct net_device *netdev;
12873 	u8 broadcast[ETH_ALEN];
12874 	u8 mac_addr[ETH_ALEN];
12875 	int etherdev_size;
12876 	netdev_features_t hw_enc_features;
12877 	netdev_features_t hw_features;
12878 
12879 	etherdev_size = sizeof(struct i40e_netdev_priv);
12880 	netdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);
12881 	if (!netdev)
12882 		return -ENOMEM;
12883 
12884 	vsi->netdev = netdev;
12885 	np = netdev_priv(netdev);
12886 	np->vsi = vsi;
12887 
12888 	hw_enc_features = NETIF_F_SG			|
12889 			  NETIF_F_IP_CSUM		|
12890 			  NETIF_F_IPV6_CSUM		|
12891 			  NETIF_F_HIGHDMA		|
12892 			  NETIF_F_SOFT_FEATURES		|
12893 			  NETIF_F_TSO			|
12894 			  NETIF_F_TSO_ECN		|
12895 			  NETIF_F_TSO6			|
12896 			  NETIF_F_GSO_GRE		|
12897 			  NETIF_F_GSO_GRE_CSUM		|
12898 			  NETIF_F_GSO_PARTIAL		|
12899 			  NETIF_F_GSO_IPXIP4		|
12900 			  NETIF_F_GSO_IPXIP6		|
12901 			  NETIF_F_GSO_UDP_TUNNEL	|
12902 			  NETIF_F_GSO_UDP_TUNNEL_CSUM	|
12903 			  NETIF_F_SCTP_CRC		|
12904 			  NETIF_F_RXHASH		|
12905 			  NETIF_F_RXCSUM		|
12906 			  0;
12907 
12908 	if (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))
12909 		netdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;
12910 
12911 	netdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;
12912 
12913 	netdev->hw_enc_features |= hw_enc_features;
12914 
12915 	/* record features VLANs can make use of */
12916 	netdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;
12917 
12918 	/* enable macvlan offloads */
12919 	netdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;
12920 
12921 	hw_features = hw_enc_features		|
12922 		      NETIF_F_HW_VLAN_CTAG_TX	|
12923 		      NETIF_F_HW_VLAN_CTAG_RX;
12924 
12925 	if (!(pf->flags & I40E_FLAG_MFP_ENABLED))
12926 		hw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;
12927 
12928 	netdev->hw_features |= hw_features;
12929 
12930 	netdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;
12931 	netdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
12932 
12933 	if (vsi->type == I40E_VSI_MAIN) {
12934 		SET_NETDEV_DEV(netdev, &pf->pdev->dev);
12935 		ether_addr_copy(mac_addr, hw->mac.perm_addr);
12936 		/* The following steps are necessary for two reasons. First,
12937 		 * some older NVM configurations load a default MAC-VLAN
12938 		 * filter that will accept any tagged packet, and we want to
12939 		 * replace this with a normal filter. Additionally, it is
12940 		 * possible our MAC address was provided by the platform using
12941 		 * Open Firmware or similar.
12942 		 *
12943 		 * Thus, we need to remove the default filter and install one
12944 		 * specific to the MAC address.
12945 		 */
12946 		i40e_rm_default_mac_filter(vsi, mac_addr);
12947 		spin_lock_bh(&vsi->mac_filter_hash_lock);
12948 		i40e_add_mac_filter(vsi, mac_addr);
12949 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
12950 	} else {
12951 		/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we
12952 		 * are still limited by IFNAMSIZ, but we're adding 'v%d\0' to
12953 		 * the end, which is 4 bytes long, so force truncation of the
12954 		 * original name by IFNAMSIZ - 4
12955 		 */
12956 		snprintf(netdev->name, IFNAMSIZ, "%.*sv%%d",
12957 			 IFNAMSIZ - 4,
12958 			 pf->vsi[pf->lan_vsi]->netdev->name);
12959 		eth_random_addr(mac_addr);
12960 
12961 		spin_lock_bh(&vsi->mac_filter_hash_lock);
12962 		i40e_add_mac_filter(vsi, mac_addr);
12963 		spin_unlock_bh(&vsi->mac_filter_hash_lock);
12964 	}
12965 
12966 	/* Add the broadcast filter so that we initially will receive
12967 	 * broadcast packets. Note that when a new VLAN is first added the
12968 	 * driver will convert all filters marked I40E_VLAN_ANY into VLAN
12969 	 * specific filters as part of transitioning into "vlan" operation.
12970 	 * When more VLANs are added, the driver will copy each existing MAC
12971 	 * filter and add it for the new VLAN.
12972 	 *
12973 	 * Broadcast filters are handled specially by
12974 	 * i40e_sync_filters_subtask, as the driver must to set the broadcast
12975 	 * promiscuous bit instead of adding this directly as a MAC/VLAN
12976 	 * filter. The subtask will update the correct broadcast promiscuous
12977 	 * bits as VLANs become active or inactive.
12978 	 */
12979 	eth_broadcast_addr(broadcast);
12980 	spin_lock_bh(&vsi->mac_filter_hash_lock);
12981 	i40e_add_mac_filter(vsi, broadcast);
12982 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
12983 
12984 	ether_addr_copy(netdev->dev_addr, mac_addr);
12985 	ether_addr_copy(netdev->perm_addr, mac_addr);
12986 
12987 	/* i40iw_net_event() reads 16 bytes from neigh->primary_key */
12988 	netdev->neigh_priv_len = sizeof(u32) * 4;
12989 
12990 	netdev->priv_flags |= IFF_UNICAST_FLT;
12991 	netdev->priv_flags |= IFF_SUPP_NOFCS;
12992 	/* Setup netdev TC information */
12993 	i40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);
12994 
12995 	netdev->netdev_ops = &i40e_netdev_ops;
12996 	netdev->watchdog_timeo = 5 * HZ;
12997 	i40e_set_ethtool_ops(netdev);
12998 
12999 	/* MTU range: 68 - 9706 */
13000 	netdev->min_mtu = ETH_MIN_MTU;
13001 	netdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;
13002 
13003 	return 0;
13004 }
13005 
13006 /**
13007  * i40e_vsi_delete - Delete a VSI from the switch
13008  * @vsi: the VSI being removed
13009  *
13010  * Returns 0 on success, negative value on failure
13011  **/
13012 static void i40e_vsi_delete(struct i40e_vsi *vsi)
13013 {
13014 	/* remove default VSI is not allowed */
13015 	if (vsi == vsi->back->vsi[vsi->back->lan_vsi])
13016 		return;
13017 
13018 	i40e_aq_delete_element(&vsi->back->hw, vsi->seid, NULL);
13019 }
13020 
13021 /**
13022  * i40e_is_vsi_uplink_mode_veb - Check if the VSI's uplink bridge mode is VEB
13023  * @vsi: the VSI being queried
13024  *
13025  * Returns 1 if HW bridge mode is VEB and return 0 in case of VEPA mode
13026  **/
13027 int i40e_is_vsi_uplink_mode_veb(struct i40e_vsi *vsi)
13028 {
13029 	struct i40e_veb *veb;
13030 	struct i40e_pf *pf = vsi->back;
13031 
13032 	/* Uplink is not a bridge so default to VEB */
13033 	if (vsi->veb_idx >= I40E_MAX_VEB)
13034 		return 1;
13035 
13036 	veb = pf->veb[vsi->veb_idx];
13037 	if (!veb) {
13038 		dev_info(&pf->pdev->dev,
13039 			 "There is no veb associated with the bridge\n");
13040 		return -ENOENT;
13041 	}
13042 
13043 	/* Uplink is a bridge in VEPA mode */
13044 	if (veb->bridge_mode & BRIDGE_MODE_VEPA) {
13045 		return 0;
13046 	} else {
13047 		/* Uplink is a bridge in VEB mode */
13048 		return 1;
13049 	}
13050 
13051 	/* VEPA is now default bridge, so return 0 */
13052 	return 0;
13053 }
13054 
13055 /**
13056  * i40e_add_vsi - Add a VSI to the switch
13057  * @vsi: the VSI being configured
13058  *
13059  * This initializes a VSI context depending on the VSI type to be added and
13060  * passes it down to the add_vsi aq command.
13061  **/
13062 static int i40e_add_vsi(struct i40e_vsi *vsi)
13063 {
13064 	int ret = -ENODEV;
13065 	struct i40e_pf *pf = vsi->back;
13066 	struct i40e_hw *hw = &pf->hw;
13067 	struct i40e_vsi_context ctxt;
13068 	struct i40e_mac_filter *f;
13069 	struct hlist_node *h;
13070 	int bkt;
13071 
13072 	u8 enabled_tc = 0x1; /* TC0 enabled */
13073 	int f_count = 0;
13074 
13075 	memset(&ctxt, 0, sizeof(ctxt));
13076 	switch (vsi->type) {
13077 	case I40E_VSI_MAIN:
13078 		/* The PF's main VSI is already setup as part of the
13079 		 * device initialization, so we'll not bother with
13080 		 * the add_vsi call, but we will retrieve the current
13081 		 * VSI context.
13082 		 */
13083 		ctxt.seid = pf->main_vsi_seid;
13084 		ctxt.pf_num = pf->hw.pf_id;
13085 		ctxt.vf_num = 0;
13086 		ret = i40e_aq_get_vsi_params(&pf->hw, &ctxt, NULL);
13087 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13088 		if (ret) {
13089 			dev_info(&pf->pdev->dev,
13090 				 "couldn't get PF vsi config, err %s aq_err %s\n",
13091 				 i40e_stat_str(&pf->hw, ret),
13092 				 i40e_aq_str(&pf->hw,
13093 					     pf->hw.aq.asq_last_status));
13094 			return -ENOENT;
13095 		}
13096 		vsi->info = ctxt.info;
13097 		vsi->info.valid_sections = 0;
13098 
13099 		vsi->seid = ctxt.seid;
13100 		vsi->id = ctxt.vsi_number;
13101 
13102 		enabled_tc = i40e_pf_get_tc_map(pf);
13103 
13104 		/* Source pruning is enabled by default, so the flag is
13105 		 * negative logic - if it's set, we need to fiddle with
13106 		 * the VSI to disable source pruning.
13107 		 */
13108 		if (pf->flags & I40E_FLAG_SOURCE_PRUNING_DISABLED) {
13109 			memset(&ctxt, 0, sizeof(ctxt));
13110 			ctxt.seid = pf->main_vsi_seid;
13111 			ctxt.pf_num = pf->hw.pf_id;
13112 			ctxt.vf_num = 0;
13113 			ctxt.info.valid_sections |=
13114 				     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13115 			ctxt.info.switch_id =
13116 				   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_LOCAL_LB);
13117 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13118 			if (ret) {
13119 				dev_info(&pf->pdev->dev,
13120 					 "update vsi failed, err %s aq_err %s\n",
13121 					 i40e_stat_str(&pf->hw, ret),
13122 					 i40e_aq_str(&pf->hw,
13123 						     pf->hw.aq.asq_last_status));
13124 				ret = -ENOENT;
13125 				goto err;
13126 			}
13127 		}
13128 
13129 		/* MFP mode setup queue map and update VSI */
13130 		if ((pf->flags & I40E_FLAG_MFP_ENABLED) &&
13131 		    !(pf->hw.func_caps.iscsi)) { /* NIC type PF */
13132 			memset(&ctxt, 0, sizeof(ctxt));
13133 			ctxt.seid = pf->main_vsi_seid;
13134 			ctxt.pf_num = pf->hw.pf_id;
13135 			ctxt.vf_num = 0;
13136 			i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, false);
13137 			ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL);
13138 			if (ret) {
13139 				dev_info(&pf->pdev->dev,
13140 					 "update vsi failed, err %s aq_err %s\n",
13141 					 i40e_stat_str(&pf->hw, ret),
13142 					 i40e_aq_str(&pf->hw,
13143 						    pf->hw.aq.asq_last_status));
13144 				ret = -ENOENT;
13145 				goto err;
13146 			}
13147 			/* update the local VSI info queue map */
13148 			i40e_vsi_update_queue_map(vsi, &ctxt);
13149 			vsi->info.valid_sections = 0;
13150 		} else {
13151 			/* Default/Main VSI is only enabled for TC0
13152 			 * reconfigure it to enable all TCs that are
13153 			 * available on the port in SFP mode.
13154 			 * For MFP case the iSCSI PF would use this
13155 			 * flow to enable LAN+iSCSI TC.
13156 			 */
13157 			ret = i40e_vsi_config_tc(vsi, enabled_tc);
13158 			if (ret) {
13159 				/* Single TC condition is not fatal,
13160 				 * message and continue
13161 				 */
13162 				dev_info(&pf->pdev->dev,
13163 					 "failed to configure TCs for main VSI tc_map 0x%08x, err %s aq_err %s\n",
13164 					 enabled_tc,
13165 					 i40e_stat_str(&pf->hw, ret),
13166 					 i40e_aq_str(&pf->hw,
13167 						    pf->hw.aq.asq_last_status));
13168 			}
13169 		}
13170 		break;
13171 
13172 	case I40E_VSI_FDIR:
13173 		ctxt.pf_num = hw->pf_id;
13174 		ctxt.vf_num = 0;
13175 		ctxt.uplink_seid = vsi->uplink_seid;
13176 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13177 		ctxt.flags = I40E_AQ_VSI_TYPE_PF;
13178 		if ((pf->flags & I40E_FLAG_VEB_MODE_ENABLED) &&
13179 		    (i40e_is_vsi_uplink_mode_veb(vsi))) {
13180 			ctxt.info.valid_sections |=
13181 			     cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13182 			ctxt.info.switch_id =
13183 			   cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13184 		}
13185 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13186 		break;
13187 
13188 	case I40E_VSI_VMDQ2:
13189 		ctxt.pf_num = hw->pf_id;
13190 		ctxt.vf_num = 0;
13191 		ctxt.uplink_seid = vsi->uplink_seid;
13192 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13193 		ctxt.flags = I40E_AQ_VSI_TYPE_VMDQ2;
13194 
13195 		/* This VSI is connected to VEB so the switch_id
13196 		 * should be set to zero by default.
13197 		 */
13198 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13199 			ctxt.info.valid_sections |=
13200 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13201 			ctxt.info.switch_id =
13202 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13203 		}
13204 
13205 		/* Setup the VSI tx/rx queue map for TC0 only for now */
13206 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13207 		break;
13208 
13209 	case I40E_VSI_SRIOV:
13210 		ctxt.pf_num = hw->pf_id;
13211 		ctxt.vf_num = vsi->vf_id + hw->func_caps.vf_base_id;
13212 		ctxt.uplink_seid = vsi->uplink_seid;
13213 		ctxt.connection_type = I40E_AQ_VSI_CONN_TYPE_NORMAL;
13214 		ctxt.flags = I40E_AQ_VSI_TYPE_VF;
13215 
13216 		/* This VSI is connected to VEB so the switch_id
13217 		 * should be set to zero by default.
13218 		 */
13219 		if (i40e_is_vsi_uplink_mode_veb(vsi)) {
13220 			ctxt.info.valid_sections |=
13221 				cpu_to_le16(I40E_AQ_VSI_PROP_SWITCH_VALID);
13222 			ctxt.info.switch_id =
13223 				cpu_to_le16(I40E_AQ_VSI_SW_ID_FLAG_ALLOW_LB);
13224 		}
13225 
13226 		if (vsi->back->flags & I40E_FLAG_IWARP_ENABLED) {
13227 			ctxt.info.valid_sections |=
13228 				cpu_to_le16(I40E_AQ_VSI_PROP_QUEUE_OPT_VALID);
13229 			ctxt.info.queueing_opt_flags |=
13230 				(I40E_AQ_VSI_QUE_OPT_TCP_ENA |
13231 				 I40E_AQ_VSI_QUE_OPT_RSS_LUT_VSI);
13232 		}
13233 
13234 		ctxt.info.valid_sections |= cpu_to_le16(I40E_AQ_VSI_PROP_VLAN_VALID);
13235 		ctxt.info.port_vlan_flags |= I40E_AQ_VSI_PVLAN_MODE_ALL;
13236 		if (pf->vf[vsi->vf_id].spoofchk) {
13237 			ctxt.info.valid_sections |=
13238 				cpu_to_le16(I40E_AQ_VSI_PROP_SECURITY_VALID);
13239 			ctxt.info.sec_flags |=
13240 				(I40E_AQ_VSI_SEC_FLAG_ENABLE_VLAN_CHK |
13241 				 I40E_AQ_VSI_SEC_FLAG_ENABLE_MAC_CHK);
13242 		}
13243 		/* Setup the VSI tx/rx queue map for TC0 only for now */
13244 		i40e_vsi_setup_queue_map(vsi, &ctxt, enabled_tc, true);
13245 		break;
13246 
13247 	case I40E_VSI_IWARP:
13248 		/* send down message to iWARP */
13249 		break;
13250 
13251 	default:
13252 		return -ENODEV;
13253 	}
13254 
13255 	if (vsi->type != I40E_VSI_MAIN) {
13256 		ret = i40e_aq_add_vsi(hw, &ctxt, NULL);
13257 		if (ret) {
13258 			dev_info(&vsi->back->pdev->dev,
13259 				 "add vsi failed, err %s aq_err %s\n",
13260 				 i40e_stat_str(&pf->hw, ret),
13261 				 i40e_aq_str(&pf->hw,
13262 					     pf->hw.aq.asq_last_status));
13263 			ret = -ENOENT;
13264 			goto err;
13265 		}
13266 		vsi->info = ctxt.info;
13267 		vsi->info.valid_sections = 0;
13268 		vsi->seid = ctxt.seid;
13269 		vsi->id = ctxt.vsi_number;
13270 	}
13271 
13272 	vsi->active_filters = 0;
13273 	clear_bit(__I40E_VSI_OVERFLOW_PROMISC, vsi->state);
13274 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13275 	/* If macvlan filters already exist, force them to get loaded */
13276 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist) {
13277 		f->state = I40E_FILTER_NEW;
13278 		f_count++;
13279 	}
13280 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13281 
13282 	if (f_count) {
13283 		vsi->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
13284 		set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
13285 	}
13286 
13287 	/* Update VSI BW information */
13288 	ret = i40e_vsi_get_bw_info(vsi);
13289 	if (ret) {
13290 		dev_info(&pf->pdev->dev,
13291 			 "couldn't get vsi bw info, err %s aq_err %s\n",
13292 			 i40e_stat_str(&pf->hw, ret),
13293 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13294 		/* VSI is already added so not tearing that up */
13295 		ret = 0;
13296 	}
13297 
13298 err:
13299 	return ret;
13300 }
13301 
13302 /**
13303  * i40e_vsi_release - Delete a VSI and free its resources
13304  * @vsi: the VSI being removed
13305  *
13306  * Returns 0 on success or < 0 on error
13307  **/
13308 int i40e_vsi_release(struct i40e_vsi *vsi)
13309 {
13310 	struct i40e_mac_filter *f;
13311 	struct hlist_node *h;
13312 	struct i40e_veb *veb = NULL;
13313 	struct i40e_pf *pf;
13314 	u16 uplink_seid;
13315 	int i, n, bkt;
13316 
13317 	pf = vsi->back;
13318 
13319 	/* release of a VEB-owner or last VSI is not allowed */
13320 	if (vsi->flags & I40E_VSI_FLAG_VEB_OWNER) {
13321 		dev_info(&pf->pdev->dev, "VSI %d has existing VEB %d\n",
13322 			 vsi->seid, vsi->uplink_seid);
13323 		return -ENODEV;
13324 	}
13325 	if (vsi == pf->vsi[pf->lan_vsi] &&
13326 	    !test_bit(__I40E_DOWN, pf->state)) {
13327 		dev_info(&pf->pdev->dev, "Can't remove PF VSI\n");
13328 		return -ENODEV;
13329 	}
13330 
13331 	uplink_seid = vsi->uplink_seid;
13332 	if (vsi->type != I40E_VSI_SRIOV) {
13333 		if (vsi->netdev_registered) {
13334 			vsi->netdev_registered = false;
13335 			if (vsi->netdev) {
13336 				/* results in a call to i40e_close() */
13337 				unregister_netdev(vsi->netdev);
13338 			}
13339 		} else {
13340 			i40e_vsi_close(vsi);
13341 		}
13342 		i40e_vsi_disable_irq(vsi);
13343 	}
13344 
13345 	spin_lock_bh(&vsi->mac_filter_hash_lock);
13346 
13347 	/* clear the sync flag on all filters */
13348 	if (vsi->netdev) {
13349 		__dev_uc_unsync(vsi->netdev, NULL);
13350 		__dev_mc_unsync(vsi->netdev, NULL);
13351 	}
13352 
13353 	/* make sure any remaining filters are marked for deletion */
13354 	hash_for_each_safe(vsi->mac_filter_hash, bkt, h, f, hlist)
13355 		__i40e_del_filter(vsi, f);
13356 
13357 	spin_unlock_bh(&vsi->mac_filter_hash_lock);
13358 
13359 	i40e_sync_vsi_filters(vsi);
13360 
13361 	i40e_vsi_delete(vsi);
13362 	i40e_vsi_free_q_vectors(vsi);
13363 	if (vsi->netdev) {
13364 		free_netdev(vsi->netdev);
13365 		vsi->netdev = NULL;
13366 	}
13367 	i40e_vsi_clear_rings(vsi);
13368 	i40e_vsi_clear(vsi);
13369 
13370 	/* If this was the last thing on the VEB, except for the
13371 	 * controlling VSI, remove the VEB, which puts the controlling
13372 	 * VSI onto the next level down in the switch.
13373 	 *
13374 	 * Well, okay, there's one more exception here: don't remove
13375 	 * the orphan VEBs yet.  We'll wait for an explicit remove request
13376 	 * from up the network stack.
13377 	 */
13378 	for (n = 0, i = 0; i < pf->num_alloc_vsi; i++) {
13379 		if (pf->vsi[i] &&
13380 		    pf->vsi[i]->uplink_seid == uplink_seid &&
13381 		    (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
13382 			n++;      /* count the VSIs */
13383 		}
13384 	}
13385 	for (i = 0; i < I40E_MAX_VEB; i++) {
13386 		if (!pf->veb[i])
13387 			continue;
13388 		if (pf->veb[i]->uplink_seid == uplink_seid)
13389 			n++;     /* count the VEBs */
13390 		if (pf->veb[i]->seid == uplink_seid)
13391 			veb = pf->veb[i];
13392 	}
13393 	if (n == 0 && veb && veb->uplink_seid != 0)
13394 		i40e_veb_release(veb);
13395 
13396 	return 0;
13397 }
13398 
13399 /**
13400  * i40e_vsi_setup_vectors - Set up the q_vectors for the given VSI
13401  * @vsi: ptr to the VSI
13402  *
13403  * This should only be called after i40e_vsi_mem_alloc() which allocates the
13404  * corresponding SW VSI structure and initializes num_queue_pairs for the
13405  * newly allocated VSI.
13406  *
13407  * Returns 0 on success or negative on failure
13408  **/
13409 static int i40e_vsi_setup_vectors(struct i40e_vsi *vsi)
13410 {
13411 	int ret = -ENOENT;
13412 	struct i40e_pf *pf = vsi->back;
13413 
13414 	if (vsi->q_vectors[0]) {
13415 		dev_info(&pf->pdev->dev, "VSI %d has existing q_vectors\n",
13416 			 vsi->seid);
13417 		return -EEXIST;
13418 	}
13419 
13420 	if (vsi->base_vector) {
13421 		dev_info(&pf->pdev->dev, "VSI %d has non-zero base vector %d\n",
13422 			 vsi->seid, vsi->base_vector);
13423 		return -EEXIST;
13424 	}
13425 
13426 	ret = i40e_vsi_alloc_q_vectors(vsi);
13427 	if (ret) {
13428 		dev_info(&pf->pdev->dev,
13429 			 "failed to allocate %d q_vector for VSI %d, ret=%d\n",
13430 			 vsi->num_q_vectors, vsi->seid, ret);
13431 		vsi->num_q_vectors = 0;
13432 		goto vector_setup_out;
13433 	}
13434 
13435 	/* In Legacy mode, we do not have to get any other vector since we
13436 	 * piggyback on the misc/ICR0 for queue interrupts.
13437 	*/
13438 	if (!(pf->flags & I40E_FLAG_MSIX_ENABLED))
13439 		return ret;
13440 	if (vsi->num_q_vectors)
13441 		vsi->base_vector = i40e_get_lump(pf, pf->irq_pile,
13442 						 vsi->num_q_vectors, vsi->idx);
13443 	if (vsi->base_vector < 0) {
13444 		dev_info(&pf->pdev->dev,
13445 			 "failed to get tracking for %d vectors for VSI %d, err=%d\n",
13446 			 vsi->num_q_vectors, vsi->seid, vsi->base_vector);
13447 		i40e_vsi_free_q_vectors(vsi);
13448 		ret = -ENOENT;
13449 		goto vector_setup_out;
13450 	}
13451 
13452 vector_setup_out:
13453 	return ret;
13454 }
13455 
13456 /**
13457  * i40e_vsi_reinit_setup - return and reallocate resources for a VSI
13458  * @vsi: pointer to the vsi.
13459  *
13460  * This re-allocates a vsi's queue resources.
13461  *
13462  * Returns pointer to the successfully allocated and configured VSI sw struct
13463  * on success, otherwise returns NULL on failure.
13464  **/
13465 static struct i40e_vsi *i40e_vsi_reinit_setup(struct i40e_vsi *vsi)
13466 {
13467 	u16 alloc_queue_pairs;
13468 	struct i40e_pf *pf;
13469 	u8 enabled_tc;
13470 	int ret;
13471 
13472 	if (!vsi)
13473 		return NULL;
13474 
13475 	pf = vsi->back;
13476 
13477 	i40e_put_lump(pf->qp_pile, vsi->base_queue, vsi->idx);
13478 	i40e_vsi_clear_rings(vsi);
13479 
13480 	i40e_vsi_free_arrays(vsi, false);
13481 	i40e_set_num_rings_in_vsi(vsi);
13482 	ret = i40e_vsi_alloc_arrays(vsi, false);
13483 	if (ret)
13484 		goto err_vsi;
13485 
13486 	alloc_queue_pairs = vsi->alloc_queue_pairs *
13487 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
13488 
13489 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
13490 	if (ret < 0) {
13491 		dev_info(&pf->pdev->dev,
13492 			 "failed to get tracking for %d queues for VSI %d err %d\n",
13493 			 alloc_queue_pairs, vsi->seid, ret);
13494 		goto err_vsi;
13495 	}
13496 	vsi->base_queue = ret;
13497 
13498 	/* Update the FW view of the VSI. Force a reset of TC and queue
13499 	 * layout configurations.
13500 	 */
13501 	enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
13502 	pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
13503 	pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
13504 	i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
13505 	if (vsi->type == I40E_VSI_MAIN)
13506 		i40e_rm_default_mac_filter(vsi, pf->hw.mac.perm_addr);
13507 
13508 	/* assign it some queues */
13509 	ret = i40e_alloc_rings(vsi);
13510 	if (ret)
13511 		goto err_rings;
13512 
13513 	/* map all of the rings to the q_vectors */
13514 	i40e_vsi_map_rings_to_vectors(vsi);
13515 	return vsi;
13516 
13517 err_rings:
13518 	i40e_vsi_free_q_vectors(vsi);
13519 	if (vsi->netdev_registered) {
13520 		vsi->netdev_registered = false;
13521 		unregister_netdev(vsi->netdev);
13522 		free_netdev(vsi->netdev);
13523 		vsi->netdev = NULL;
13524 	}
13525 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
13526 err_vsi:
13527 	i40e_vsi_clear(vsi);
13528 	return NULL;
13529 }
13530 
13531 /**
13532  * i40e_vsi_setup - Set up a VSI by a given type
13533  * @pf: board private structure
13534  * @type: VSI type
13535  * @uplink_seid: the switch element to link to
13536  * @param1: usage depends upon VSI type. For VF types, indicates VF id
13537  *
13538  * This allocates the sw VSI structure and its queue resources, then add a VSI
13539  * to the identified VEB.
13540  *
13541  * Returns pointer to the successfully allocated and configure VSI sw struct on
13542  * success, otherwise returns NULL on failure.
13543  **/
13544 struct i40e_vsi *i40e_vsi_setup(struct i40e_pf *pf, u8 type,
13545 				u16 uplink_seid, u32 param1)
13546 {
13547 	struct i40e_vsi *vsi = NULL;
13548 	struct i40e_veb *veb = NULL;
13549 	u16 alloc_queue_pairs;
13550 	int ret, i;
13551 	int v_idx;
13552 
13553 	/* The requested uplink_seid must be either
13554 	 *     - the PF's port seid
13555 	 *              no VEB is needed because this is the PF
13556 	 *              or this is a Flow Director special case VSI
13557 	 *     - seid of an existing VEB
13558 	 *     - seid of a VSI that owns an existing VEB
13559 	 *     - seid of a VSI that doesn't own a VEB
13560 	 *              a new VEB is created and the VSI becomes the owner
13561 	 *     - seid of the PF VSI, which is what creates the first VEB
13562 	 *              this is a special case of the previous
13563 	 *
13564 	 * Find which uplink_seid we were given and create a new VEB if needed
13565 	 */
13566 	for (i = 0; i < I40E_MAX_VEB; i++) {
13567 		if (pf->veb[i] && pf->veb[i]->seid == uplink_seid) {
13568 			veb = pf->veb[i];
13569 			break;
13570 		}
13571 	}
13572 
13573 	if (!veb && uplink_seid != pf->mac_seid) {
13574 
13575 		for (i = 0; i < pf->num_alloc_vsi; i++) {
13576 			if (pf->vsi[i] && pf->vsi[i]->seid == uplink_seid) {
13577 				vsi = pf->vsi[i];
13578 				break;
13579 			}
13580 		}
13581 		if (!vsi) {
13582 			dev_info(&pf->pdev->dev, "no such uplink_seid %d\n",
13583 				 uplink_seid);
13584 			return NULL;
13585 		}
13586 
13587 		if (vsi->uplink_seid == pf->mac_seid)
13588 			veb = i40e_veb_setup(pf, 0, pf->mac_seid, vsi->seid,
13589 					     vsi->tc_config.enabled_tc);
13590 		else if ((vsi->flags & I40E_VSI_FLAG_VEB_OWNER) == 0)
13591 			veb = i40e_veb_setup(pf, 0, vsi->uplink_seid, vsi->seid,
13592 					     vsi->tc_config.enabled_tc);
13593 		if (veb) {
13594 			if (vsi->seid != pf->vsi[pf->lan_vsi]->seid) {
13595 				dev_info(&vsi->back->pdev->dev,
13596 					 "New VSI creation error, uplink seid of LAN VSI expected.\n");
13597 				return NULL;
13598 			}
13599 			/* We come up by default in VEPA mode if SRIOV is not
13600 			 * already enabled, in which case we can't force VEPA
13601 			 * mode.
13602 			 */
13603 			if (!(pf->flags & I40E_FLAG_VEB_MODE_ENABLED)) {
13604 				veb->bridge_mode = BRIDGE_MODE_VEPA;
13605 				pf->flags &= ~I40E_FLAG_VEB_MODE_ENABLED;
13606 			}
13607 			i40e_config_bridge_mode(veb);
13608 		}
13609 		for (i = 0; i < I40E_MAX_VEB && !veb; i++) {
13610 			if (pf->veb[i] && pf->veb[i]->seid == vsi->uplink_seid)
13611 				veb = pf->veb[i];
13612 		}
13613 		if (!veb) {
13614 			dev_info(&pf->pdev->dev, "couldn't add VEB\n");
13615 			return NULL;
13616 		}
13617 
13618 		vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
13619 		uplink_seid = veb->seid;
13620 	}
13621 
13622 	/* get vsi sw struct */
13623 	v_idx = i40e_vsi_mem_alloc(pf, type);
13624 	if (v_idx < 0)
13625 		goto err_alloc;
13626 	vsi = pf->vsi[v_idx];
13627 	if (!vsi)
13628 		goto err_alloc;
13629 	vsi->type = type;
13630 	vsi->veb_idx = (veb ? veb->idx : I40E_NO_VEB);
13631 
13632 	if (type == I40E_VSI_MAIN)
13633 		pf->lan_vsi = v_idx;
13634 	else if (type == I40E_VSI_SRIOV)
13635 		vsi->vf_id = param1;
13636 	/* assign it some queues */
13637 	alloc_queue_pairs = vsi->alloc_queue_pairs *
13638 			    (i40e_enabled_xdp_vsi(vsi) ? 2 : 1);
13639 
13640 	ret = i40e_get_lump(pf, pf->qp_pile, alloc_queue_pairs, vsi->idx);
13641 	if (ret < 0) {
13642 		dev_info(&pf->pdev->dev,
13643 			 "failed to get tracking for %d queues for VSI %d err=%d\n",
13644 			 alloc_queue_pairs, vsi->seid, ret);
13645 		goto err_vsi;
13646 	}
13647 	vsi->base_queue = ret;
13648 
13649 	/* get a VSI from the hardware */
13650 	vsi->uplink_seid = uplink_seid;
13651 	ret = i40e_add_vsi(vsi);
13652 	if (ret)
13653 		goto err_vsi;
13654 
13655 	switch (vsi->type) {
13656 	/* setup the netdev if needed */
13657 	case I40E_VSI_MAIN:
13658 	case I40E_VSI_VMDQ2:
13659 		ret = i40e_config_netdev(vsi);
13660 		if (ret)
13661 			goto err_netdev;
13662 		ret = register_netdev(vsi->netdev);
13663 		if (ret)
13664 			goto err_netdev;
13665 		vsi->netdev_registered = true;
13666 		netif_carrier_off(vsi->netdev);
13667 #ifdef CONFIG_I40E_DCB
13668 		/* Setup DCB netlink interface */
13669 		i40e_dcbnl_setup(vsi);
13670 #endif /* CONFIG_I40E_DCB */
13671 		/* fall through */
13672 
13673 	case I40E_VSI_FDIR:
13674 		/* set up vectors and rings if needed */
13675 		ret = i40e_vsi_setup_vectors(vsi);
13676 		if (ret)
13677 			goto err_msix;
13678 
13679 		ret = i40e_alloc_rings(vsi);
13680 		if (ret)
13681 			goto err_rings;
13682 
13683 		/* map all of the rings to the q_vectors */
13684 		i40e_vsi_map_rings_to_vectors(vsi);
13685 
13686 		i40e_vsi_reset_stats(vsi);
13687 		break;
13688 
13689 	default:
13690 		/* no netdev or rings for the other VSI types */
13691 		break;
13692 	}
13693 
13694 	if ((pf->hw_features & I40E_HW_RSS_AQ_CAPABLE) &&
13695 	    (vsi->type == I40E_VSI_VMDQ2)) {
13696 		ret = i40e_vsi_config_rss(vsi);
13697 	}
13698 	return vsi;
13699 
13700 err_rings:
13701 	i40e_vsi_free_q_vectors(vsi);
13702 err_msix:
13703 	if (vsi->netdev_registered) {
13704 		vsi->netdev_registered = false;
13705 		unregister_netdev(vsi->netdev);
13706 		free_netdev(vsi->netdev);
13707 		vsi->netdev = NULL;
13708 	}
13709 err_netdev:
13710 	i40e_aq_delete_element(&pf->hw, vsi->seid, NULL);
13711 err_vsi:
13712 	i40e_vsi_clear(vsi);
13713 err_alloc:
13714 	return NULL;
13715 }
13716 
13717 /**
13718  * i40e_veb_get_bw_info - Query VEB BW information
13719  * @veb: the veb to query
13720  *
13721  * Query the Tx scheduler BW configuration data for given VEB
13722  **/
13723 static int i40e_veb_get_bw_info(struct i40e_veb *veb)
13724 {
13725 	struct i40e_aqc_query_switching_comp_ets_config_resp ets_data;
13726 	struct i40e_aqc_query_switching_comp_bw_config_resp bw_data;
13727 	struct i40e_pf *pf = veb->pf;
13728 	struct i40e_hw *hw = &pf->hw;
13729 	u32 tc_bw_max;
13730 	int ret = 0;
13731 	int i;
13732 
13733 	ret = i40e_aq_query_switch_comp_bw_config(hw, veb->seid,
13734 						  &bw_data, NULL);
13735 	if (ret) {
13736 		dev_info(&pf->pdev->dev,
13737 			 "query veb bw config failed, err %s aq_err %s\n",
13738 			 i40e_stat_str(&pf->hw, ret),
13739 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
13740 		goto out;
13741 	}
13742 
13743 	ret = i40e_aq_query_switch_comp_ets_config(hw, veb->seid,
13744 						   &ets_data, NULL);
13745 	if (ret) {
13746 		dev_info(&pf->pdev->dev,
13747 			 "query veb bw ets config failed, err %s aq_err %s\n",
13748 			 i40e_stat_str(&pf->hw, ret),
13749 			 i40e_aq_str(&pf->hw, hw->aq.asq_last_status));
13750 		goto out;
13751 	}
13752 
13753 	veb->bw_limit = le16_to_cpu(ets_data.port_bw_limit);
13754 	veb->bw_max_quanta = ets_data.tc_bw_max;
13755 	veb->is_abs_credits = bw_data.absolute_credits_enable;
13756 	veb->enabled_tc = ets_data.tc_valid_bits;
13757 	tc_bw_max = le16_to_cpu(bw_data.tc_bw_max[0]) |
13758 		    (le16_to_cpu(bw_data.tc_bw_max[1]) << 16);
13759 	for (i = 0; i < I40E_MAX_TRAFFIC_CLASS; i++) {
13760 		veb->bw_tc_share_credits[i] = bw_data.tc_bw_share_credits[i];
13761 		veb->bw_tc_limit_credits[i] =
13762 					le16_to_cpu(bw_data.tc_bw_limits[i]);
13763 		veb->bw_tc_max_quanta[i] = ((tc_bw_max >> (i*4)) & 0x7);
13764 	}
13765 
13766 out:
13767 	return ret;
13768 }
13769 
13770 /**
13771  * i40e_veb_mem_alloc - Allocates the next available struct veb in the PF
13772  * @pf: board private structure
13773  *
13774  * On error: returns error code (negative)
13775  * On success: returns vsi index in PF (positive)
13776  **/
13777 static int i40e_veb_mem_alloc(struct i40e_pf *pf)
13778 {
13779 	int ret = -ENOENT;
13780 	struct i40e_veb *veb;
13781 	int i;
13782 
13783 	/* Need to protect the allocation of switch elements at the PF level */
13784 	mutex_lock(&pf->switch_mutex);
13785 
13786 	/* VEB list may be fragmented if VEB creation/destruction has
13787 	 * been happening.  We can afford to do a quick scan to look
13788 	 * for any free slots in the list.
13789 	 *
13790 	 * find next empty veb slot, looping back around if necessary
13791 	 */
13792 	i = 0;
13793 	while ((i < I40E_MAX_VEB) && (pf->veb[i] != NULL))
13794 		i++;
13795 	if (i >= I40E_MAX_VEB) {
13796 		ret = -ENOMEM;
13797 		goto err_alloc_veb;  /* out of VEB slots! */
13798 	}
13799 
13800 	veb = kzalloc(sizeof(*veb), GFP_KERNEL);
13801 	if (!veb) {
13802 		ret = -ENOMEM;
13803 		goto err_alloc_veb;
13804 	}
13805 	veb->pf = pf;
13806 	veb->idx = i;
13807 	veb->enabled_tc = 1;
13808 
13809 	pf->veb[i] = veb;
13810 	ret = i;
13811 err_alloc_veb:
13812 	mutex_unlock(&pf->switch_mutex);
13813 	return ret;
13814 }
13815 
13816 /**
13817  * i40e_switch_branch_release - Delete a branch of the switch tree
13818  * @branch: where to start deleting
13819  *
13820  * This uses recursion to find the tips of the branch to be
13821  * removed, deleting until we get back to and can delete this VEB.
13822  **/
13823 static void i40e_switch_branch_release(struct i40e_veb *branch)
13824 {
13825 	struct i40e_pf *pf = branch->pf;
13826 	u16 branch_seid = branch->seid;
13827 	u16 veb_idx = branch->idx;
13828 	int i;
13829 
13830 	/* release any VEBs on this VEB - RECURSION */
13831 	for (i = 0; i < I40E_MAX_VEB; i++) {
13832 		if (!pf->veb[i])
13833 			continue;
13834 		if (pf->veb[i]->uplink_seid == branch->seid)
13835 			i40e_switch_branch_release(pf->veb[i]);
13836 	}
13837 
13838 	/* Release the VSIs on this VEB, but not the owner VSI.
13839 	 *
13840 	 * NOTE: Removing the last VSI on a VEB has the SIDE EFFECT of removing
13841 	 *       the VEB itself, so don't use (*branch) after this loop.
13842 	 */
13843 	for (i = 0; i < pf->num_alloc_vsi; i++) {
13844 		if (!pf->vsi[i])
13845 			continue;
13846 		if (pf->vsi[i]->uplink_seid == branch_seid &&
13847 		   (pf->vsi[i]->flags & I40E_VSI_FLAG_VEB_OWNER) == 0) {
13848 			i40e_vsi_release(pf->vsi[i]);
13849 		}
13850 	}
13851 
13852 	/* There's one corner case where the VEB might not have been
13853 	 * removed, so double check it here and remove it if needed.
13854 	 * This case happens if the veb was created from the debugfs
13855 	 * commands and no VSIs were added to it.
13856 	 */
13857 	if (pf->veb[veb_idx])
13858 		i40e_veb_release(pf->veb[veb_idx]);
13859 }
13860 
13861 /**
13862  * i40e_veb_clear - remove veb struct
13863  * @veb: the veb to remove
13864  **/
13865 static void i40e_veb_clear(struct i40e_veb *veb)
13866 {
13867 	if (!veb)
13868 		return;
13869 
13870 	if (veb->pf) {
13871 		struct i40e_pf *pf = veb->pf;
13872 
13873 		mutex_lock(&pf->switch_mutex);
13874 		if (pf->veb[veb->idx] == veb)
13875 			pf->veb[veb->idx] = NULL;
13876 		mutex_unlock(&pf->switch_mutex);
13877 	}
13878 
13879 	kfree(veb);
13880 }
13881 
13882 /**
13883  * i40e_veb_release - Delete a VEB and free its resources
13884  * @veb: the VEB being removed
13885  **/
13886 void i40e_veb_release(struct i40e_veb *veb)
13887 {
13888 	struct i40e_vsi *vsi = NULL;
13889 	struct i40e_pf *pf;
13890 	int i, n = 0;
13891 
13892 	pf = veb->pf;
13893 
13894 	/* find the remaining VSI and check for extras */
13895 	for (i = 0; i < pf->num_alloc_vsi; i++) {
13896 		if (pf->vsi[i] && pf->vsi[i]->uplink_seid == veb->seid) {
13897 			n++;
13898 			vsi = pf->vsi[i];
13899 		}
13900 	}
13901 	if (n != 1) {
13902 		dev_info(&pf->pdev->dev,
13903 			 "can't remove VEB %d with %d VSIs left\n",
13904 			 veb->seid, n);
13905 		return;
13906 	}
13907 
13908 	/* move the remaining VSI to uplink veb */
13909 	vsi->flags &= ~I40E_VSI_FLAG_VEB_OWNER;
13910 	if (veb->uplink_seid) {
13911 		vsi->uplink_seid = veb->uplink_seid;
13912 		if (veb->uplink_seid == pf->mac_seid)
13913 			vsi->veb_idx = I40E_NO_VEB;
13914 		else
13915 			vsi->veb_idx = veb->veb_idx;
13916 	} else {
13917 		/* floating VEB */
13918 		vsi->uplink_seid = pf->vsi[pf->lan_vsi]->uplink_seid;
13919 		vsi->veb_idx = pf->vsi[pf->lan_vsi]->veb_idx;
13920 	}
13921 
13922 	i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
13923 	i40e_veb_clear(veb);
13924 }
13925 
13926 /**
13927  * i40e_add_veb - create the VEB in the switch
13928  * @veb: the VEB to be instantiated
13929  * @vsi: the controlling VSI
13930  **/
13931 static int i40e_add_veb(struct i40e_veb *veb, struct i40e_vsi *vsi)
13932 {
13933 	struct i40e_pf *pf = veb->pf;
13934 	bool enable_stats = !!(pf->flags & I40E_FLAG_VEB_STATS_ENABLED);
13935 	int ret;
13936 
13937 	ret = i40e_aq_add_veb(&pf->hw, veb->uplink_seid, vsi->seid,
13938 			      veb->enabled_tc, false,
13939 			      &veb->seid, enable_stats, NULL);
13940 
13941 	/* get a VEB from the hardware */
13942 	if (ret) {
13943 		dev_info(&pf->pdev->dev,
13944 			 "couldn't add VEB, err %s aq_err %s\n",
13945 			 i40e_stat_str(&pf->hw, ret),
13946 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13947 		return -EPERM;
13948 	}
13949 
13950 	/* get statistics counter */
13951 	ret = i40e_aq_get_veb_parameters(&pf->hw, veb->seid, NULL, NULL,
13952 					 &veb->stats_idx, NULL, NULL, NULL);
13953 	if (ret) {
13954 		dev_info(&pf->pdev->dev,
13955 			 "couldn't get VEB statistics idx, err %s aq_err %s\n",
13956 			 i40e_stat_str(&pf->hw, ret),
13957 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13958 		return -EPERM;
13959 	}
13960 	ret = i40e_veb_get_bw_info(veb);
13961 	if (ret) {
13962 		dev_info(&pf->pdev->dev,
13963 			 "couldn't get VEB bw info, err %s aq_err %s\n",
13964 			 i40e_stat_str(&pf->hw, ret),
13965 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
13966 		i40e_aq_delete_element(&pf->hw, veb->seid, NULL);
13967 		return -ENOENT;
13968 	}
13969 
13970 	vsi->uplink_seid = veb->seid;
13971 	vsi->veb_idx = veb->idx;
13972 	vsi->flags |= I40E_VSI_FLAG_VEB_OWNER;
13973 
13974 	return 0;
13975 }
13976 
13977 /**
13978  * i40e_veb_setup - Set up a VEB
13979  * @pf: board private structure
13980  * @flags: VEB setup flags
13981  * @uplink_seid: the switch element to link to
13982  * @vsi_seid: the initial VSI seid
13983  * @enabled_tc: Enabled TC bit-map
13984  *
13985  * This allocates the sw VEB structure and links it into the switch
13986  * It is possible and legal for this to be a duplicate of an already
13987  * existing VEB.  It is also possible for both uplink and vsi seids
13988  * to be zero, in order to create a floating VEB.
13989  *
13990  * Returns pointer to the successfully allocated VEB sw struct on
13991  * success, otherwise returns NULL on failure.
13992  **/
13993 struct i40e_veb *i40e_veb_setup(struct i40e_pf *pf, u16 flags,
13994 				u16 uplink_seid, u16 vsi_seid,
13995 				u8 enabled_tc)
13996 {
13997 	struct i40e_veb *veb, *uplink_veb = NULL;
13998 	int vsi_idx, veb_idx;
13999 	int ret;
14000 
14001 	/* if one seid is 0, the other must be 0 to create a floating relay */
14002 	if ((uplink_seid == 0 || vsi_seid == 0) &&
14003 	    (uplink_seid + vsi_seid != 0)) {
14004 		dev_info(&pf->pdev->dev,
14005 			 "one, not both seid's are 0: uplink=%d vsi=%d\n",
14006 			 uplink_seid, vsi_seid);
14007 		return NULL;
14008 	}
14009 
14010 	/* make sure there is such a vsi and uplink */
14011 	for (vsi_idx = 0; vsi_idx < pf->num_alloc_vsi; vsi_idx++)
14012 		if (pf->vsi[vsi_idx] && pf->vsi[vsi_idx]->seid == vsi_seid)
14013 			break;
14014 	if (vsi_idx == pf->num_alloc_vsi && vsi_seid != 0) {
14015 		dev_info(&pf->pdev->dev, "vsi seid %d not found\n",
14016 			 vsi_seid);
14017 		return NULL;
14018 	}
14019 
14020 	if (uplink_seid && uplink_seid != pf->mac_seid) {
14021 		for (veb_idx = 0; veb_idx < I40E_MAX_VEB; veb_idx++) {
14022 			if (pf->veb[veb_idx] &&
14023 			    pf->veb[veb_idx]->seid == uplink_seid) {
14024 				uplink_veb = pf->veb[veb_idx];
14025 				break;
14026 			}
14027 		}
14028 		if (!uplink_veb) {
14029 			dev_info(&pf->pdev->dev,
14030 				 "uplink seid %d not found\n", uplink_seid);
14031 			return NULL;
14032 		}
14033 	}
14034 
14035 	/* get veb sw struct */
14036 	veb_idx = i40e_veb_mem_alloc(pf);
14037 	if (veb_idx < 0)
14038 		goto err_alloc;
14039 	veb = pf->veb[veb_idx];
14040 	veb->flags = flags;
14041 	veb->uplink_seid = uplink_seid;
14042 	veb->veb_idx = (uplink_veb ? uplink_veb->idx : I40E_NO_VEB);
14043 	veb->enabled_tc = (enabled_tc ? enabled_tc : 0x1);
14044 
14045 	/* create the VEB in the switch */
14046 	ret = i40e_add_veb(veb, pf->vsi[vsi_idx]);
14047 	if (ret)
14048 		goto err_veb;
14049 	if (vsi_idx == pf->lan_vsi)
14050 		pf->lan_veb = veb->idx;
14051 
14052 	return veb;
14053 
14054 err_veb:
14055 	i40e_veb_clear(veb);
14056 err_alloc:
14057 	return NULL;
14058 }
14059 
14060 /**
14061  * i40e_setup_pf_switch_element - set PF vars based on switch type
14062  * @pf: board private structure
14063  * @ele: element we are building info from
14064  * @num_reported: total number of elements
14065  * @printconfig: should we print the contents
14066  *
14067  * helper function to assist in extracting a few useful SEID values.
14068  **/
14069 static void i40e_setup_pf_switch_element(struct i40e_pf *pf,
14070 				struct i40e_aqc_switch_config_element_resp *ele,
14071 				u16 num_reported, bool printconfig)
14072 {
14073 	u16 downlink_seid = le16_to_cpu(ele->downlink_seid);
14074 	u16 uplink_seid = le16_to_cpu(ele->uplink_seid);
14075 	u8 element_type = ele->element_type;
14076 	u16 seid = le16_to_cpu(ele->seid);
14077 
14078 	if (printconfig)
14079 		dev_info(&pf->pdev->dev,
14080 			 "type=%d seid=%d uplink=%d downlink=%d\n",
14081 			 element_type, seid, uplink_seid, downlink_seid);
14082 
14083 	switch (element_type) {
14084 	case I40E_SWITCH_ELEMENT_TYPE_MAC:
14085 		pf->mac_seid = seid;
14086 		break;
14087 	case I40E_SWITCH_ELEMENT_TYPE_VEB:
14088 		/* Main VEB? */
14089 		if (uplink_seid != pf->mac_seid)
14090 			break;
14091 		if (pf->lan_veb >= I40E_MAX_VEB) {
14092 			int v;
14093 
14094 			/* find existing or else empty VEB */
14095 			for (v = 0; v < I40E_MAX_VEB; v++) {
14096 				if (pf->veb[v] && (pf->veb[v]->seid == seid)) {
14097 					pf->lan_veb = v;
14098 					break;
14099 				}
14100 			}
14101 			if (pf->lan_veb >= I40E_MAX_VEB) {
14102 				v = i40e_veb_mem_alloc(pf);
14103 				if (v < 0)
14104 					break;
14105 				pf->lan_veb = v;
14106 			}
14107 		}
14108 		if (pf->lan_veb >= I40E_MAX_VEB)
14109 			break;
14110 
14111 		pf->veb[pf->lan_veb]->seid = seid;
14112 		pf->veb[pf->lan_veb]->uplink_seid = pf->mac_seid;
14113 		pf->veb[pf->lan_veb]->pf = pf;
14114 		pf->veb[pf->lan_veb]->veb_idx = I40E_NO_VEB;
14115 		break;
14116 	case I40E_SWITCH_ELEMENT_TYPE_VSI:
14117 		if (num_reported != 1)
14118 			break;
14119 		/* This is immediately after a reset so we can assume this is
14120 		 * the PF's VSI
14121 		 */
14122 		pf->mac_seid = uplink_seid;
14123 		pf->pf_seid = downlink_seid;
14124 		pf->main_vsi_seid = seid;
14125 		if (printconfig)
14126 			dev_info(&pf->pdev->dev,
14127 				 "pf_seid=%d main_vsi_seid=%d\n",
14128 				 pf->pf_seid, pf->main_vsi_seid);
14129 		break;
14130 	case I40E_SWITCH_ELEMENT_TYPE_PF:
14131 	case I40E_SWITCH_ELEMENT_TYPE_VF:
14132 	case I40E_SWITCH_ELEMENT_TYPE_EMP:
14133 	case I40E_SWITCH_ELEMENT_TYPE_BMC:
14134 	case I40E_SWITCH_ELEMENT_TYPE_PE:
14135 	case I40E_SWITCH_ELEMENT_TYPE_PA:
14136 		/* ignore these for now */
14137 		break;
14138 	default:
14139 		dev_info(&pf->pdev->dev, "unknown element type=%d seid=%d\n",
14140 			 element_type, seid);
14141 		break;
14142 	}
14143 }
14144 
14145 /**
14146  * i40e_fetch_switch_configuration - Get switch config from firmware
14147  * @pf: board private structure
14148  * @printconfig: should we print the contents
14149  *
14150  * Get the current switch configuration from the device and
14151  * extract a few useful SEID values.
14152  **/
14153 int i40e_fetch_switch_configuration(struct i40e_pf *pf, bool printconfig)
14154 {
14155 	struct i40e_aqc_get_switch_config_resp *sw_config;
14156 	u16 next_seid = 0;
14157 	int ret = 0;
14158 	u8 *aq_buf;
14159 	int i;
14160 
14161 	aq_buf = kzalloc(I40E_AQ_LARGE_BUF, GFP_KERNEL);
14162 	if (!aq_buf)
14163 		return -ENOMEM;
14164 
14165 	sw_config = (struct i40e_aqc_get_switch_config_resp *)aq_buf;
14166 	do {
14167 		u16 num_reported, num_total;
14168 
14169 		ret = i40e_aq_get_switch_config(&pf->hw, sw_config,
14170 						I40E_AQ_LARGE_BUF,
14171 						&next_seid, NULL);
14172 		if (ret) {
14173 			dev_info(&pf->pdev->dev,
14174 				 "get switch config failed err %s aq_err %s\n",
14175 				 i40e_stat_str(&pf->hw, ret),
14176 				 i40e_aq_str(&pf->hw,
14177 					     pf->hw.aq.asq_last_status));
14178 			kfree(aq_buf);
14179 			return -ENOENT;
14180 		}
14181 
14182 		num_reported = le16_to_cpu(sw_config->header.num_reported);
14183 		num_total = le16_to_cpu(sw_config->header.num_total);
14184 
14185 		if (printconfig)
14186 			dev_info(&pf->pdev->dev,
14187 				 "header: %d reported %d total\n",
14188 				 num_reported, num_total);
14189 
14190 		for (i = 0; i < num_reported; i++) {
14191 			struct i40e_aqc_switch_config_element_resp *ele =
14192 				&sw_config->element[i];
14193 
14194 			i40e_setup_pf_switch_element(pf, ele, num_reported,
14195 						     printconfig);
14196 		}
14197 	} while (next_seid != 0);
14198 
14199 	kfree(aq_buf);
14200 	return ret;
14201 }
14202 
14203 /**
14204  * i40e_setup_pf_switch - Setup the HW switch on startup or after reset
14205  * @pf: board private structure
14206  * @reinit: if the Main VSI needs to re-initialized.
14207  *
14208  * Returns 0 on success, negative value on failure
14209  **/
14210 static int i40e_setup_pf_switch(struct i40e_pf *pf, bool reinit)
14211 {
14212 	u16 flags = 0;
14213 	int ret;
14214 
14215 	/* find out what's out there already */
14216 	ret = i40e_fetch_switch_configuration(pf, false);
14217 	if (ret) {
14218 		dev_info(&pf->pdev->dev,
14219 			 "couldn't fetch switch config, err %s aq_err %s\n",
14220 			 i40e_stat_str(&pf->hw, ret),
14221 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
14222 		return ret;
14223 	}
14224 	i40e_pf_reset_stats(pf);
14225 
14226 	/* set the switch config bit for the whole device to
14227 	 * support limited promisc or true promisc
14228 	 * when user requests promisc. The default is limited
14229 	 * promisc.
14230 	*/
14231 
14232 	if ((pf->hw.pf_id == 0) &&
14233 	    !(pf->flags & I40E_FLAG_TRUE_PROMISC_SUPPORT)) {
14234 		flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14235 		pf->last_sw_conf_flags = flags;
14236 	}
14237 
14238 	if (pf->hw.pf_id == 0) {
14239 		u16 valid_flags;
14240 
14241 		valid_flags = I40E_AQ_SET_SWITCH_CFG_PROMISC;
14242 		ret = i40e_aq_set_switch_config(&pf->hw, flags, valid_flags, 0,
14243 						NULL);
14244 		if (ret && pf->hw.aq.asq_last_status != I40E_AQ_RC_ESRCH) {
14245 			dev_info(&pf->pdev->dev,
14246 				 "couldn't set switch config bits, err %s aq_err %s\n",
14247 				 i40e_stat_str(&pf->hw, ret),
14248 				 i40e_aq_str(&pf->hw,
14249 					     pf->hw.aq.asq_last_status));
14250 			/* not a fatal problem, just keep going */
14251 		}
14252 		pf->last_sw_conf_valid_flags = valid_flags;
14253 	}
14254 
14255 	/* first time setup */
14256 	if (pf->lan_vsi == I40E_NO_VSI || reinit) {
14257 		struct i40e_vsi *vsi = NULL;
14258 		u16 uplink_seid;
14259 
14260 		/* Set up the PF VSI associated with the PF's main VSI
14261 		 * that is already in the HW switch
14262 		 */
14263 		if (pf->lan_veb < I40E_MAX_VEB && pf->veb[pf->lan_veb])
14264 			uplink_seid = pf->veb[pf->lan_veb]->seid;
14265 		else
14266 			uplink_seid = pf->mac_seid;
14267 		if (pf->lan_vsi == I40E_NO_VSI)
14268 			vsi = i40e_vsi_setup(pf, I40E_VSI_MAIN, uplink_seid, 0);
14269 		else if (reinit)
14270 			vsi = i40e_vsi_reinit_setup(pf->vsi[pf->lan_vsi]);
14271 		if (!vsi) {
14272 			dev_info(&pf->pdev->dev, "setup of MAIN VSI failed\n");
14273 			i40e_cloud_filter_exit(pf);
14274 			i40e_fdir_teardown(pf);
14275 			return -EAGAIN;
14276 		}
14277 	} else {
14278 		/* force a reset of TC and queue layout configurations */
14279 		u8 enabled_tc = pf->vsi[pf->lan_vsi]->tc_config.enabled_tc;
14280 
14281 		pf->vsi[pf->lan_vsi]->tc_config.enabled_tc = 0;
14282 		pf->vsi[pf->lan_vsi]->seid = pf->main_vsi_seid;
14283 		i40e_vsi_config_tc(pf->vsi[pf->lan_vsi], enabled_tc);
14284 	}
14285 	i40e_vlan_stripping_disable(pf->vsi[pf->lan_vsi]);
14286 
14287 	i40e_fdir_sb_setup(pf);
14288 
14289 	/* Setup static PF queue filter control settings */
14290 	ret = i40e_setup_pf_filter_control(pf);
14291 	if (ret) {
14292 		dev_info(&pf->pdev->dev, "setup_pf_filter_control failed: %d\n",
14293 			 ret);
14294 		/* Failure here should not stop continuing other steps */
14295 	}
14296 
14297 	/* enable RSS in the HW, even for only one queue, as the stack can use
14298 	 * the hash
14299 	 */
14300 	if ((pf->flags & I40E_FLAG_RSS_ENABLED))
14301 		i40e_pf_config_rss(pf);
14302 
14303 	/* fill in link information and enable LSE reporting */
14304 	i40e_link_event(pf);
14305 
14306 	/* Initialize user-specific link properties */
14307 	pf->fc_autoneg_status = ((pf->hw.phy.link_info.an_info &
14308 				  I40E_AQ_AN_COMPLETED) ? true : false);
14309 
14310 	i40e_ptp_init(pf);
14311 
14312 	/* repopulate tunnel port filters */
14313 	i40e_sync_udp_filters(pf);
14314 
14315 	return ret;
14316 }
14317 
14318 /**
14319  * i40e_determine_queue_usage - Work out queue distribution
14320  * @pf: board private structure
14321  **/
14322 static void i40e_determine_queue_usage(struct i40e_pf *pf)
14323 {
14324 	int queues_left;
14325 	int q_max;
14326 
14327 	pf->num_lan_qps = 0;
14328 
14329 	/* Find the max queues to be put into basic use.  We'll always be
14330 	 * using TC0, whether or not DCB is running, and TC0 will get the
14331 	 * big RSS set.
14332 	 */
14333 	queues_left = pf->hw.func_caps.num_tx_qp;
14334 
14335 	if ((queues_left == 1) ||
14336 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED)) {
14337 		/* one qp for PF, no queues for anything else */
14338 		queues_left = 0;
14339 		pf->alloc_rss_size = pf->num_lan_qps = 1;
14340 
14341 		/* make sure all the fancies are disabled */
14342 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
14343 			       I40E_FLAG_IWARP_ENABLED	|
14344 			       I40E_FLAG_FD_SB_ENABLED	|
14345 			       I40E_FLAG_FD_ATR_ENABLED	|
14346 			       I40E_FLAG_DCB_CAPABLE	|
14347 			       I40E_FLAG_DCB_ENABLED	|
14348 			       I40E_FLAG_SRIOV_ENABLED	|
14349 			       I40E_FLAG_VMDQ_ENABLED);
14350 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
14351 	} else if (!(pf->flags & (I40E_FLAG_RSS_ENABLED |
14352 				  I40E_FLAG_FD_SB_ENABLED |
14353 				  I40E_FLAG_FD_ATR_ENABLED |
14354 				  I40E_FLAG_DCB_CAPABLE))) {
14355 		/* one qp for PF */
14356 		pf->alloc_rss_size = pf->num_lan_qps = 1;
14357 		queues_left -= pf->num_lan_qps;
14358 
14359 		pf->flags &= ~(I40E_FLAG_RSS_ENABLED	|
14360 			       I40E_FLAG_IWARP_ENABLED	|
14361 			       I40E_FLAG_FD_SB_ENABLED	|
14362 			       I40E_FLAG_FD_ATR_ENABLED	|
14363 			       I40E_FLAG_DCB_ENABLED	|
14364 			       I40E_FLAG_VMDQ_ENABLED);
14365 		pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
14366 	} else {
14367 		/* Not enough queues for all TCs */
14368 		if ((pf->flags & I40E_FLAG_DCB_CAPABLE) &&
14369 		    (queues_left < I40E_MAX_TRAFFIC_CLASS)) {
14370 			pf->flags &= ~(I40E_FLAG_DCB_CAPABLE |
14371 					I40E_FLAG_DCB_ENABLED);
14372 			dev_info(&pf->pdev->dev, "not enough queues for DCB. DCB is disabled.\n");
14373 		}
14374 
14375 		/* limit lan qps to the smaller of qps, cpus or msix */
14376 		q_max = max_t(int, pf->rss_size_max, num_online_cpus());
14377 		q_max = min_t(int, q_max, pf->hw.func_caps.num_tx_qp);
14378 		q_max = min_t(int, q_max, pf->hw.func_caps.num_msix_vectors);
14379 		pf->num_lan_qps = q_max;
14380 
14381 		queues_left -= pf->num_lan_qps;
14382 	}
14383 
14384 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
14385 		if (queues_left > 1) {
14386 			queues_left -= 1; /* save 1 queue for FD */
14387 		} else {
14388 			pf->flags &= ~I40E_FLAG_FD_SB_ENABLED;
14389 			pf->flags |= I40E_FLAG_FD_SB_INACTIVE;
14390 			dev_info(&pf->pdev->dev, "not enough queues for Flow Director. Flow Director feature is disabled\n");
14391 		}
14392 	}
14393 
14394 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
14395 	    pf->num_vf_qps && pf->num_req_vfs && queues_left) {
14396 		pf->num_req_vfs = min_t(int, pf->num_req_vfs,
14397 					(queues_left / pf->num_vf_qps));
14398 		queues_left -= (pf->num_req_vfs * pf->num_vf_qps);
14399 	}
14400 
14401 	if ((pf->flags & I40E_FLAG_VMDQ_ENABLED) &&
14402 	    pf->num_vmdq_vsis && pf->num_vmdq_qps && queues_left) {
14403 		pf->num_vmdq_vsis = min_t(int, pf->num_vmdq_vsis,
14404 					  (queues_left / pf->num_vmdq_qps));
14405 		queues_left -= (pf->num_vmdq_vsis * pf->num_vmdq_qps);
14406 	}
14407 
14408 	pf->queues_left = queues_left;
14409 	dev_dbg(&pf->pdev->dev,
14410 		"qs_avail=%d FD SB=%d lan_qs=%d lan_tc0=%d vf=%d*%d vmdq=%d*%d, remaining=%d\n",
14411 		pf->hw.func_caps.num_tx_qp,
14412 		!!(pf->flags & I40E_FLAG_FD_SB_ENABLED),
14413 		pf->num_lan_qps, pf->alloc_rss_size, pf->num_req_vfs,
14414 		pf->num_vf_qps, pf->num_vmdq_vsis, pf->num_vmdq_qps,
14415 		queues_left);
14416 }
14417 
14418 /**
14419  * i40e_setup_pf_filter_control - Setup PF static filter control
14420  * @pf: PF to be setup
14421  *
14422  * i40e_setup_pf_filter_control sets up a PF's initial filter control
14423  * settings. If PE/FCoE are enabled then it will also set the per PF
14424  * based filter sizes required for them. It also enables Flow director,
14425  * ethertype and macvlan type filter settings for the pf.
14426  *
14427  * Returns 0 on success, negative on failure
14428  **/
14429 static int i40e_setup_pf_filter_control(struct i40e_pf *pf)
14430 {
14431 	struct i40e_filter_control_settings *settings = &pf->filter_settings;
14432 
14433 	settings->hash_lut_size = I40E_HASH_LUT_SIZE_128;
14434 
14435 	/* Flow Director is enabled */
14436 	if (pf->flags & (I40E_FLAG_FD_SB_ENABLED | I40E_FLAG_FD_ATR_ENABLED))
14437 		settings->enable_fdir = true;
14438 
14439 	/* Ethtype and MACVLAN filters enabled for PF */
14440 	settings->enable_ethtype = true;
14441 	settings->enable_macvlan = true;
14442 
14443 	if (i40e_set_filter_control(&pf->hw, settings))
14444 		return -ENOENT;
14445 
14446 	return 0;
14447 }
14448 
14449 #define INFO_STRING_LEN 255
14450 #define REMAIN(__x) (INFO_STRING_LEN - (__x))
14451 static void i40e_print_features(struct i40e_pf *pf)
14452 {
14453 	struct i40e_hw *hw = &pf->hw;
14454 	char *buf;
14455 	int i;
14456 
14457 	buf = kmalloc(INFO_STRING_LEN, GFP_KERNEL);
14458 	if (!buf)
14459 		return;
14460 
14461 	i = snprintf(buf, INFO_STRING_LEN, "Features: PF-id[%d]", hw->pf_id);
14462 #ifdef CONFIG_PCI_IOV
14463 	i += snprintf(&buf[i], REMAIN(i), " VFs: %d", pf->num_req_vfs);
14464 #endif
14465 	i += snprintf(&buf[i], REMAIN(i), " VSIs: %d QP: %d",
14466 		      pf->hw.func_caps.num_vsis,
14467 		      pf->vsi[pf->lan_vsi]->num_queue_pairs);
14468 	if (pf->flags & I40E_FLAG_RSS_ENABLED)
14469 		i += snprintf(&buf[i], REMAIN(i), " RSS");
14470 	if (pf->flags & I40E_FLAG_FD_ATR_ENABLED)
14471 		i += snprintf(&buf[i], REMAIN(i), " FD_ATR");
14472 	if (pf->flags & I40E_FLAG_FD_SB_ENABLED) {
14473 		i += snprintf(&buf[i], REMAIN(i), " FD_SB");
14474 		i += snprintf(&buf[i], REMAIN(i), " NTUPLE");
14475 	}
14476 	if (pf->flags & I40E_FLAG_DCB_CAPABLE)
14477 		i += snprintf(&buf[i], REMAIN(i), " DCB");
14478 	i += snprintf(&buf[i], REMAIN(i), " VxLAN");
14479 	i += snprintf(&buf[i], REMAIN(i), " Geneve");
14480 	if (pf->flags & I40E_FLAG_PTP)
14481 		i += snprintf(&buf[i], REMAIN(i), " PTP");
14482 	if (pf->flags & I40E_FLAG_VEB_MODE_ENABLED)
14483 		i += snprintf(&buf[i], REMAIN(i), " VEB");
14484 	else
14485 		i += snprintf(&buf[i], REMAIN(i), " VEPA");
14486 
14487 	dev_info(&pf->pdev->dev, "%s\n", buf);
14488 	kfree(buf);
14489 	WARN_ON(i > INFO_STRING_LEN);
14490 }
14491 
14492 /**
14493  * i40e_get_platform_mac_addr - get platform-specific MAC address
14494  * @pdev: PCI device information struct
14495  * @pf: board private structure
14496  *
14497  * Look up the MAC address for the device. First we'll try
14498  * eth_platform_get_mac_address, which will check Open Firmware, or arch
14499  * specific fallback. Otherwise, we'll default to the stored value in
14500  * firmware.
14501  **/
14502 static void i40e_get_platform_mac_addr(struct pci_dev *pdev, struct i40e_pf *pf)
14503 {
14504 	if (eth_platform_get_mac_address(&pdev->dev, pf->hw.mac.addr))
14505 		i40e_get_mac_addr(&pf->hw, pf->hw.mac.addr);
14506 }
14507 
14508 /**
14509  * i40e_set_fec_in_flags - helper function for setting FEC options in flags
14510  * @fec_cfg: FEC option to set in flags
14511  * @flags: ptr to flags in which we set FEC option
14512  **/
14513 void i40e_set_fec_in_flags(u8 fec_cfg, u32 *flags)
14514 {
14515 	if (fec_cfg & I40E_AQ_SET_FEC_AUTO)
14516 		*flags |= I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC;
14517 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_RS) ||
14518 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_RS)) {
14519 		*flags |= I40E_FLAG_RS_FEC;
14520 		*flags &= ~I40E_FLAG_BASE_R_FEC;
14521 	}
14522 	if ((fec_cfg & I40E_AQ_SET_FEC_REQUEST_KR) ||
14523 	    (fec_cfg & I40E_AQ_SET_FEC_ABILITY_KR)) {
14524 		*flags |= I40E_FLAG_BASE_R_FEC;
14525 		*flags &= ~I40E_FLAG_RS_FEC;
14526 	}
14527 	if (fec_cfg == 0)
14528 		*flags &= ~(I40E_FLAG_RS_FEC | I40E_FLAG_BASE_R_FEC);
14529 }
14530 
14531 /**
14532  * i40e_check_recovery_mode - check if we are running transition firmware
14533  * @pf: board private structure
14534  *
14535  * Check registers indicating the firmware runs in recovery mode. Sets the
14536  * appropriate driver state.
14537  *
14538  * Returns true if the recovery mode was detected, false otherwise
14539  **/
14540 static bool i40e_check_recovery_mode(struct i40e_pf *pf)
14541 {
14542 	u32 val = rd32(&pf->hw, I40E_GL_FWSTS) & I40E_GL_FWSTS_FWS1B_MASK;
14543 	bool is_recovery_mode = false;
14544 
14545 	if (pf->hw.mac.type == I40E_MAC_XL710)
14546 		is_recovery_mode =
14547 		val == I40E_XL710_GL_FWSTS_FWS1B_REC_MOD_CORER_MASK ||
14548 		val == I40E_XL710_GL_FWSTS_FWS1B_REC_MOD_GLOBR_MASK ||
14549 		val == I40E_XL710_GL_FWSTS_FWS1B_REC_MOD_TRANSITION_MASK ||
14550 		val == I40E_XL710_GL_FWSTS_FWS1B_REC_MOD_NVM_MASK;
14551 	if (pf->hw.mac.type == I40E_MAC_X722)
14552 		is_recovery_mode =
14553 		val == I40E_X722_GL_FWSTS_FWS1B_REC_MOD_CORER_MASK ||
14554 		val == I40E_X722_GL_FWSTS_FWS1B_REC_MOD_GLOBR_MASK;
14555 	if (is_recovery_mode) {
14556 		dev_notice(&pf->pdev->dev, "Firmware recovery mode detected. Limiting functionality.\n");
14557 		dev_notice(&pf->pdev->dev, "Refer to the Intel(R) Ethernet Adapters and Devices User Guide for details on firmware recovery mode.\n");
14558 		set_bit(__I40E_RECOVERY_MODE, pf->state);
14559 
14560 		return true;
14561 	}
14562 	if (test_and_clear_bit(__I40E_RECOVERY_MODE, pf->state))
14563 		dev_info(&pf->pdev->dev, "Reinitializing in normal mode with full functionality.\n");
14564 
14565 	return false;
14566 }
14567 
14568 /**
14569  * i40e_pf_loop_reset - perform reset in a loop.
14570  * @pf: board private structure
14571  *
14572  * This function is useful when a NIC is about to enter recovery mode.
14573  * When a NIC's internal data structures are corrupted the NIC's
14574  * firmware is going to enter recovery mode.
14575  * Right after a POR it takes about 7 minutes for firmware to enter
14576  * recovery mode. Until that time a NIC is in some kind of intermediate
14577  * state. After that time period the NIC almost surely enters
14578  * recovery mode. The only way for a driver to detect intermediate
14579  * state is to issue a series of pf-resets and check a return value.
14580  * If a PF reset returns success then the firmware could be in recovery
14581  * mode so the caller of this code needs to check for recovery mode
14582  * if this function returns success. There is a little chance that
14583  * firmware will hang in intermediate state forever.
14584  * Since waiting 7 minutes is quite a lot of time this function waits
14585  * 10 seconds and then gives up by returning an error.
14586  *
14587  * Return 0 on success, negative on failure.
14588  **/
14589 static i40e_status i40e_pf_loop_reset(struct i40e_pf *pf)
14590 {
14591 	const unsigned short MAX_CNT = 1000;
14592 	const unsigned short MSECS = 10;
14593 	struct i40e_hw *hw = &pf->hw;
14594 	i40e_status ret;
14595 	int cnt;
14596 
14597 	for (cnt = 0; cnt < MAX_CNT; ++cnt) {
14598 		ret = i40e_pf_reset(hw);
14599 		if (!ret)
14600 			break;
14601 		msleep(MSECS);
14602 	}
14603 
14604 	if (cnt == MAX_CNT) {
14605 		dev_info(&pf->pdev->dev, "PF reset failed: %d\n", ret);
14606 		return ret;
14607 	}
14608 
14609 	pf->pfr_count++;
14610 	return ret;
14611 }
14612 
14613 /**
14614  * i40e_init_recovery_mode - initialize subsystems needed in recovery mode
14615  * @pf: board private structure
14616  * @hw: ptr to the hardware info
14617  *
14618  * This function does a minimal setup of all subsystems needed for running
14619  * recovery mode.
14620  *
14621  * Returns 0 on success, negative on failure
14622  **/
14623 static int i40e_init_recovery_mode(struct i40e_pf *pf, struct i40e_hw *hw)
14624 {
14625 	struct i40e_vsi *vsi;
14626 	int err;
14627 	int v_idx;
14628 
14629 	pci_save_state(pf->pdev);
14630 
14631 	/* set up periodic task facility */
14632 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
14633 	pf->service_timer_period = HZ;
14634 
14635 	INIT_WORK(&pf->service_task, i40e_service_task);
14636 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
14637 
14638 	err = i40e_init_interrupt_scheme(pf);
14639 	if (err)
14640 		goto err_switch_setup;
14641 
14642 	/* The number of VSIs reported by the FW is the minimum guaranteed
14643 	 * to us; HW supports far more and we share the remaining pool with
14644 	 * the other PFs. We allocate space for more than the guarantee with
14645 	 * the understanding that we might not get them all later.
14646 	 */
14647 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
14648 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
14649 	else
14650 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
14651 
14652 	/* Set up the vsi struct and our local tracking of the MAIN PF vsi. */
14653 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
14654 			  GFP_KERNEL);
14655 	if (!pf->vsi) {
14656 		err = -ENOMEM;
14657 		goto err_switch_setup;
14658 	}
14659 
14660 	/* We allocate one VSI which is needed as absolute minimum
14661 	 * in order to register the netdev
14662 	 */
14663 	v_idx = i40e_vsi_mem_alloc(pf, I40E_VSI_MAIN);
14664 	if (v_idx < 0)
14665 		goto err_switch_setup;
14666 	pf->lan_vsi = v_idx;
14667 	vsi = pf->vsi[v_idx];
14668 	if (!vsi)
14669 		goto err_switch_setup;
14670 	vsi->alloc_queue_pairs = 1;
14671 	err = i40e_config_netdev(vsi);
14672 	if (err)
14673 		goto err_switch_setup;
14674 	err = register_netdev(vsi->netdev);
14675 	if (err)
14676 		goto err_switch_setup;
14677 	vsi->netdev_registered = true;
14678 	i40e_dbg_pf_init(pf);
14679 
14680 	err = i40e_setup_misc_vector_for_recovery_mode(pf);
14681 	if (err)
14682 		goto err_switch_setup;
14683 
14684 	/* tell the firmware that we're starting */
14685 	i40e_send_version(pf);
14686 
14687 	/* since everything's happy, start the service_task timer */
14688 	mod_timer(&pf->service_timer,
14689 		  round_jiffies(jiffies + pf->service_timer_period));
14690 
14691 	return 0;
14692 
14693 err_switch_setup:
14694 	i40e_reset_interrupt_capability(pf);
14695 	del_timer_sync(&pf->service_timer);
14696 	i40e_shutdown_adminq(hw);
14697 	iounmap(hw->hw_addr);
14698 	pci_disable_pcie_error_reporting(pf->pdev);
14699 	pci_release_mem_regions(pf->pdev);
14700 	pci_disable_device(pf->pdev);
14701 	kfree(pf);
14702 
14703 	return err;
14704 }
14705 
14706 /**
14707  * i40e_probe - Device initialization routine
14708  * @pdev: PCI device information struct
14709  * @ent: entry in i40e_pci_tbl
14710  *
14711  * i40e_probe initializes a PF identified by a pci_dev structure.
14712  * The OS initialization, configuring of the PF private structure,
14713  * and a hardware reset occur.
14714  *
14715  * Returns 0 on success, negative on failure
14716  **/
14717 static int i40e_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
14718 {
14719 	struct i40e_aq_get_phy_abilities_resp abilities;
14720 	struct i40e_pf *pf;
14721 	struct i40e_hw *hw;
14722 	static u16 pfs_found;
14723 	u16 wol_nvm_bits;
14724 	u16 link_status;
14725 	int err;
14726 	u32 val;
14727 	u32 i;
14728 	u8 set_fc_aq_fail;
14729 
14730 	err = pci_enable_device_mem(pdev);
14731 	if (err)
14732 		return err;
14733 
14734 	/* set up for high or low dma */
14735 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
14736 	if (err) {
14737 		err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
14738 		if (err) {
14739 			dev_err(&pdev->dev,
14740 				"DMA configuration failed: 0x%x\n", err);
14741 			goto err_dma;
14742 		}
14743 	}
14744 
14745 	/* set up pci connections */
14746 	err = pci_request_mem_regions(pdev, i40e_driver_name);
14747 	if (err) {
14748 		dev_info(&pdev->dev,
14749 			 "pci_request_selected_regions failed %d\n", err);
14750 		goto err_pci_reg;
14751 	}
14752 
14753 	pci_enable_pcie_error_reporting(pdev);
14754 	pci_set_master(pdev);
14755 
14756 	/* Now that we have a PCI connection, we need to do the
14757 	 * low level device setup.  This is primarily setting up
14758 	 * the Admin Queue structures and then querying for the
14759 	 * device's current profile information.
14760 	 */
14761 	pf = kzalloc(sizeof(*pf), GFP_KERNEL);
14762 	if (!pf) {
14763 		err = -ENOMEM;
14764 		goto err_pf_alloc;
14765 	}
14766 	pf->next_vsi = 0;
14767 	pf->pdev = pdev;
14768 	set_bit(__I40E_DOWN, pf->state);
14769 
14770 	hw = &pf->hw;
14771 	hw->back = pf;
14772 
14773 	pf->ioremap_len = min_t(int, pci_resource_len(pdev, 0),
14774 				I40E_MAX_CSR_SPACE);
14775 	/* We believe that the highest register to read is
14776 	 * I40E_GLGEN_STAT_CLEAR, so we check if the BAR size
14777 	 * is not less than that before mapping to prevent a
14778 	 * kernel panic.
14779 	 */
14780 	if (pf->ioremap_len < I40E_GLGEN_STAT_CLEAR) {
14781 		dev_err(&pdev->dev, "Cannot map registers, bar size 0x%X too small, aborting\n",
14782 			pf->ioremap_len);
14783 		err = -ENOMEM;
14784 		goto err_ioremap;
14785 	}
14786 	hw->hw_addr = ioremap(pci_resource_start(pdev, 0), pf->ioremap_len);
14787 	if (!hw->hw_addr) {
14788 		err = -EIO;
14789 		dev_info(&pdev->dev, "ioremap(0x%04x, 0x%04x) failed: 0x%x\n",
14790 			 (unsigned int)pci_resource_start(pdev, 0),
14791 			 pf->ioremap_len, err);
14792 		goto err_ioremap;
14793 	}
14794 	hw->vendor_id = pdev->vendor;
14795 	hw->device_id = pdev->device;
14796 	pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
14797 	hw->subsystem_vendor_id = pdev->subsystem_vendor;
14798 	hw->subsystem_device_id = pdev->subsystem_device;
14799 	hw->bus.device = PCI_SLOT(pdev->devfn);
14800 	hw->bus.func = PCI_FUNC(pdev->devfn);
14801 	hw->bus.bus_id = pdev->bus->number;
14802 	pf->instance = pfs_found;
14803 
14804 	/* Select something other than the 802.1ad ethertype for the
14805 	 * switch to use internally and drop on ingress.
14806 	 */
14807 	hw->switch_tag = 0xffff;
14808 	hw->first_tag = ETH_P_8021AD;
14809 	hw->second_tag = ETH_P_8021Q;
14810 
14811 	INIT_LIST_HEAD(&pf->l3_flex_pit_list);
14812 	INIT_LIST_HEAD(&pf->l4_flex_pit_list);
14813 	INIT_LIST_HEAD(&pf->ddp_old_prof);
14814 
14815 	/* set up the locks for the AQ, do this only once in probe
14816 	 * and destroy them only once in remove
14817 	 */
14818 	mutex_init(&hw->aq.asq_mutex);
14819 	mutex_init(&hw->aq.arq_mutex);
14820 
14821 	pf->msg_enable = netif_msg_init(debug,
14822 					NETIF_MSG_DRV |
14823 					NETIF_MSG_PROBE |
14824 					NETIF_MSG_LINK);
14825 	if (debug < -1)
14826 		pf->hw.debug_mask = debug;
14827 
14828 	/* do a special CORER for clearing PXE mode once at init */
14829 	if (hw->revision_id == 0 &&
14830 	    (rd32(hw, I40E_GLLAN_RCTL_0) & I40E_GLLAN_RCTL_0_PXE_MODE_MASK)) {
14831 		wr32(hw, I40E_GLGEN_RTRIG, I40E_GLGEN_RTRIG_CORER_MASK);
14832 		i40e_flush(hw);
14833 		msleep(200);
14834 		pf->corer_count++;
14835 
14836 		i40e_clear_pxe_mode(hw);
14837 	}
14838 
14839 	/* Reset here to make sure all is clean and to define PF 'n' */
14840 	i40e_clear_hw(hw);
14841 
14842 	err = i40e_set_mac_type(hw);
14843 	if (err) {
14844 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
14845 			 err);
14846 		goto err_pf_reset;
14847 	}
14848 
14849 	err = i40e_pf_loop_reset(pf);
14850 	if (err) {
14851 		dev_info(&pdev->dev, "Initial pf_reset failed: %d\n", err);
14852 		goto err_pf_reset;
14853 	}
14854 
14855 	i40e_check_recovery_mode(pf);
14856 
14857 	hw->aq.num_arq_entries = I40E_AQ_LEN;
14858 	hw->aq.num_asq_entries = I40E_AQ_LEN;
14859 	hw->aq.arq_buf_size = I40E_MAX_AQ_BUF_SIZE;
14860 	hw->aq.asq_buf_size = I40E_MAX_AQ_BUF_SIZE;
14861 	pf->adminq_work_limit = I40E_AQ_WORK_LIMIT;
14862 
14863 	snprintf(pf->int_name, sizeof(pf->int_name) - 1,
14864 		 "%s-%s:misc",
14865 		 dev_driver_string(&pf->pdev->dev), dev_name(&pdev->dev));
14866 
14867 	err = i40e_init_shared_code(hw);
14868 	if (err) {
14869 		dev_warn(&pdev->dev, "unidentified MAC or BLANK NVM: %d\n",
14870 			 err);
14871 		goto err_pf_reset;
14872 	}
14873 
14874 	/* set up a default setting for link flow control */
14875 	pf->hw.fc.requested_mode = I40E_FC_NONE;
14876 
14877 	err = i40e_init_adminq(hw);
14878 	if (err) {
14879 		if (err == I40E_ERR_FIRMWARE_API_VERSION)
14880 			dev_info(&pdev->dev,
14881 				 "The driver for the device stopped because the NVM image v%u.%u is newer than expected v%u.%u. You must install the most recent version of the network driver.\n",
14882 				 hw->aq.api_maj_ver,
14883 				 hw->aq.api_min_ver,
14884 				 I40E_FW_API_VERSION_MAJOR,
14885 				 I40E_FW_MINOR_VERSION(hw));
14886 		else
14887 			dev_info(&pdev->dev,
14888 				 "The driver for the device stopped because the device firmware failed to init. Try updating your NVM image.\n");
14889 
14890 		goto err_pf_reset;
14891 	}
14892 	i40e_get_oem_version(hw);
14893 
14894 	/* provide nvm, fw, api versions, vendor:device id, subsys vendor:device id */
14895 	dev_info(&pdev->dev, "fw %d.%d.%05d api %d.%d nvm %s [%04x:%04x] [%04x:%04x]\n",
14896 		 hw->aq.fw_maj_ver, hw->aq.fw_min_ver, hw->aq.fw_build,
14897 		 hw->aq.api_maj_ver, hw->aq.api_min_ver,
14898 		 i40e_nvm_version_str(hw), hw->vendor_id, hw->device_id,
14899 		 hw->subsystem_vendor_id, hw->subsystem_device_id);
14900 
14901 	if (hw->aq.api_maj_ver == I40E_FW_API_VERSION_MAJOR &&
14902 	    hw->aq.api_min_ver > I40E_FW_MINOR_VERSION(hw))
14903 		dev_info(&pdev->dev,
14904 			 "The driver for the device detected a newer version of the NVM image v%u.%u than expected v%u.%u. Please install the most recent version of the network driver.\n",
14905 			 hw->aq.api_maj_ver,
14906 			 hw->aq.api_min_ver,
14907 			 I40E_FW_API_VERSION_MAJOR,
14908 			 I40E_FW_MINOR_VERSION(hw));
14909 	else if (hw->aq.api_maj_ver == 1 && hw->aq.api_min_ver < 4)
14910 		dev_info(&pdev->dev,
14911 			 "The driver for the device detected an older version of the NVM image v%u.%u than expected v%u.%u. Please update the NVM image.\n",
14912 			 hw->aq.api_maj_ver,
14913 			 hw->aq.api_min_ver,
14914 			 I40E_FW_API_VERSION_MAJOR,
14915 			 I40E_FW_MINOR_VERSION(hw));
14916 
14917 	i40e_verify_eeprom(pf);
14918 
14919 	/* Rev 0 hardware was never productized */
14920 	if (hw->revision_id < 1)
14921 		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");
14922 
14923 	i40e_clear_pxe_mode(hw);
14924 
14925 	err = i40e_get_capabilities(pf, i40e_aqc_opc_list_func_capabilities);
14926 	if (err)
14927 		goto err_adminq_setup;
14928 
14929 	err = i40e_sw_init(pf);
14930 	if (err) {
14931 		dev_info(&pdev->dev, "sw_init failed: %d\n", err);
14932 		goto err_sw_init;
14933 	}
14934 
14935 	if (test_bit(__I40E_RECOVERY_MODE, pf->state))
14936 		return i40e_init_recovery_mode(pf, hw);
14937 
14938 	err = i40e_init_lan_hmc(hw, hw->func_caps.num_tx_qp,
14939 				hw->func_caps.num_rx_qp, 0, 0);
14940 	if (err) {
14941 		dev_info(&pdev->dev, "init_lan_hmc failed: %d\n", err);
14942 		goto err_init_lan_hmc;
14943 	}
14944 
14945 	err = i40e_configure_lan_hmc(hw, I40E_HMC_MODEL_DIRECT_ONLY);
14946 	if (err) {
14947 		dev_info(&pdev->dev, "configure_lan_hmc failed: %d\n", err);
14948 		err = -ENOENT;
14949 		goto err_configure_lan_hmc;
14950 	}
14951 
14952 	/* Disable LLDP for NICs that have firmware versions lower than v4.3.
14953 	 * Ignore error return codes because if it was already disabled via
14954 	 * hardware settings this will fail
14955 	 */
14956 	if (pf->hw_features & I40E_HW_STOP_FW_LLDP) {
14957 		dev_info(&pdev->dev, "Stopping firmware LLDP agent.\n");
14958 		i40e_aq_stop_lldp(hw, true, false, NULL);
14959 	}
14960 
14961 	/* allow a platform config to override the HW addr */
14962 	i40e_get_platform_mac_addr(pdev, pf);
14963 
14964 	if (!is_valid_ether_addr(hw->mac.addr)) {
14965 		dev_info(&pdev->dev, "invalid MAC address %pM\n", hw->mac.addr);
14966 		err = -EIO;
14967 		goto err_mac_addr;
14968 	}
14969 	dev_info(&pdev->dev, "MAC address: %pM\n", hw->mac.addr);
14970 	ether_addr_copy(hw->mac.perm_addr, hw->mac.addr);
14971 	i40e_get_port_mac_addr(hw, hw->mac.port_addr);
14972 	if (is_valid_ether_addr(hw->mac.port_addr))
14973 		pf->hw_features |= I40E_HW_PORT_ID_VALID;
14974 
14975 	pci_set_drvdata(pdev, pf);
14976 	pci_save_state(pdev);
14977 
14978 	dev_info(&pdev->dev,
14979 		 (pf->flags & I40E_FLAG_DISABLE_FW_LLDP) ?
14980 			"FW LLDP is disabled\n" :
14981 			"FW LLDP is enabled\n");
14982 
14983 	/* Enable FW to write default DCB config on link-up */
14984 	i40e_aq_set_dcb_parameters(hw, true, NULL);
14985 
14986 #ifdef CONFIG_I40E_DCB
14987 	err = i40e_init_pf_dcb(pf);
14988 	if (err) {
14989 		dev_info(&pdev->dev, "DCB init failed %d, disabled\n", err);
14990 		pf->flags &= ~(I40E_FLAG_DCB_CAPABLE | I40E_FLAG_DCB_ENABLED);
14991 		/* Continue without DCB enabled */
14992 	}
14993 #endif /* CONFIG_I40E_DCB */
14994 
14995 	/* set up periodic task facility */
14996 	timer_setup(&pf->service_timer, i40e_service_timer, 0);
14997 	pf->service_timer_period = HZ;
14998 
14999 	INIT_WORK(&pf->service_task, i40e_service_task);
15000 	clear_bit(__I40E_SERVICE_SCHED, pf->state);
15001 
15002 	/* NVM bit on means WoL disabled for the port */
15003 	i40e_read_nvm_word(hw, I40E_SR_NVM_WAKE_ON_LAN, &wol_nvm_bits);
15004 	if (BIT (hw->port) & wol_nvm_bits || hw->partition_id != 1)
15005 		pf->wol_en = false;
15006 	else
15007 		pf->wol_en = true;
15008 	device_set_wakeup_enable(&pf->pdev->dev, pf->wol_en);
15009 
15010 	/* set up the main switch operations */
15011 	i40e_determine_queue_usage(pf);
15012 	err = i40e_init_interrupt_scheme(pf);
15013 	if (err)
15014 		goto err_switch_setup;
15015 
15016 	/* The number of VSIs reported by the FW is the minimum guaranteed
15017 	 * to us; HW supports far more and we share the remaining pool with
15018 	 * the other PFs. We allocate space for more than the guarantee with
15019 	 * the understanding that we might not get them all later.
15020 	 */
15021 	if (pf->hw.func_caps.num_vsis < I40E_MIN_VSI_ALLOC)
15022 		pf->num_alloc_vsi = I40E_MIN_VSI_ALLOC;
15023 	else
15024 		pf->num_alloc_vsi = pf->hw.func_caps.num_vsis;
15025 
15026 	/* Set up the *vsi struct and our local tracking of the MAIN PF vsi. */
15027 	pf->vsi = kcalloc(pf->num_alloc_vsi, sizeof(struct i40e_vsi *),
15028 			  GFP_KERNEL);
15029 	if (!pf->vsi) {
15030 		err = -ENOMEM;
15031 		goto err_switch_setup;
15032 	}
15033 
15034 #ifdef CONFIG_PCI_IOV
15035 	/* prep for VF support */
15036 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15037 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15038 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15039 		if (pci_num_vf(pdev))
15040 			pf->flags |= I40E_FLAG_VEB_MODE_ENABLED;
15041 	}
15042 #endif
15043 	err = i40e_setup_pf_switch(pf, false);
15044 	if (err) {
15045 		dev_info(&pdev->dev, "setup_pf_switch failed: %d\n", err);
15046 		goto err_vsis;
15047 	}
15048 	INIT_LIST_HEAD(&pf->vsi[pf->lan_vsi]->ch_list);
15049 
15050 	/* Make sure flow control is set according to current settings */
15051 	err = i40e_set_fc(hw, &set_fc_aq_fail, true);
15052 	if (set_fc_aq_fail & I40E_SET_FC_AQ_FAIL_GET)
15053 		dev_dbg(&pf->pdev->dev,
15054 			"Set fc with err %s aq_err %s on get_phy_cap\n",
15055 			i40e_stat_str(hw, err),
15056 			i40e_aq_str(hw, hw->aq.asq_last_status));
15057 	if (set_fc_aq_fail & I40E_SET_FC_AQ_FAIL_SET)
15058 		dev_dbg(&pf->pdev->dev,
15059 			"Set fc with err %s aq_err %s on set_phy_config\n",
15060 			i40e_stat_str(hw, err),
15061 			i40e_aq_str(hw, hw->aq.asq_last_status));
15062 	if (set_fc_aq_fail & I40E_SET_FC_AQ_FAIL_UPDATE)
15063 		dev_dbg(&pf->pdev->dev,
15064 			"Set fc with err %s aq_err %s on get_link_info\n",
15065 			i40e_stat_str(hw, err),
15066 			i40e_aq_str(hw, hw->aq.asq_last_status));
15067 
15068 	/* if FDIR VSI was set up, start it now */
15069 	for (i = 0; i < pf->num_alloc_vsi; i++) {
15070 		if (pf->vsi[i] && pf->vsi[i]->type == I40E_VSI_FDIR) {
15071 			i40e_vsi_open(pf->vsi[i]);
15072 			break;
15073 		}
15074 	}
15075 
15076 	/* The driver only wants link up/down and module qualification
15077 	 * reports from firmware.  Note the negative logic.
15078 	 */
15079 	err = i40e_aq_set_phy_int_mask(&pf->hw,
15080 				       ~(I40E_AQ_EVENT_LINK_UPDOWN |
15081 					 I40E_AQ_EVENT_MEDIA_NA |
15082 					 I40E_AQ_EVENT_MODULE_QUAL_FAIL), NULL);
15083 	if (err)
15084 		dev_info(&pf->pdev->dev, "set phy mask fail, err %s aq_err %s\n",
15085 			 i40e_stat_str(&pf->hw, err),
15086 			 i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15087 
15088 	/* Reconfigure hardware for allowing smaller MSS in the case
15089 	 * of TSO, so that we avoid the MDD being fired and causing
15090 	 * a reset in the case of small MSS+TSO.
15091 	 */
15092 	val = rd32(hw, I40E_REG_MSS);
15093 	if ((val & I40E_REG_MSS_MIN_MASK) > I40E_64BYTE_MSS) {
15094 		val &= ~I40E_REG_MSS_MIN_MASK;
15095 		val |= I40E_64BYTE_MSS;
15096 		wr32(hw, I40E_REG_MSS, val);
15097 	}
15098 
15099 	if (pf->hw_features & I40E_HW_RESTART_AUTONEG) {
15100 		msleep(75);
15101 		err = i40e_aq_set_link_restart_an(&pf->hw, true, NULL);
15102 		if (err)
15103 			dev_info(&pf->pdev->dev, "link restart failed, err %s aq_err %s\n",
15104 				 i40e_stat_str(&pf->hw, err),
15105 				 i40e_aq_str(&pf->hw,
15106 					     pf->hw.aq.asq_last_status));
15107 	}
15108 	/* The main driver is (mostly) up and happy. We need to set this state
15109 	 * before setting up the misc vector or we get a race and the vector
15110 	 * ends up disabled forever.
15111 	 */
15112 	clear_bit(__I40E_DOWN, pf->state);
15113 
15114 	/* In case of MSIX we are going to setup the misc vector right here
15115 	 * to handle admin queue events etc. In case of legacy and MSI
15116 	 * the misc functionality and queue processing is combined in
15117 	 * the same vector and that gets setup at open.
15118 	 */
15119 	if (pf->flags & I40E_FLAG_MSIX_ENABLED) {
15120 		err = i40e_setup_misc_vector(pf);
15121 		if (err) {
15122 			dev_info(&pdev->dev,
15123 				 "setup of misc vector failed: %d\n", err);
15124 			goto err_vsis;
15125 		}
15126 	}
15127 
15128 #ifdef CONFIG_PCI_IOV
15129 	/* prep for VF support */
15130 	if ((pf->flags & I40E_FLAG_SRIOV_ENABLED) &&
15131 	    (pf->flags & I40E_FLAG_MSIX_ENABLED) &&
15132 	    !test_bit(__I40E_BAD_EEPROM, pf->state)) {
15133 		/* disable link interrupts for VFs */
15134 		val = rd32(hw, I40E_PFGEN_PORTMDIO_NUM);
15135 		val &= ~I40E_PFGEN_PORTMDIO_NUM_VFLINK_STAT_ENA_MASK;
15136 		wr32(hw, I40E_PFGEN_PORTMDIO_NUM, val);
15137 		i40e_flush(hw);
15138 
15139 		if (pci_num_vf(pdev)) {
15140 			dev_info(&pdev->dev,
15141 				 "Active VFs found, allocating resources.\n");
15142 			err = i40e_alloc_vfs(pf, pci_num_vf(pdev));
15143 			if (err)
15144 				dev_info(&pdev->dev,
15145 					 "Error %d allocating resources for existing VFs\n",
15146 					 err);
15147 		}
15148 	}
15149 #endif /* CONFIG_PCI_IOV */
15150 
15151 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15152 		pf->iwarp_base_vector = i40e_get_lump(pf, pf->irq_pile,
15153 						      pf->num_iwarp_msix,
15154 						      I40E_IWARP_IRQ_PILE_ID);
15155 		if (pf->iwarp_base_vector < 0) {
15156 			dev_info(&pdev->dev,
15157 				 "failed to get tracking for %d vectors for IWARP err=%d\n",
15158 				 pf->num_iwarp_msix, pf->iwarp_base_vector);
15159 			pf->flags &= ~I40E_FLAG_IWARP_ENABLED;
15160 		}
15161 	}
15162 
15163 	i40e_dbg_pf_init(pf);
15164 
15165 	/* tell the firmware that we're starting */
15166 	i40e_send_version(pf);
15167 
15168 	/* since everything's happy, start the service_task timer */
15169 	mod_timer(&pf->service_timer,
15170 		  round_jiffies(jiffies + pf->service_timer_period));
15171 
15172 	/* add this PF to client device list and launch a client service task */
15173 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15174 		err = i40e_lan_add_device(pf);
15175 		if (err)
15176 			dev_info(&pdev->dev, "Failed to add PF to client API service list: %d\n",
15177 				 err);
15178 	}
15179 
15180 #define PCI_SPEED_SIZE 8
15181 #define PCI_WIDTH_SIZE 8
15182 	/* Devices on the IOSF bus do not have this information
15183 	 * and will report PCI Gen 1 x 1 by default so don't bother
15184 	 * checking them.
15185 	 */
15186 	if (!(pf->hw_features & I40E_HW_NO_PCI_LINK_CHECK)) {
15187 		char speed[PCI_SPEED_SIZE] = "Unknown";
15188 		char width[PCI_WIDTH_SIZE] = "Unknown";
15189 
15190 		/* Get the negotiated link width and speed from PCI config
15191 		 * space
15192 		 */
15193 		pcie_capability_read_word(pf->pdev, PCI_EXP_LNKSTA,
15194 					  &link_status);
15195 
15196 		i40e_set_pci_config_data(hw, link_status);
15197 
15198 		switch (hw->bus.speed) {
15199 		case i40e_bus_speed_8000:
15200 			strlcpy(speed, "8.0", PCI_SPEED_SIZE); break;
15201 		case i40e_bus_speed_5000:
15202 			strlcpy(speed, "5.0", PCI_SPEED_SIZE); break;
15203 		case i40e_bus_speed_2500:
15204 			strlcpy(speed, "2.5", PCI_SPEED_SIZE); break;
15205 		default:
15206 			break;
15207 		}
15208 		switch (hw->bus.width) {
15209 		case i40e_bus_width_pcie_x8:
15210 			strlcpy(width, "8", PCI_WIDTH_SIZE); break;
15211 		case i40e_bus_width_pcie_x4:
15212 			strlcpy(width, "4", PCI_WIDTH_SIZE); break;
15213 		case i40e_bus_width_pcie_x2:
15214 			strlcpy(width, "2", PCI_WIDTH_SIZE); break;
15215 		case i40e_bus_width_pcie_x1:
15216 			strlcpy(width, "1", PCI_WIDTH_SIZE); break;
15217 		default:
15218 			break;
15219 		}
15220 
15221 		dev_info(&pdev->dev, "PCI-Express: Speed %sGT/s Width x%s\n",
15222 			 speed, width);
15223 
15224 		if (hw->bus.width < i40e_bus_width_pcie_x8 ||
15225 		    hw->bus.speed < i40e_bus_speed_8000) {
15226 			dev_warn(&pdev->dev, "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
15227 			dev_warn(&pdev->dev, "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
15228 		}
15229 	}
15230 
15231 	/* get the requested speeds from the fw */
15232 	err = i40e_aq_get_phy_capabilities(hw, false, false, &abilities, NULL);
15233 	if (err)
15234 		dev_dbg(&pf->pdev->dev, "get requested speeds ret =  %s last_status =  %s\n",
15235 			i40e_stat_str(&pf->hw, err),
15236 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15237 	pf->hw.phy.link_info.requested_speeds = abilities.link_speed;
15238 
15239 	/* set the FEC config due to the board capabilities */
15240 	i40e_set_fec_in_flags(abilities.fec_cfg_curr_mod_ext_info, &pf->flags);
15241 
15242 	/* get the supported phy types from the fw */
15243 	err = i40e_aq_get_phy_capabilities(hw, false, true, &abilities, NULL);
15244 	if (err)
15245 		dev_dbg(&pf->pdev->dev, "get supported phy types ret =  %s last_status =  %s\n",
15246 			i40e_stat_str(&pf->hw, err),
15247 			i40e_aq_str(&pf->hw, pf->hw.aq.asq_last_status));
15248 
15249 	/* Add a filter to drop all Flow control frames from any VSI from being
15250 	 * transmitted. By doing so we stop a malicious VF from sending out
15251 	 * PAUSE or PFC frames and potentially controlling traffic for other
15252 	 * PF/VF VSIs.
15253 	 * The FW can still send Flow control frames if enabled.
15254 	 */
15255 	i40e_add_filter_to_drop_tx_flow_control_frames(&pf->hw,
15256 						       pf->main_vsi_seid);
15257 
15258 	if ((pf->hw.device_id == I40E_DEV_ID_10G_BASE_T) ||
15259 		(pf->hw.device_id == I40E_DEV_ID_10G_BASE_T4))
15260 		pf->hw_features |= I40E_HW_PHY_CONTROLS_LEDS;
15261 	if (pf->hw.device_id == I40E_DEV_ID_SFP_I_X722)
15262 		pf->hw_features |= I40E_HW_HAVE_CRT_RETIMER;
15263 	/* print a string summarizing features */
15264 	i40e_print_features(pf);
15265 
15266 	return 0;
15267 
15268 	/* Unwind what we've done if something failed in the setup */
15269 err_vsis:
15270 	set_bit(__I40E_DOWN, pf->state);
15271 	i40e_clear_interrupt_scheme(pf);
15272 	kfree(pf->vsi);
15273 err_switch_setup:
15274 	i40e_reset_interrupt_capability(pf);
15275 	del_timer_sync(&pf->service_timer);
15276 err_mac_addr:
15277 err_configure_lan_hmc:
15278 	(void)i40e_shutdown_lan_hmc(hw);
15279 err_init_lan_hmc:
15280 	kfree(pf->qp_pile);
15281 err_sw_init:
15282 err_adminq_setup:
15283 err_pf_reset:
15284 	iounmap(hw->hw_addr);
15285 err_ioremap:
15286 	kfree(pf);
15287 err_pf_alloc:
15288 	pci_disable_pcie_error_reporting(pdev);
15289 	pci_release_mem_regions(pdev);
15290 err_pci_reg:
15291 err_dma:
15292 	pci_disable_device(pdev);
15293 	return err;
15294 }
15295 
15296 /**
15297  * i40e_remove - Device removal routine
15298  * @pdev: PCI device information struct
15299  *
15300  * i40e_remove is called by the PCI subsystem to alert the driver
15301  * that is should release a PCI device.  This could be caused by a
15302  * Hot-Plug event, or because the driver is going to be removed from
15303  * memory.
15304  **/
15305 static void i40e_remove(struct pci_dev *pdev)
15306 {
15307 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15308 	struct i40e_hw *hw = &pf->hw;
15309 	i40e_status ret_code;
15310 	int i;
15311 
15312 	i40e_dbg_pf_exit(pf);
15313 
15314 	i40e_ptp_stop(pf);
15315 
15316 	/* Disable RSS in hw */
15317 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(0), 0);
15318 	i40e_write_rx_ctl(hw, I40E_PFQF_HENA(1), 0);
15319 
15320 	/* no more scheduling of any task */
15321 	set_bit(__I40E_SUSPENDED, pf->state);
15322 	set_bit(__I40E_DOWN, pf->state);
15323 	if (pf->service_timer.function)
15324 		del_timer_sync(&pf->service_timer);
15325 	if (pf->service_task.func)
15326 		cancel_work_sync(&pf->service_task);
15327 
15328 	if (test_bit(__I40E_RECOVERY_MODE, pf->state)) {
15329 		struct i40e_vsi *vsi = pf->vsi[0];
15330 
15331 		/* We know that we have allocated only one vsi for this PF,
15332 		 * it was just for registering netdevice, so the interface
15333 		 * could be visible in the 'ifconfig' output
15334 		 */
15335 		unregister_netdev(vsi->netdev);
15336 		free_netdev(vsi->netdev);
15337 
15338 		goto unmap;
15339 	}
15340 
15341 	/* Client close must be called explicitly here because the timer
15342 	 * has been stopped.
15343 	 */
15344 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
15345 
15346 	if (pf->flags & I40E_FLAG_SRIOV_ENABLED) {
15347 		i40e_free_vfs(pf);
15348 		pf->flags &= ~I40E_FLAG_SRIOV_ENABLED;
15349 	}
15350 
15351 	i40e_fdir_teardown(pf);
15352 
15353 	/* If there is a switch structure or any orphans, remove them.
15354 	 * This will leave only the PF's VSI remaining.
15355 	 */
15356 	for (i = 0; i < I40E_MAX_VEB; i++) {
15357 		if (!pf->veb[i])
15358 			continue;
15359 
15360 		if (pf->veb[i]->uplink_seid == pf->mac_seid ||
15361 		    pf->veb[i]->uplink_seid == 0)
15362 			i40e_switch_branch_release(pf->veb[i]);
15363 	}
15364 
15365 	/* Now we can shutdown the PF's VSI, just before we kill
15366 	 * adminq and hmc.
15367 	 */
15368 	if (pf->vsi[pf->lan_vsi])
15369 		i40e_vsi_release(pf->vsi[pf->lan_vsi]);
15370 
15371 	i40e_cloud_filter_exit(pf);
15372 
15373 	/* remove attached clients */
15374 	if (pf->flags & I40E_FLAG_IWARP_ENABLED) {
15375 		ret_code = i40e_lan_del_device(pf);
15376 		if (ret_code)
15377 			dev_warn(&pdev->dev, "Failed to delete client device: %d\n",
15378 				 ret_code);
15379 	}
15380 
15381 	/* shutdown and destroy the HMC */
15382 	if (hw->hmc.hmc_obj) {
15383 		ret_code = i40e_shutdown_lan_hmc(hw);
15384 		if (ret_code)
15385 			dev_warn(&pdev->dev,
15386 				 "Failed to destroy the HMC resources: %d\n",
15387 				 ret_code);
15388 	}
15389 
15390 unmap:
15391 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
15392 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
15393 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
15394 		free_irq(pf->pdev->irq, pf);
15395 
15396 	/* shutdown the adminq */
15397 	i40e_shutdown_adminq(hw);
15398 
15399 	/* destroy the locks only once, here */
15400 	mutex_destroy(&hw->aq.arq_mutex);
15401 	mutex_destroy(&hw->aq.asq_mutex);
15402 
15403 	/* Clear all dynamic memory lists of rings, q_vectors, and VSIs */
15404 	rtnl_lock();
15405 	i40e_clear_interrupt_scheme(pf);
15406 	for (i = 0; i < pf->num_alloc_vsi; i++) {
15407 		if (pf->vsi[i]) {
15408 			if (!test_bit(__I40E_RECOVERY_MODE, pf->state))
15409 				i40e_vsi_clear_rings(pf->vsi[i]);
15410 			i40e_vsi_clear(pf->vsi[i]);
15411 			pf->vsi[i] = NULL;
15412 		}
15413 	}
15414 	rtnl_unlock();
15415 
15416 	for (i = 0; i < I40E_MAX_VEB; i++) {
15417 		kfree(pf->veb[i]);
15418 		pf->veb[i] = NULL;
15419 	}
15420 
15421 	kfree(pf->qp_pile);
15422 	kfree(pf->vsi);
15423 
15424 	iounmap(hw->hw_addr);
15425 	kfree(pf);
15426 	pci_release_mem_regions(pdev);
15427 
15428 	pci_disable_pcie_error_reporting(pdev);
15429 	pci_disable_device(pdev);
15430 }
15431 
15432 /**
15433  * i40e_pci_error_detected - warning that something funky happened in PCI land
15434  * @pdev: PCI device information struct
15435  * @error: the type of PCI error
15436  *
15437  * Called to warn that something happened and the error handling steps
15438  * are in progress.  Allows the driver to quiesce things, be ready for
15439  * remediation.
15440  **/
15441 static pci_ers_result_t i40e_pci_error_detected(struct pci_dev *pdev,
15442 						enum pci_channel_state error)
15443 {
15444 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15445 
15446 	dev_info(&pdev->dev, "%s: error %d\n", __func__, error);
15447 
15448 	if (!pf) {
15449 		dev_info(&pdev->dev,
15450 			 "Cannot recover - error happened during device probe\n");
15451 		return PCI_ERS_RESULT_DISCONNECT;
15452 	}
15453 
15454 	/* shutdown all operations */
15455 	if (!test_bit(__I40E_SUSPENDED, pf->state))
15456 		i40e_prep_for_reset(pf, false);
15457 
15458 	/* Request a slot reset */
15459 	return PCI_ERS_RESULT_NEED_RESET;
15460 }
15461 
15462 /**
15463  * i40e_pci_error_slot_reset - a PCI slot reset just happened
15464  * @pdev: PCI device information struct
15465  *
15466  * Called to find if the driver can work with the device now that
15467  * the pci slot has been reset.  If a basic connection seems good
15468  * (registers are readable and have sane content) then return a
15469  * happy little PCI_ERS_RESULT_xxx.
15470  **/
15471 static pci_ers_result_t i40e_pci_error_slot_reset(struct pci_dev *pdev)
15472 {
15473 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15474 	pci_ers_result_t result;
15475 	u32 reg;
15476 
15477 	dev_dbg(&pdev->dev, "%s\n", __func__);
15478 	if (pci_enable_device_mem(pdev)) {
15479 		dev_info(&pdev->dev,
15480 			 "Cannot re-enable PCI device after reset.\n");
15481 		result = PCI_ERS_RESULT_DISCONNECT;
15482 	} else {
15483 		pci_set_master(pdev);
15484 		pci_restore_state(pdev);
15485 		pci_save_state(pdev);
15486 		pci_wake_from_d3(pdev, false);
15487 
15488 		reg = rd32(&pf->hw, I40E_GLGEN_RTRIG);
15489 		if (reg == 0)
15490 			result = PCI_ERS_RESULT_RECOVERED;
15491 		else
15492 			result = PCI_ERS_RESULT_DISCONNECT;
15493 	}
15494 
15495 	return result;
15496 }
15497 
15498 /**
15499  * i40e_pci_error_reset_prepare - prepare device driver for pci reset
15500  * @pdev: PCI device information struct
15501  */
15502 static void i40e_pci_error_reset_prepare(struct pci_dev *pdev)
15503 {
15504 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15505 
15506 	i40e_prep_for_reset(pf, false);
15507 }
15508 
15509 /**
15510  * i40e_pci_error_reset_done - pci reset done, device driver reset can begin
15511  * @pdev: PCI device information struct
15512  */
15513 static void i40e_pci_error_reset_done(struct pci_dev *pdev)
15514 {
15515 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15516 
15517 	i40e_reset_and_rebuild(pf, false, false);
15518 }
15519 
15520 /**
15521  * i40e_pci_error_resume - restart operations after PCI error recovery
15522  * @pdev: PCI device information struct
15523  *
15524  * Called to allow the driver to bring things back up after PCI error
15525  * and/or reset recovery has finished.
15526  **/
15527 static void i40e_pci_error_resume(struct pci_dev *pdev)
15528 {
15529 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15530 
15531 	dev_dbg(&pdev->dev, "%s\n", __func__);
15532 	if (test_bit(__I40E_SUSPENDED, pf->state))
15533 		return;
15534 
15535 	i40e_handle_reset_warning(pf, false);
15536 }
15537 
15538 /**
15539  * i40e_enable_mc_magic_wake - enable multicast magic packet wake up
15540  * using the mac_address_write admin q function
15541  * @pf: pointer to i40e_pf struct
15542  **/
15543 static void i40e_enable_mc_magic_wake(struct i40e_pf *pf)
15544 {
15545 	struct i40e_hw *hw = &pf->hw;
15546 	i40e_status ret;
15547 	u8 mac_addr[6];
15548 	u16 flags = 0;
15549 
15550 	/* Get current MAC address in case it's an LAA */
15551 	if (pf->vsi[pf->lan_vsi] && pf->vsi[pf->lan_vsi]->netdev) {
15552 		ether_addr_copy(mac_addr,
15553 				pf->vsi[pf->lan_vsi]->netdev->dev_addr);
15554 	} else {
15555 		dev_err(&pf->pdev->dev,
15556 			"Failed to retrieve MAC address; using default\n");
15557 		ether_addr_copy(mac_addr, hw->mac.addr);
15558 	}
15559 
15560 	/* The FW expects the mac address write cmd to first be called with
15561 	 * one of these flags before calling it again with the multicast
15562 	 * enable flags.
15563 	 */
15564 	flags = I40E_AQC_WRITE_TYPE_LAA_WOL;
15565 
15566 	if (hw->func_caps.flex10_enable && hw->partition_id != 1)
15567 		flags = I40E_AQC_WRITE_TYPE_LAA_ONLY;
15568 
15569 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
15570 	if (ret) {
15571 		dev_err(&pf->pdev->dev,
15572 			"Failed to update MAC address registers; cannot enable Multicast Magic packet wake up");
15573 		return;
15574 	}
15575 
15576 	flags = I40E_AQC_MC_MAG_EN
15577 			| I40E_AQC_WOL_PRESERVE_ON_PFR
15578 			| I40E_AQC_WRITE_TYPE_UPDATE_MC_MAG;
15579 	ret = i40e_aq_mac_address_write(hw, flags, mac_addr, NULL);
15580 	if (ret)
15581 		dev_err(&pf->pdev->dev,
15582 			"Failed to enable Multicast Magic Packet wake up\n");
15583 }
15584 
15585 /**
15586  * i40e_shutdown - PCI callback for shutting down
15587  * @pdev: PCI device information struct
15588  **/
15589 static void i40e_shutdown(struct pci_dev *pdev)
15590 {
15591 	struct i40e_pf *pf = pci_get_drvdata(pdev);
15592 	struct i40e_hw *hw = &pf->hw;
15593 
15594 	set_bit(__I40E_SUSPENDED, pf->state);
15595 	set_bit(__I40E_DOWN, pf->state);
15596 
15597 	del_timer_sync(&pf->service_timer);
15598 	cancel_work_sync(&pf->service_task);
15599 	i40e_cloud_filter_exit(pf);
15600 	i40e_fdir_teardown(pf);
15601 
15602 	/* Client close must be called explicitly here because the timer
15603 	 * has been stopped.
15604 	 */
15605 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
15606 
15607 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
15608 		i40e_enable_mc_magic_wake(pf);
15609 
15610 	i40e_prep_for_reset(pf, false);
15611 
15612 	wr32(hw, I40E_PFPM_APM,
15613 	     (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
15614 	wr32(hw, I40E_PFPM_WUFC,
15615 	     (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
15616 
15617 	/* Free MSI/legacy interrupt 0 when in recovery mode. */
15618 	if (test_bit(__I40E_RECOVERY_MODE, pf->state) &&
15619 	    !(pf->flags & I40E_FLAG_MSIX_ENABLED))
15620 		free_irq(pf->pdev->irq, pf);
15621 
15622 	/* Since we're going to destroy queues during the
15623 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
15624 	 * whole section
15625 	 */
15626 	rtnl_lock();
15627 	i40e_clear_interrupt_scheme(pf);
15628 	rtnl_unlock();
15629 
15630 	if (system_state == SYSTEM_POWER_OFF) {
15631 		pci_wake_from_d3(pdev, pf->wol_en);
15632 		pci_set_power_state(pdev, PCI_D3hot);
15633 	}
15634 }
15635 
15636 /**
15637  * i40e_suspend - PM callback for moving to D3
15638  * @dev: generic device information structure
15639  **/
15640 static int __maybe_unused i40e_suspend(struct device *dev)
15641 {
15642 	struct i40e_pf *pf = dev_get_drvdata(dev);
15643 	struct i40e_hw *hw = &pf->hw;
15644 
15645 	/* If we're already suspended, then there is nothing to do */
15646 	if (test_and_set_bit(__I40E_SUSPENDED, pf->state))
15647 		return 0;
15648 
15649 	set_bit(__I40E_DOWN, pf->state);
15650 
15651 	/* Ensure service task will not be running */
15652 	del_timer_sync(&pf->service_timer);
15653 	cancel_work_sync(&pf->service_task);
15654 
15655 	/* Client close must be called explicitly here because the timer
15656 	 * has been stopped.
15657 	 */
15658 	i40e_notify_client_of_netdev_close(pf->vsi[pf->lan_vsi], false);
15659 
15660 	if (pf->wol_en && (pf->hw_features & I40E_HW_WOL_MC_MAGIC_PKT_WAKE))
15661 		i40e_enable_mc_magic_wake(pf);
15662 
15663 	/* Since we're going to destroy queues during the
15664 	 * i40e_clear_interrupt_scheme() we should hold the RTNL lock for this
15665 	 * whole section
15666 	 */
15667 	rtnl_lock();
15668 
15669 	i40e_prep_for_reset(pf, true);
15670 
15671 	wr32(hw, I40E_PFPM_APM, (pf->wol_en ? I40E_PFPM_APM_APME_MASK : 0));
15672 	wr32(hw, I40E_PFPM_WUFC, (pf->wol_en ? I40E_PFPM_WUFC_MAG_MASK : 0));
15673 
15674 	/* Clear the interrupt scheme and release our IRQs so that the system
15675 	 * can safely hibernate even when there are a large number of CPUs.
15676 	 * Otherwise hibernation might fail when mapping all the vectors back
15677 	 * to CPU0.
15678 	 */
15679 	i40e_clear_interrupt_scheme(pf);
15680 
15681 	rtnl_unlock();
15682 
15683 	return 0;
15684 }
15685 
15686 /**
15687  * i40e_resume - PM callback for waking up from D3
15688  * @dev: generic device information structure
15689  **/
15690 static int __maybe_unused i40e_resume(struct device *dev)
15691 {
15692 	struct i40e_pf *pf = dev_get_drvdata(dev);
15693 	int err;
15694 
15695 	/* If we're not suspended, then there is nothing to do */
15696 	if (!test_bit(__I40E_SUSPENDED, pf->state))
15697 		return 0;
15698 
15699 	/* We need to hold the RTNL lock prior to restoring interrupt schemes,
15700 	 * since we're going to be restoring queues
15701 	 */
15702 	rtnl_lock();
15703 
15704 	/* We cleared the interrupt scheme when we suspended, so we need to
15705 	 * restore it now to resume device functionality.
15706 	 */
15707 	err = i40e_restore_interrupt_scheme(pf);
15708 	if (err) {
15709 		dev_err(dev, "Cannot restore interrupt scheme: %d\n",
15710 			err);
15711 	}
15712 
15713 	clear_bit(__I40E_DOWN, pf->state);
15714 	i40e_reset_and_rebuild(pf, false, true);
15715 
15716 	rtnl_unlock();
15717 
15718 	/* Clear suspended state last after everything is recovered */
15719 	clear_bit(__I40E_SUSPENDED, pf->state);
15720 
15721 	/* Restart the service task */
15722 	mod_timer(&pf->service_timer,
15723 		  round_jiffies(jiffies + pf->service_timer_period));
15724 
15725 	return 0;
15726 }
15727 
15728 static const struct pci_error_handlers i40e_err_handler = {
15729 	.error_detected = i40e_pci_error_detected,
15730 	.slot_reset = i40e_pci_error_slot_reset,
15731 	.reset_prepare = i40e_pci_error_reset_prepare,
15732 	.reset_done = i40e_pci_error_reset_done,
15733 	.resume = i40e_pci_error_resume,
15734 };
15735 
15736 static SIMPLE_DEV_PM_OPS(i40e_pm_ops, i40e_suspend, i40e_resume);
15737 
15738 static struct pci_driver i40e_driver = {
15739 	.name     = i40e_driver_name,
15740 	.id_table = i40e_pci_tbl,
15741 	.probe    = i40e_probe,
15742 	.remove   = i40e_remove,
15743 	.driver   = {
15744 		.pm = &i40e_pm_ops,
15745 	},
15746 	.shutdown = i40e_shutdown,
15747 	.err_handler = &i40e_err_handler,
15748 	.sriov_configure = i40e_pci_sriov_configure,
15749 };
15750 
15751 /**
15752  * i40e_init_module - Driver registration routine
15753  *
15754  * i40e_init_module is the first routine called when the driver is
15755  * loaded. All it does is register with the PCI subsystem.
15756  **/
15757 static int __init i40e_init_module(void)
15758 {
15759 	pr_info("%s: %s - version %s\n", i40e_driver_name,
15760 		i40e_driver_string, i40e_driver_version_str);
15761 	pr_info("%s: %s\n", i40e_driver_name, i40e_copyright);
15762 
15763 	/* There is no need to throttle the number of active tasks because
15764 	 * each device limits its own task using a state bit for scheduling
15765 	 * the service task, and the device tasks do not interfere with each
15766 	 * other, so we don't set a max task limit. We must set WQ_MEM_RECLAIM
15767 	 * since we need to be able to guarantee forward progress even under
15768 	 * memory pressure.
15769 	 */
15770 	i40e_wq = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0, i40e_driver_name);
15771 	if (!i40e_wq) {
15772 		pr_err("%s: Failed to create workqueue\n", i40e_driver_name);
15773 		return -ENOMEM;
15774 	}
15775 
15776 	i40e_dbg_init();
15777 	return pci_register_driver(&i40e_driver);
15778 }
15779 module_init(i40e_init_module);
15780 
15781 /**
15782  * i40e_exit_module - Driver exit cleanup routine
15783  *
15784  * i40e_exit_module is called just before the driver is removed
15785  * from memory.
15786  **/
15787 static void __exit i40e_exit_module(void)
15788 {
15789 	pci_unregister_driver(&i40e_driver);
15790 	destroy_workqueue(i40e_wq);
15791 	i40e_dbg_exit();
15792 }
15793 module_exit(i40e_exit_module);
15794